qid
int64 1
74.7M
| question
stringlengths 15
55.4k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 2
32.4k
| response_k
stringlengths 9
40.5k
|
---|---|---|---|---|---|
53,179,085 | I'm writing a code using Java Swing to press the right button when I type a number key.
But I can't find what I want through search.
This is my code and I can't understand why this isn't working.
Please help me..
```
import javax.swing.*;
import java.awt.Dimension;
import java.awt.event.*;
class class01 {
public static void main(String[] args) {
JFrame f = new JFrame("Key event test");
f.setSize(230, 500);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
JButton button1 = new JButton("Coffe");
button1.setSize(100, 100);
button1.setLocation(0, 0);
JButton button2 = new JButton("Latte");
button2.setSize(100, 100);
button2.setLocation(0, 100);
JButton button3 = new JButton("Espresso");
button3.setSize(100, 100);
button3.setLocation(100, 100);
JButton button4 = new JButton("Vanilla Latte");
button4.setSize(100, 100);
button4.setLocation(100, 0);
f.add(button1);
f.add(button2);
f.add(button3);
f.add(button4);
// Show message when the corresponding button is pressed.
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button1.keyPressed(KeyEvent.VK_1);
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button2.keyPressed(KeyEvent.VK_2);
JOptionPane.showMessageDialog(f.getComponent(0), "Latte selected");
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button3.keyPressed(KeyEvent.VK_3);
JOptionPane.showMessageDialog(f.getComponent(0), "Espresso selected");
}
});
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button4.keyPressed(KeyEvent.VK_4);
JOptionPane.showMessageDialog(f.getComponent(0), "Vanilla Latte selected");
}
});
}
}
``` | 2018/11/06 | [
"https://Stackoverflow.com/questions/53179085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8933767/"
] | The code you are showing does exactly one thing: attach action listeners to your buttons..
Meaning: when you click the button, then the listener will be called.
You need a generic keyboard listener that translates key events into calls to the appropriate button, respectively action listener instead. | When you do this:
```
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button1.keyPressed(KeyEvent.VK_1);
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
});
```
You are telling `button1` what to do when somebody clicks on the button. The line with `keyPressed` should not be there (it does not compile even).
What you need to do is listen for key presses by adding a `KeyListener` to the frame like this:
```
f.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if( e.getKeyChar() == KeyEvent.VK_1) {
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
}
});
```
I repeated the `showMessageDialog`, but you should extract the actual logic into a method and call that method from within the `KeyListener` on the frame and the `ActionListener` on the button. |
53,179,085 | I'm writing a code using Java Swing to press the right button when I type a number key.
But I can't find what I want through search.
This is my code and I can't understand why this isn't working.
Please help me..
```
import javax.swing.*;
import java.awt.Dimension;
import java.awt.event.*;
class class01 {
public static void main(String[] args) {
JFrame f = new JFrame("Key event test");
f.setSize(230, 500);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
JButton button1 = new JButton("Coffe");
button1.setSize(100, 100);
button1.setLocation(0, 0);
JButton button2 = new JButton("Latte");
button2.setSize(100, 100);
button2.setLocation(0, 100);
JButton button3 = new JButton("Espresso");
button3.setSize(100, 100);
button3.setLocation(100, 100);
JButton button4 = new JButton("Vanilla Latte");
button4.setSize(100, 100);
button4.setLocation(100, 0);
f.add(button1);
f.add(button2);
f.add(button3);
f.add(button4);
// Show message when the corresponding button is pressed.
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button1.keyPressed(KeyEvent.VK_1);
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button2.keyPressed(KeyEvent.VK_2);
JOptionPane.showMessageDialog(f.getComponent(0), "Latte selected");
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button3.keyPressed(KeyEvent.VK_3);
JOptionPane.showMessageDialog(f.getComponent(0), "Espresso selected");
}
});
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button4.keyPressed(KeyEvent.VK_4);
JOptionPane.showMessageDialog(f.getComponent(0), "Vanilla Latte selected");
}
});
}
}
``` | 2018/11/06 | [
"https://Stackoverflow.com/questions/53179085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8933767/"
] | From what I understand, essentially you want to have the same operation of a button assigned to a specific key stroke.
Things you want to avoid are `KeyListener`, especially because you have other focusable components in the view, namely buttons, which will steal keyboard focus and render the `KeyListener` useless. This is why, in almost all cases, you want to avoid `KeyListener`.
A better and more reliable solution would be to use the [Key Bindings API](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html), which overcomes this focus related issue, but it also encourages the use of reusable components of work through the [`Action`s API](https://docs.oracle.com/javase/tutorial/uiswing/misc/action.html)
Something like...
```
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.StringJoiner;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JTextField field = new JTextField(10);
field.setEditable(false);
field.setFocusable(false);
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), "Pressed.One");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_2, 0), "Pressed.Two");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_3, 0), "Pressed.Three");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_4, 0), "Pressed.Four");
am.put("Pressed.One", new OrderAction(1, field));
am.put("Pressed.Two", new OrderAction(2, field));
am.put("Pressed.Three", new OrderAction(3, field));
am.put("Pressed.Four", new OrderAction(4, field));
JButton btnOne = new JButton(new OrderAction(1, field));
JButton btnTwo = new JButton(new OrderAction(2, field));
JButton btnThree = new JButton(new OrderAction(3, field));
JButton btnFour = new JButton(new OrderAction(4, field));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
add(btnOne, gbc);
gbc.gridx++;
add(btnTwo, gbc);
gbc.gridx = 0;
gbc.gridy++;
add(btnThree, gbc);
gbc.gridx++;
add(btnFour, gbc);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
add(field, gbc);
}
protected class OrderAction extends AbstractAction {
private int value;
private JTextField field;
public OrderAction(int value, JTextField field) {
this.value = value;
this.field = field;
switch (value) {
case 1:
putValue(NAME, "Coffe");
break;
case 2:
putValue(NAME, "Latte");
break;
case 3:
putValue(NAME, "Espresso");
break;
case 4:
putValue(NAME, "Vanilla Latte");
break;
}
}
@Override
public void actionPerformed(ActionEvent e) {
StringJoiner sj = new StringJoiner("; ");
if (field.getText() != null && field.getText().length() > 0) {
sj.add(field.getText());
}
sj.add(Integer.toString(value));
field.setText(sj.toString());
}
}
}
}
```
Note, you could apply the key bindings directly to each button instead
Now, if you want to "visually" press the button on a key stroke, I would recommend either creating a custom `JButton` or factory method, which could allow for a more simplified implementation, but the basic idea would be to define a key binding and `Action` which simply called the buttons `doClick` method, for example
```
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.StringJoiner;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JTextField field = new JTextField(10);
field.setEditable(false);
field.setFocusable(false);
JButton btnOne = new JButton(new OrderAction(1, field));
JButton btnTwo = new JButton(new OrderAction(2, field));
JButton btnThree = new JButton(new OrderAction(3, field));
JButton btnFour = new JButton(new OrderAction(4, field));
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), "Pressed.One");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_2, 0), "Pressed.Two");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_3, 0), "Pressed.Three");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_4, 0), "Pressed.Four");
am.put("Pressed.One", new ProxyAction(btnOne));
am.put("Pressed.Two", new ProxyAction(btnTwo));
am.put("Pressed.Three", new ProxyAction(btnThree));
am.put("Pressed.Four", new ProxyAction(btnFour));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
add(btnOne, gbc);
gbc.gridx++;
add(btnTwo, gbc);
gbc.gridx = 0;
gbc.gridy++;
add(btnThree, gbc);
gbc.gridx++;
add(btnFour, gbc);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
add(field, gbc);
}
protected class ProxyAction extends AbstractAction {
private JButton btn;
public ProxyAction(JButton btn) {
this.btn = btn;
}
@Override
public void actionPerformed(ActionEvent e) {
btn.doClick();
}
}
protected class OrderAction extends AbstractAction {
private int value;
private JTextField field;
public OrderAction(int value, JTextField field) {
this.value = value;
this.field = field;
switch (value) {
case 1:
putValue(NAME, "Coffe");
break;
case 2:
putValue(NAME, "Latte");
break;
case 3:
putValue(NAME, "Espresso");
break;
case 4:
putValue(NAME, "Vanilla Latte");
break;
}
}
@Override
public void actionPerformed(ActionEvent e) {
StringJoiner sj = new StringJoiner("; ");
if (field.getText() != null && field.getText().length() > 0) {
sj.add(field.getText());
}
sj.add(Integer.toString(value));
field.setText(sj.toString());
}
}
}
}
``` | When you do this:
```
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button1.keyPressed(KeyEvent.VK_1);
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
});
```
You are telling `button1` what to do when somebody clicks on the button. The line with `keyPressed` should not be there (it does not compile even).
What you need to do is listen for key presses by adding a `KeyListener` to the frame like this:
```
f.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if( e.getKeyChar() == KeyEvent.VK_1) {
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
}
});
```
I repeated the `showMessageDialog`, but you should extract the actual logic into a method and call that method from within the `KeyListener` on the frame and the `ActionListener` on the button. |
213,173 | I am a senior Siebel CRM developer having more than 8 years of working experience. Now, I am very keen and excited to learn Salesforce and get certified as soon as possible.
Please guide me where to start from scratch ? | 2018/03/29 | [
"https://salesforce.stackexchange.com/questions/213173",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/55249/"
] | After some research and not reaching to any solution, I refreshed the selected Business Units by removing them, saving and the adding and saving again. This solved my issue. | You may need to raise the case with SFMC support. I have seen these issues, and support needs to toggle some backend settings to reset the SC and SFMC connection. |
6,763,429 | i want to write a shape with " \* " and " | " the shape is below.
The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5
```
|*____|
|_*___|
|__*__|
|___*_|
|____*|
|___*_|
|__*__|
|_*___|
|*____|
|_*___|
```
```
private static void Function()
{
int height, width;
if (width == 2)
while (height > 0)
{
FirstPart(width, height);
height -= width;
}
else
while (height > 0)
{
if (height > 1)
{
FirstPart(width, height);
height -= width;
}
if (height > 0)
{
SecondPart(width, height);
height -= width - 2;
}
}
}
private static void FirstPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
private static void SecondPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width-2; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width-1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width - 1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
``` | 2011/07/20 | [
"https://Stackoverflow.com/questions/6763429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852118/"
] | I see a
```
while (Height > 0)
```
so your infinite loop is coming from Height never getting less or equal to 0. | It's better to rewrite. When you do, decouple the code into several functions so that one function draws a single line, and another one calls the former to draw all the lines. |
6,763,429 | i want to write a shape with " \* " and " | " the shape is below.
The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5
```
|*____|
|_*___|
|__*__|
|___*_|
|____*|
|___*_|
|__*__|
|_*___|
|*____|
|_*___|
```
```
private static void Function()
{
int height, width;
if (width == 2)
while (height > 0)
{
FirstPart(width, height);
height -= width;
}
else
while (height > 0)
{
if (height > 1)
{
FirstPart(width, height);
height -= width;
}
if (height > 0)
{
SecondPart(width, height);
height -= width - 2;
}
}
}
private static void FirstPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
private static void SecondPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width-2; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width-1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width - 1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
``` | 2011/07/20 | [
"https://Stackoverflow.com/questions/6763429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852118/"
] | I see a
```
while (Height > 0)
```
so your infinite loop is coming from Height never getting less or equal to 0. | ```
void WriteStars(int Width,int Height)
{
int _sp=1; //Star Pos
bool _left = false;
for(int i =0;i<Height;i++)
{
Console.Write("|");
int j;
for(j=1;j<Width-1;j++)
{
if(j==_sp)
{
Console.Write("*");
if(_left)
{
_sp--;
}
else
{
_sp++;
}
j++;
break;
}
else
{
Console.Write("_");
}
}
for(;j<Width-1;j++)
{
Console.Write("_");
}
Console.WriteLine("|");
if(_sp==0)
{
_left = false;
}
else if(_sp==Width)
{
_left = true;
}
}
}
```
Try if it works, wrote it right here. |
6,763,429 | i want to write a shape with " \* " and " | " the shape is below.
The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5
```
|*____|
|_*___|
|__*__|
|___*_|
|____*|
|___*_|
|__*__|
|_*___|
|*____|
|_*___|
```
```
private static void Function()
{
int height, width;
if (width == 2)
while (height > 0)
{
FirstPart(width, height);
height -= width;
}
else
while (height > 0)
{
if (height > 1)
{
FirstPart(width, height);
height -= width;
}
if (height > 0)
{
SecondPart(width, height);
height -= width - 2;
}
}
}
private static void FirstPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
private static void SecondPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width-2; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width-1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width - 1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
``` | 2011/07/20 | [
"https://Stackoverflow.com/questions/6763429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852118/"
] | ```
private static void WriteStars(int width, int height)
{
int j = 0;
for (int i = 0; i < height; i++)
{
Console.Write("|");
for (int f = 0; f < width; f++)
{
if (f == Math.Abs(j))
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
j++;
if (Math.Abs(j) == width - 1)
{
j *= -1;
}
Console.WriteLine("|");
}
}
```
Probably going to get downvoted for giving you a complete answer, but maybe it'll show you one correct approach and you can learn something from it... | I see a
```
while (Height > 0)
```
so your infinite loop is coming from Height never getting less or equal to 0. |
6,763,429 | i want to write a shape with " \* " and " | " the shape is below.
The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5
```
|*____|
|_*___|
|__*__|
|___*_|
|____*|
|___*_|
|__*__|
|_*___|
|*____|
|_*___|
```
```
private static void Function()
{
int height, width;
if (width == 2)
while (height > 0)
{
FirstPart(width, height);
height -= width;
}
else
while (height > 0)
{
if (height > 1)
{
FirstPart(width, height);
height -= width;
}
if (height > 0)
{
SecondPart(width, height);
height -= width - 2;
}
}
}
private static void FirstPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
private static void SecondPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width-2; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width-1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width - 1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
``` | 2011/07/20 | [
"https://Stackoverflow.com/questions/6763429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852118/"
] | I see a
```
while (Height > 0)
```
so your infinite loop is coming from Height never getting less or equal to 0. | even shorter:
```
static void Variante_2(int height, int width)
{
byte[][] arr = new byte[height][];
int pos = 0;
int mov = 1;
for (int line = 0; line < height; line++)
{
arr[line] = new byte[width];
for (int col = 0; col < width; col++) { arr[line][col] = 45; }
arr[line][pos] = 42;
pos += mov;
if (pos == 0 || pos == (width - 1)) { mov *= -1; }
Console.WriteLine("|" + ASCIIEncoding.ASCII.GetString(arr[line]) + "|");
}
string temp = Console.ReadLine();
}
``` |
6,763,429 | i want to write a shape with " \* " and " | " the shape is below.
The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5
```
|*____|
|_*___|
|__*__|
|___*_|
|____*|
|___*_|
|__*__|
|_*___|
|*____|
|_*___|
```
```
private static void Function()
{
int height, width;
if (width == 2)
while (height > 0)
{
FirstPart(width, height);
height -= width;
}
else
while (height > 0)
{
if (height > 1)
{
FirstPart(width, height);
height -= width;
}
if (height > 0)
{
SecondPart(width, height);
height -= width - 2;
}
}
}
private static void FirstPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
private static void SecondPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width-2; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width-1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width - 1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
``` | 2011/07/20 | [
"https://Stackoverflow.com/questions/6763429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852118/"
] | I see a
```
while (Height > 0)
```
so your infinite loop is coming from Height never getting less or equal to 0. | and it is possible to do it with less code:
```
static void Variante_3(int height, int width)
{
int pos = 1;
int mov = 1;
for (int line = 0; line < height; line++)
{
Console.WriteLine("|" + "*".PadLeft(pos, '_') + "|".PadLeft(width - pos, '_'));
pos += mov;
if (pos == 1 || pos == (width - 1)) { mov *= -1; }
}
string temp = Console.ReadLine();
}
```
Sorry to all not doing others homework, but I couldn´t sleep without showing this *g* |
6,763,429 | i want to write a shape with " \* " and " | " the shape is below.
The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5
```
|*____|
|_*___|
|__*__|
|___*_|
|____*|
|___*_|
|__*__|
|_*___|
|*____|
|_*___|
```
```
private static void Function()
{
int height, width;
if (width == 2)
while (height > 0)
{
FirstPart(width, height);
height -= width;
}
else
while (height > 0)
{
if (height > 1)
{
FirstPart(width, height);
height -= width;
}
if (height > 0)
{
SecondPart(width, height);
height -= width - 2;
}
}
}
private static void FirstPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
private static void SecondPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width-2; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width-1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width - 1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
``` | 2011/07/20 | [
"https://Stackoverflow.com/questions/6763429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852118/"
] | ```
private static void WriteStars(int width, int height)
{
int j = 0;
for (int i = 0; i < height; i++)
{
Console.Write("|");
for (int f = 0; f < width; f++)
{
if (f == Math.Abs(j))
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
j++;
if (Math.Abs(j) == width - 1)
{
j *= -1;
}
Console.WriteLine("|");
}
}
```
Probably going to get downvoted for giving you a complete answer, but maybe it'll show you one correct approach and you can learn something from it... | It's better to rewrite. When you do, decouple the code into several functions so that one function draws a single line, and another one calls the former to draw all the lines. |
6,763,429 | i want to write a shape with " \* " and " | " the shape is below.
The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5
```
|*____|
|_*___|
|__*__|
|___*_|
|____*|
|___*_|
|__*__|
|_*___|
|*____|
|_*___|
```
```
private static void Function()
{
int height, width;
if (width == 2)
while (height > 0)
{
FirstPart(width, height);
height -= width;
}
else
while (height > 0)
{
if (height > 1)
{
FirstPart(width, height);
height -= width;
}
if (height > 0)
{
SecondPart(width, height);
height -= width - 2;
}
}
}
private static void FirstPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
private static void SecondPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width-2; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width-1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width - 1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
``` | 2011/07/20 | [
"https://Stackoverflow.com/questions/6763429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852118/"
] | ```
private static void WriteStars(int width, int height)
{
int j = 0;
for (int i = 0; i < height; i++)
{
Console.Write("|");
for (int f = 0; f < width; f++)
{
if (f == Math.Abs(j))
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
j++;
if (Math.Abs(j) == width - 1)
{
j *= -1;
}
Console.WriteLine("|");
}
}
```
Probably going to get downvoted for giving you a complete answer, but maybe it'll show you one correct approach and you can learn something from it... | ```
void WriteStars(int Width,int Height)
{
int _sp=1; //Star Pos
bool _left = false;
for(int i =0;i<Height;i++)
{
Console.Write("|");
int j;
for(j=1;j<Width-1;j++)
{
if(j==_sp)
{
Console.Write("*");
if(_left)
{
_sp--;
}
else
{
_sp++;
}
j++;
break;
}
else
{
Console.Write("_");
}
}
for(;j<Width-1;j++)
{
Console.Write("_");
}
Console.WriteLine("|");
if(_sp==0)
{
_left = false;
}
else if(_sp==Width)
{
_left = true;
}
}
}
```
Try if it works, wrote it right here. |
6,763,429 | i want to write a shape with " \* " and " | " the shape is below.
The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5
```
|*____|
|_*___|
|__*__|
|___*_|
|____*|
|___*_|
|__*__|
|_*___|
|*____|
|_*___|
```
```
private static void Function()
{
int height, width;
if (width == 2)
while (height > 0)
{
FirstPart(width, height);
height -= width;
}
else
while (height > 0)
{
if (height > 1)
{
FirstPart(width, height);
height -= width;
}
if (height > 0)
{
SecondPart(width, height);
height -= width - 2;
}
}
}
private static void FirstPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
private static void SecondPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width-2; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width-1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width - 1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
``` | 2011/07/20 | [
"https://Stackoverflow.com/questions/6763429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852118/"
] | ```
private static void WriteStars(int width, int height)
{
int j = 0;
for (int i = 0; i < height; i++)
{
Console.Write("|");
for (int f = 0; f < width; f++)
{
if (f == Math.Abs(j))
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
j++;
if (Math.Abs(j) == width - 1)
{
j *= -1;
}
Console.WriteLine("|");
}
}
```
Probably going to get downvoted for giving you a complete answer, but maybe it'll show you one correct approach and you can learn something from it... | even shorter:
```
static void Variante_2(int height, int width)
{
byte[][] arr = new byte[height][];
int pos = 0;
int mov = 1;
for (int line = 0; line < height; line++)
{
arr[line] = new byte[width];
for (int col = 0; col < width; col++) { arr[line][col] = 45; }
arr[line][pos] = 42;
pos += mov;
if (pos == 0 || pos == (width - 1)) { mov *= -1; }
Console.WriteLine("|" + ASCIIEncoding.ASCII.GetString(arr[line]) + "|");
}
string temp = Console.ReadLine();
}
``` |
6,763,429 | i want to write a shape with " \* " and " | " the shape is below.
The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5
```
|*____|
|_*___|
|__*__|
|___*_|
|____*|
|___*_|
|__*__|
|_*___|
|*____|
|_*___|
```
```
private static void Function()
{
int height, width;
if (width == 2)
while (height > 0)
{
FirstPart(width, height);
height -= width;
}
else
while (height > 0)
{
if (height > 1)
{
FirstPart(width, height);
height -= width;
}
if (height > 0)
{
SecondPart(width, height);
height -= width - 2;
}
}
}
private static void FirstPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + 1 == j)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
private static void SecondPart(int width,int height)
{
if(height > width)
for (int i = 0; i < width-2; i++)
{
for (int j = 0; j < width+2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width-1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
else
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width + 2; j++)
{
if (j == 0 || j == width + 1)
Console.Write("|");
else
if (i + j == width - 1)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine();
}
}
``` | 2011/07/20 | [
"https://Stackoverflow.com/questions/6763429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852118/"
] | ```
private static void WriteStars(int width, int height)
{
int j = 0;
for (int i = 0; i < height; i++)
{
Console.Write("|");
for (int f = 0; f < width; f++)
{
if (f == Math.Abs(j))
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
j++;
if (Math.Abs(j) == width - 1)
{
j *= -1;
}
Console.WriteLine("|");
}
}
```
Probably going to get downvoted for giving you a complete answer, but maybe it'll show you one correct approach and you can learn something from it... | and it is possible to do it with less code:
```
static void Variante_3(int height, int width)
{
int pos = 1;
int mov = 1;
for (int line = 0; line < height; line++)
{
Console.WriteLine("|" + "*".PadLeft(pos, '_') + "|".PadLeft(width - pos, '_'));
pos += mov;
if (pos == 1 || pos == (width - 1)) { mov *= -1; }
}
string temp = Console.ReadLine();
}
```
Sorry to all not doing others homework, but I couldn´t sleep without showing this *g* |
62,851,314 | Let me explain what is happening:
* Database: Oracle 19c
* Apex: 19.1.0.00.15
* ORDS standalone is 19.1.0.r0921545
I did the tasks to configure an Apex Social Sign In to Microsoft AAD without almost any issue:
* I created the authentication method in Apex.
* I register my application and get the web credentials in Azure.
* I created a wallet in my database with the root CA Microsoft certificates and configured the instance settings to usee that wallet.
* My wallet in the database server contains the property auto\_login to avoid using passwords.
* I created the ACEs entries to allow connection to the login.microsoftonline.com in the port 443
* Although it is not important for the purpose of the question itself and the error that is producing, just comment that I configured the wallet settings in the internal workspace in order to provide access to the wallet to the apex applications.
For some weeks the process was working fine, I was having a perfect Single Sing on mechanism for all my apex applications in the different workspaces. However, since some days ago, I am getting always the same error:
**ORA-29024: Certificate validation failure**
After some digging I realise that someone has configured a PROXY for outgoing traffic. Before even trying in Apex, I tried in SQL using APEX\_WEB\_SERVICE
Request with proxy settings to login.microsoftonline.com
```
select apex_web_service.make_rest_request(
p_url => 'https://login.microsoftonline.com',
p_http_method => 'GET',
p_wallet_path => 'file:/home/oracle/wallet',
p_wallet_pwd => 'MyPassword' ,
p_proxy_override => 'http://myproxy:myport'
7 ) from dual;
ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1035
ORA-29024: Certificate validation failure
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1148
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 934
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1580
ORA-06512: at "APEX_190100.WWV_FLOW_WEBSERVICES_API", line 408
ORA-06512: at line 1
```
Request without proxy settings, just to see if I can get there
```
SQL> select apex_web_service.make_rest_request(
2 p_url => 'https://login.microsoftonline.com',
3 p_http_method => 'GET',
4 p_wallet_path => 'file:/home/oracle/wallet'
5* ) from dual
SQL> /
ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1035
ORA-29024: Certificate validation failure
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1148
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 934
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1580
ORA-06512: at "APEX_190100.WWV_FLOW_WEBSERVICES_API", line 408
ORA-06512: at line 1
```
Request to google using Proxy settings
```
select apex_web_service.make_rest_request(
p_url => 'https://google.com',
p_http_method => 'GET',
p_wallet_path => 'file:/home/oracle/wallet',
p_wallet_pwd => 'MyPassword' ,
6 p_proxy_override => 'http://myproxy:myport'
7 ) from dual ;
ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1035
ORA-29024: Certificate validation failure
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1148
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 934
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1580
ORA-06512: at "APEX_190100.WWV_FLOW_WEBSERVICES_API", line 408
ORA-06512: at line 1
```
Request to google without proxy settings
```
SQL> select apex_web_service.make_rest_request(
2 p_url => 'https://google.com',
3 p_http_method => 'GET',
4 p_wallet_path => 'file:/home/oracle/wallet'
5* ) from dual
SQL> /
ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1035
ORA-12535: TNS:operation timed out
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1148
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 934
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1580
ORA-06512: at "APEX_190100.WWV_FLOW_WEBSERVICES_API", line 408
ORA-06512: at line 1
```
My questions are the following:
* It is a network problem or a proxy issue regarding inbound/outbound
traffic ? I can reach Microsoft but not Google in the port 443 when I don't specify proxy.
* Why am I getting invalid certificate when it has nothing to do with
the certificates ?
* How can I setup my APEX to use authentication on Azure or any other
provider for that matter when I have a proxy in the middle ?
* As I use ORDS standalone, am I allow to keep using it or I need a
reverse proxy with Tomcat ?
I tried to configure the ACE to use HTTP\_PROXY in the ports by running
```
begin
sys.dbms_network_acl_admin.append_host_ace(
host => 'myproxyserver'
,lower_port => 8080
,upper_port => 8080
,ace => xs$ace_type(
privilege_list => xs$name_list('http_proxy')
,granted => true
,principal_name => 'MY_PRINCIPAL'
,principal_type => XS_ACL.PTYPE_DB
)
);
end;
/
```
Even I grant to the ACE privileges over the wallet
```
SET SERVEROUTPUT ON
BEGIN
DBMS_NETWORK_ACL_ADMIN.APPEND_WALLET_ACE
(
WALLET_PATH => 'file:/home/oracle/wallet',
ACE => XS$ACE_TYPE(
PRIVILEGE_LIST => XS$NAME_LIST('use_passwords','use_client_certificates'),
PRINCIPAL_NAME => 'MY_PRINCIPAL',
PRINCIPAL_TYPE => XS_ACL.PTYPE_DB
)
);
EXCEPTION WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error while configuring ACL for wallet: '|| SQLERRM);
END;
/
```
but I am still getting the same error all over.
Any help would be appreciated!
Thank you | 2020/07/11 | [
"https://Stackoverflow.com/questions/62851314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13755538/"
] | I had issue like this, it seems Oracle SSL library has some bugs. Finally I implemented some Java Source for OJVM, please read my answer here: <https://stackoverflow.com/a/60152830/11272044> | In my understanding,you will need to do following(in addition to what you did) :
1. login to Apex as administrator
2. From settings, go to 'Wallet'
3. Add Wallet path(absolute path with prefix 'file://' and password you used for creating wallet
Now, your problem should be solved. |
62,851,314 | Let me explain what is happening:
* Database: Oracle 19c
* Apex: 19.1.0.00.15
* ORDS standalone is 19.1.0.r0921545
I did the tasks to configure an Apex Social Sign In to Microsoft AAD without almost any issue:
* I created the authentication method in Apex.
* I register my application and get the web credentials in Azure.
* I created a wallet in my database with the root CA Microsoft certificates and configured the instance settings to usee that wallet.
* My wallet in the database server contains the property auto\_login to avoid using passwords.
* I created the ACEs entries to allow connection to the login.microsoftonline.com in the port 443
* Although it is not important for the purpose of the question itself and the error that is producing, just comment that I configured the wallet settings in the internal workspace in order to provide access to the wallet to the apex applications.
For some weeks the process was working fine, I was having a perfect Single Sing on mechanism for all my apex applications in the different workspaces. However, since some days ago, I am getting always the same error:
**ORA-29024: Certificate validation failure**
After some digging I realise that someone has configured a PROXY for outgoing traffic. Before even trying in Apex, I tried in SQL using APEX\_WEB\_SERVICE
Request with proxy settings to login.microsoftonline.com
```
select apex_web_service.make_rest_request(
p_url => 'https://login.microsoftonline.com',
p_http_method => 'GET',
p_wallet_path => 'file:/home/oracle/wallet',
p_wallet_pwd => 'MyPassword' ,
p_proxy_override => 'http://myproxy:myport'
7 ) from dual;
ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1035
ORA-29024: Certificate validation failure
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1148
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 934
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1580
ORA-06512: at "APEX_190100.WWV_FLOW_WEBSERVICES_API", line 408
ORA-06512: at line 1
```
Request without proxy settings, just to see if I can get there
```
SQL> select apex_web_service.make_rest_request(
2 p_url => 'https://login.microsoftonline.com',
3 p_http_method => 'GET',
4 p_wallet_path => 'file:/home/oracle/wallet'
5* ) from dual
SQL> /
ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1035
ORA-29024: Certificate validation failure
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1148
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 934
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1580
ORA-06512: at "APEX_190100.WWV_FLOW_WEBSERVICES_API", line 408
ORA-06512: at line 1
```
Request to google using Proxy settings
```
select apex_web_service.make_rest_request(
p_url => 'https://google.com',
p_http_method => 'GET',
p_wallet_path => 'file:/home/oracle/wallet',
p_wallet_pwd => 'MyPassword' ,
6 p_proxy_override => 'http://myproxy:myport'
7 ) from dual ;
ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1035
ORA-29024: Certificate validation failure
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1148
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 934
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1580
ORA-06512: at "APEX_190100.WWV_FLOW_WEBSERVICES_API", line 408
ORA-06512: at line 1
```
Request to google without proxy settings
```
SQL> select apex_web_service.make_rest_request(
2 p_url => 'https://google.com',
3 p_http_method => 'GET',
4 p_wallet_path => 'file:/home/oracle/wallet'
5* ) from dual
SQL> /
ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1035
ORA-12535: TNS:operation timed out
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1148
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 934
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1580
ORA-06512: at "APEX_190100.WWV_FLOW_WEBSERVICES_API", line 408
ORA-06512: at line 1
```
My questions are the following:
* It is a network problem or a proxy issue regarding inbound/outbound
traffic ? I can reach Microsoft but not Google in the port 443 when I don't specify proxy.
* Why am I getting invalid certificate when it has nothing to do with
the certificates ?
* How can I setup my APEX to use authentication on Azure or any other
provider for that matter when I have a proxy in the middle ?
* As I use ORDS standalone, am I allow to keep using it or I need a
reverse proxy with Tomcat ?
I tried to configure the ACE to use HTTP\_PROXY in the ports by running
```
begin
sys.dbms_network_acl_admin.append_host_ace(
host => 'myproxyserver'
,lower_port => 8080
,upper_port => 8080
,ace => xs$ace_type(
privilege_list => xs$name_list('http_proxy')
,granted => true
,principal_name => 'MY_PRINCIPAL'
,principal_type => XS_ACL.PTYPE_DB
)
);
end;
/
```
Even I grant to the ACE privileges over the wallet
```
SET SERVEROUTPUT ON
BEGIN
DBMS_NETWORK_ACL_ADMIN.APPEND_WALLET_ACE
(
WALLET_PATH => 'file:/home/oracle/wallet',
ACE => XS$ACE_TYPE(
PRIVILEGE_LIST => XS$NAME_LIST('use_passwords','use_client_certificates'),
PRINCIPAL_NAME => 'MY_PRINCIPAL',
PRINCIPAL_TYPE => XS_ACL.PTYPE_DB
)
);
EXCEPTION WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error while configuring ACL for wallet: '|| SQLERRM);
END;
/
```
but I am still getting the same error all over.
Any help would be appreciated!
Thank you | 2020/07/11 | [
"https://Stackoverflow.com/questions/62851314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13755538/"
] | Thank you to all who post answers, but finally, after struggling for a while, I found the root cause. Actually Oracle was right after all, as Microsoft has changed the way the authentication is handled, either you are using Oauth2 or OpenID, when you use Office365 and Azure Active Directory.
In this case, my organisation is using Office 365 and at the beginning was enough with importing the PKI certificates from :
<https://www.microsoft.com/pki/mscorp/cps/default.htm>
After a change done in Azure Active Directory (AAD), you now need also the Global Sign certificates from [office.com](http://office.com)
I hope it clarifies to other users who got in the same problem trying to authenticate with Azure Active Directory using Apex Social sign in.
You can download the certificates directly from office365.com
[![enter image description here](https://i.stack.imgur.com/zkbq2.png)](https://i.stack.imgur.com/zkbq2.png)
After adding the new two certificates to the wallet, you can now enter without issues:
```
select apex_web_service.make_rest_request(
p_url => 'https://login.microsoftonline.com',
p_http_method => 'GET',
4 p_wallet_path => 'file:/home/oracle/wallet' ) from dual ;
APEX_WEB_SERVICE.MAKE_REST_REQUEST(P_URL=>'HTTPS://LOGIN.MICROSOFTONLINE.COM',P_
--------------------------------------------------------------------------------
<!-- Copyright (C) Microsoft Corporation. All rights reserved. -->
<!DOCTYP
SQL>
``` | In my understanding,you will need to do following(in addition to what you did) :
1. login to Apex as administrator
2. From settings, go to 'Wallet'
3. Add Wallet path(absolute path with prefix 'file://' and password you used for creating wallet
Now, your problem should be solved. |
62,851,314 | Let me explain what is happening:
* Database: Oracle 19c
* Apex: 19.1.0.00.15
* ORDS standalone is 19.1.0.r0921545
I did the tasks to configure an Apex Social Sign In to Microsoft AAD without almost any issue:
* I created the authentication method in Apex.
* I register my application and get the web credentials in Azure.
* I created a wallet in my database with the root CA Microsoft certificates and configured the instance settings to usee that wallet.
* My wallet in the database server contains the property auto\_login to avoid using passwords.
* I created the ACEs entries to allow connection to the login.microsoftonline.com in the port 443
* Although it is not important for the purpose of the question itself and the error that is producing, just comment that I configured the wallet settings in the internal workspace in order to provide access to the wallet to the apex applications.
For some weeks the process was working fine, I was having a perfect Single Sing on mechanism for all my apex applications in the different workspaces. However, since some days ago, I am getting always the same error:
**ORA-29024: Certificate validation failure**
After some digging I realise that someone has configured a PROXY for outgoing traffic. Before even trying in Apex, I tried in SQL using APEX\_WEB\_SERVICE
Request with proxy settings to login.microsoftonline.com
```
select apex_web_service.make_rest_request(
p_url => 'https://login.microsoftonline.com',
p_http_method => 'GET',
p_wallet_path => 'file:/home/oracle/wallet',
p_wallet_pwd => 'MyPassword' ,
p_proxy_override => 'http://myproxy:myport'
7 ) from dual;
ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1035
ORA-29024: Certificate validation failure
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1148
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 934
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1580
ORA-06512: at "APEX_190100.WWV_FLOW_WEBSERVICES_API", line 408
ORA-06512: at line 1
```
Request without proxy settings, just to see if I can get there
```
SQL> select apex_web_service.make_rest_request(
2 p_url => 'https://login.microsoftonline.com',
3 p_http_method => 'GET',
4 p_wallet_path => 'file:/home/oracle/wallet'
5* ) from dual
SQL> /
ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1035
ORA-29024: Certificate validation failure
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1148
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 934
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1580
ORA-06512: at "APEX_190100.WWV_FLOW_WEBSERVICES_API", line 408
ORA-06512: at line 1
```
Request to google using Proxy settings
```
select apex_web_service.make_rest_request(
p_url => 'https://google.com',
p_http_method => 'GET',
p_wallet_path => 'file:/home/oracle/wallet',
p_wallet_pwd => 'MyPassword' ,
6 p_proxy_override => 'http://myproxy:myport'
7 ) from dual ;
ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1035
ORA-29024: Certificate validation failure
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1148
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 934
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1580
ORA-06512: at "APEX_190100.WWV_FLOW_WEBSERVICES_API", line 408
ORA-06512: at line 1
```
Request to google without proxy settings
```
SQL> select apex_web_service.make_rest_request(
2 p_url => 'https://google.com',
3 p_http_method => 'GET',
4 p_wallet_path => 'file:/home/oracle/wallet'
5* ) from dual
SQL> /
ERROR:
ORA-29273: HTTP request failed
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1035
ORA-12535: TNS:operation timed out
ORA-06512: at "SYS.UTL_HTTP", line 380
ORA-06512: at "SYS.UTL_HTTP", line 1148
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 934
ORA-06512: at "APEX_190100.WWV_FLOW_WEB_SERVICES", line 1580
ORA-06512: at "APEX_190100.WWV_FLOW_WEBSERVICES_API", line 408
ORA-06512: at line 1
```
My questions are the following:
* It is a network problem or a proxy issue regarding inbound/outbound
traffic ? I can reach Microsoft but not Google in the port 443 when I don't specify proxy.
* Why am I getting invalid certificate when it has nothing to do with
the certificates ?
* How can I setup my APEX to use authentication on Azure or any other
provider for that matter when I have a proxy in the middle ?
* As I use ORDS standalone, am I allow to keep using it or I need a
reverse proxy with Tomcat ?
I tried to configure the ACE to use HTTP\_PROXY in the ports by running
```
begin
sys.dbms_network_acl_admin.append_host_ace(
host => 'myproxyserver'
,lower_port => 8080
,upper_port => 8080
,ace => xs$ace_type(
privilege_list => xs$name_list('http_proxy')
,granted => true
,principal_name => 'MY_PRINCIPAL'
,principal_type => XS_ACL.PTYPE_DB
)
);
end;
/
```
Even I grant to the ACE privileges over the wallet
```
SET SERVEROUTPUT ON
BEGIN
DBMS_NETWORK_ACL_ADMIN.APPEND_WALLET_ACE
(
WALLET_PATH => 'file:/home/oracle/wallet',
ACE => XS$ACE_TYPE(
PRIVILEGE_LIST => XS$NAME_LIST('use_passwords','use_client_certificates'),
PRINCIPAL_NAME => 'MY_PRINCIPAL',
PRINCIPAL_TYPE => XS_ACL.PTYPE_DB
)
);
EXCEPTION WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error while configuring ACL for wallet: '|| SQLERRM);
END;
/
```
but I am still getting the same error all over.
Any help would be appreciated!
Thank you | 2020/07/11 | [
"https://Stackoverflow.com/questions/62851314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13755538/"
] | Thank you to all who post answers, but finally, after struggling for a while, I found the root cause. Actually Oracle was right after all, as Microsoft has changed the way the authentication is handled, either you are using Oauth2 or OpenID, when you use Office365 and Azure Active Directory.
In this case, my organisation is using Office 365 and at the beginning was enough with importing the PKI certificates from :
<https://www.microsoft.com/pki/mscorp/cps/default.htm>
After a change done in Azure Active Directory (AAD), you now need also the Global Sign certificates from [office.com](http://office.com)
I hope it clarifies to other users who got in the same problem trying to authenticate with Azure Active Directory using Apex Social sign in.
You can download the certificates directly from office365.com
[![enter image description here](https://i.stack.imgur.com/zkbq2.png)](https://i.stack.imgur.com/zkbq2.png)
After adding the new two certificates to the wallet, you can now enter without issues:
```
select apex_web_service.make_rest_request(
p_url => 'https://login.microsoftonline.com',
p_http_method => 'GET',
4 p_wallet_path => 'file:/home/oracle/wallet' ) from dual ;
APEX_WEB_SERVICE.MAKE_REST_REQUEST(P_URL=>'HTTPS://LOGIN.MICROSOFTONLINE.COM',P_
--------------------------------------------------------------------------------
<!-- Copyright (C) Microsoft Corporation. All rights reserved. -->
<!DOCTYP
SQL>
``` | I had issue like this, it seems Oracle SSL library has some bugs. Finally I implemented some Java Source for OJVM, please read my answer here: <https://stackoverflow.com/a/60152830/11272044> |
20,576,864 | I am using Omniauth in a Rails application for login, my omniauth.rb, is as show below:
```
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, 'xxxxxxx', 'xxxxxxx'
provider :google_oauth2, 'xxxxxxxxx','xxxxxxxx'
end
```
When a user attempts to login (via Facebook or Goolge) and denies permissions, get the following error:
```
OmniAuth::Strategies::OAuth2::CallbackError
```
with this parameters:
```
{"error"=>"access_denied",
"error_code"=>"200",
"error_description"=>"Permissions error",
"error_reason"=>"user_denied",
"state"=>"60daee5f78d9cc28972050ae8ca8f950bb4ed5958302bcea"}
```
if the user accept, no problem and everything works fine.
I've tried some of the possible solutions related with this error, and listed on this website, but none solved my problem. For example:
[How to rescue OmniAuth::Strategies::OAuth2::CallbackError?](https://stackoverflow.com/questions/10737200/how-to-rescue-omniauthstrategiesoauth2callbackerror)
[Omniauth+facebook error when trying to cancel the popup](https://stackoverflow.com/questions/10647642/omniauthfacebook-error-when-trying-to-cancel-the-popup)
Please, I need help to solve this problem. | 2013/12/13 | [
"https://Stackoverflow.com/questions/20576864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3100897/"
] | Our old friend `strace` solves this mystery.
In the `fflush("cat")` case, awk quickly writes all three values while cat is still loading. When cat finishes loading, it reads all three values in sequence and writes them out at the same time.
In the case of `close("cat")`, awk waits for the process to exit, at which point cat is guaranteed to have read the value, written it, and exited.
I increased the numbers in the `fflush` case from 3 to 1000, and now `awk` reaches 120 before cat catches up, and from there on it works basically as you expect. It prints "1,2,..,120,1,2,...,120,121,121,122,122,123,123,...".
Note that you're not guaranteed to see numbers in perfect pairs. awk blocks until the number has been written to the pipe, but it doesn't wait for cat to do anything with it. | Not really something I have much experience of but the gawk manual tells us:
>
> fflush([filename])
> Flush any buffered output associated with filename,
> which is either a file opened for writing or a shell command for
> redirecting output **to a pipe** or coprocess.
>
>
>
Note that "cat" as used above is in none of the contexts the gawk manual says are affected by fflush().
The same manual for close() on the other hand says:
>
> close(filename [, how])
> Close the file filename for input or output.
> Alternatively, the argument may be a shell command that was used for
> creating a coprocess, or for redirecting **to or from a pipe**; then
> the coprocess or pipe is closed.
>
>
>
Note that the context in which you're using cat is redirecting **from** a pipe and so is included in the list of items affected by close() but not by fflush(). |
946,937 | I bought a Dell Studio XPS 8100 desktop back in 2010, which had Windows 7 installed and came with a partition for Dell Factory Restore.
After having installed Windows 10, what happened to that partition? Did the installation get rid of it? If not and I were to use it to do a Dell Factory Restore, would it "reinstall" Windows 7?
Sorry if this is a duplicate of a question somewhere, I didn't see one exactly like this asking about Windows 10 upgrade and Dell's Recovery partition. | 2015/07/29 | [
"https://superuser.com/questions/946937",
"https://superuser.com",
"https://superuser.com/users/474857/"
] | The recovery partition will not be touched nor upgraded during this process. If you did a factory restore, you would end up with Windows 7. | If you run into a problem where you cannot access your recovery partition, or the partition is deleted, you can run a tool called DSRFIX and it should restore the recovery partition. |
946,937 | I bought a Dell Studio XPS 8100 desktop back in 2010, which had Windows 7 installed and came with a partition for Dell Factory Restore.
After having installed Windows 10, what happened to that partition? Did the installation get rid of it? If not and I were to use it to do a Dell Factory Restore, would it "reinstall" Windows 7?
Sorry if this is a duplicate of a question somewhere, I didn't see one exactly like this asking about Windows 10 upgrade and Dell's Recovery partition. | 2015/07/29 | [
"https://superuser.com/questions/946937",
"https://superuser.com",
"https://superuser.com/users/474857/"
] | From what I am seeing, if there is not a system partition on the drive, only the Dell recovery partition & OS partition, then Windows 10 will alter the boot folder of that partition. This effects the PE recovery environment & will break the factory recovery. Even after reapplying the Factory.wim of windows 7 and it blue screens, Windows 10 PE recovery environment will start & not help with the start up issues. I'm presently trying to undo all of this on a Dell Inspiron laptop at present.
I don't think this will happen if there is a 100MB system partition on the drive as this is where the Windows 10 recovery environment will install (in the boot folder). Thus leaving the Dell Recovery partition untouched leaving the F11 function in tact to be able to factory install the OS that shipped with the laptop. Isn't the digital life wonderful!!! | If you run into a problem where you cannot access your recovery partition, or the partition is deleted, you can run a tool called DSRFIX and it should restore the recovery partition. |
418,342 | I know I can pass parameters to java to limit the amount of memory used, but that doesn't change the application behavior. (assuming I will get an out of memory exception or similar)
I would like to limit the amount of memory that solr uses. I am assuming it is as simple as setting a single configuration option, but googling so far has been fruitless.
Any ideas? Thanks!
Edit: I just want to note that I understand there will be a tradeoff between memory usage and execution speed. In this case, I am willing to sacrifice speed to reduce memory footprint. I also understand that it is possible that solr does not support the option of tuning this tradeoff. | 2012/08/16 | [
"https://serverfault.com/questions/418342",
"https://serverfault.com",
"https://serverfault.com/users/107102/"
] | Check out this article, it should address your needs
<http://blogs.technet.com/b/grouppolicy/archive/2009/07/30/security-filtering-wmi-filtering-and-item-level-targeting-in-group-policy-preferences.aspx>
and like Joe said, yes you can use groups for computers as well | Yes, you can use a security group populated with computer accounts to filter Group Policy. |
29,743,729 | I am using video.js (<http://www.videojs.com/>) to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks.
I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it.
When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play.
If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started.
Can anyone help me to find the position in the video where the seek begins?
If this is not possible, I'd settle for a way to disable seeking during playback.
EDIT: adding code as requested. It's pretty simple:
```
var trackedPlayer = videojs('pvp-player');
trackedPlayer.on("play", function (e) {
console.log("Video playback started: " + trackedPlayer.currentTime());
});
trackedPlayer.on("pause", function (e) {
console.log("Video playback paused: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeking", function (e) {
console.log("Video seeking: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeked", function (e) {
console.log("Video seek ended: " + trackedPlayer.currentTime());
});
trackedPlayer.on("ended", function (e) {
console.log("Video playback ended.");
});
```
If I can get all the tracking I want I will replace console.log with ajax calls to store the data. | 2015/04/20 | [
"https://Stackoverflow.com/questions/29743729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2664914/"
] | You can listen to `timeupdate` und take the next to last value you got there before `seeking` is called as your source:
```
var previousTime = 0;
var currentTime = 0;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = trackedPlayer.currentTime();
});
trackedPlayer.on('seeking', function() {
console.log('seeking from', previousTime, 'to', currentTime, '; delta:', currentTime - previousTime);
});
```
This seems to work with the HTML5 tech. I have not tested with other techs.
There is, however, one glitch: the first time seeking a *paused* player yields only a small delta (and the almost-same previous value for both variables). But this shouldn’t matter much since the delta is only a few hundred milliseconds (and I gather you’re only interested in the “from” value).
**Update**
`seeked` is triggered far more infrequently than `seeking`. Try the following.
```
var previousTime = 0;
var currentTime = 0;
var seekStart = null;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = trackedPlayer.currentTime();
});
trackedPlayer.on('seeking', function() {
if(seekStart === null) {
seekStart = previousTime;
}
});
trackedPlayer.on('seeked', function() {
console.log('seeked from', seekStart, 'to', currentTime, '; delta:', currentTime - previousTime);
seekStart = null;
});
```
There are also many libraries for debouncing function calls (in this case the call to your backend). | Try with this code to know the length of video.
```
var duration = document.getElementById("duration");
var vid_duration = Math.round(document.getElementById("video").duration);
//alert(vid_duration);
duration.innerHTML = vid_duration;
//duration.firstChild.nodeValue = vid_duration;
``` |
29,743,729 | I am using video.js (<http://www.videojs.com/>) to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks.
I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it.
When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play.
If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started.
Can anyone help me to find the position in the video where the seek begins?
If this is not possible, I'd settle for a way to disable seeking during playback.
EDIT: adding code as requested. It's pretty simple:
```
var trackedPlayer = videojs('pvp-player');
trackedPlayer.on("play", function (e) {
console.log("Video playback started: " + trackedPlayer.currentTime());
});
trackedPlayer.on("pause", function (e) {
console.log("Video playback paused: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeking", function (e) {
console.log("Video seeking: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeked", function (e) {
console.log("Video seek ended: " + trackedPlayer.currentTime());
});
trackedPlayer.on("ended", function (e) {
console.log("Video playback ended.");
});
```
If I can get all the tracking I want I will replace console.log with ajax calls to store the data. | 2015/04/20 | [
"https://Stackoverflow.com/questions/29743729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2664914/"
] | I needed to find the same value for a project I was working on so I could determine whether or not a user was skipping forward or backward in a videojs player.
Initially, I thought to save the currentTime() a user was seeking **from** on **timeupdate** then immediately removing my timeupdate listener once **seeking** was dispatched. While this worked in some browsers like Chrome, unfortunately, I found that other browsers continued to fire timeupdate more frequently and would continue to update the currentTime() I was saving after the player actually seeked.
Here was the solution that ultimately worked across Safari/Chrome/Firefox. I have yet to test in IE.
```
var previousTime = 0,
currentTime = 0,
completeTime = 0,
position = 0;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = Math.floor(player.currentTime());
// save 'position' so long as time is moving forward with each update
if (previousTime < currentTime) {
position = previousTime;
previousTime = currentTime;
}
});
// when seeking starts
trackedPlayer.on('seeking', function() {
player.off('timeupdate', onTimeUpdate);
player.one('seeked', onSeekComplete);
});
// when seeking completes
trackedPlayer.on('seeked', function() {
completeTime = Math.floor(player.currentTime());
console.log("User came from: " + position);
console.log("User ended at: " + completeTime);
});
``` | Try with this code to know the length of video.
```
var duration = document.getElementById("duration");
var vid_duration = Math.round(document.getElementById("video").duration);
//alert(vid_duration);
duration.innerHTML = vid_duration;
//duration.firstChild.nodeValue = vid_duration;
``` |
29,743,729 | I am using video.js (<http://www.videojs.com/>) to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks.
I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it.
When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play.
If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started.
Can anyone help me to find the position in the video where the seek begins?
If this is not possible, I'd settle for a way to disable seeking during playback.
EDIT: adding code as requested. It's pretty simple:
```
var trackedPlayer = videojs('pvp-player');
trackedPlayer.on("play", function (e) {
console.log("Video playback started: " + trackedPlayer.currentTime());
});
trackedPlayer.on("pause", function (e) {
console.log("Video playback paused: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeking", function (e) {
console.log("Video seeking: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeked", function (e) {
console.log("Video seek ended: " + trackedPlayer.currentTime());
});
trackedPlayer.on("ended", function (e) {
console.log("Video playback ended.");
});
```
If I can get all the tracking I want I will replace console.log with ajax calls to store the data. | 2015/04/20 | [
"https://Stackoverflow.com/questions/29743729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2664914/"
] | I know this is an old post but this is the only solution that worked for me.
```
var counter = 0;
var beforeTimeChange = 0;
function handleSeeking() {
var timeoutTime = 300;
var beforeCounter = counter + 1;
if (trackedPlayer.cache_.currentTime === trackedPlayer.duration()) {
return;
// when video starts over, calls seek
}
beforeTimeChange = beforeTimeChange || trackedPlayer.cache_.currentTime;
setTimeout(function() {
if (beforeCounter === counter) {
console.log('before seek', beforeTimeChange, '\nafter seek', trackedPlayer.currentTime() - (timeoutTime / 1000));
counter = 0;
beforeTimeChange = 0;
}
}, timeoutTime);
counter++;
}
trackedPlayer.on('seeking', handleSeeking);
``` | Try with this code to know the length of video.
```
var duration = document.getElementById("duration");
var vid_duration = Math.round(document.getElementById("video").duration);
//alert(vid_duration);
duration.innerHTML = vid_duration;
//duration.firstChild.nodeValue = vid_duration;
``` |
29,743,729 | I am using video.js (<http://www.videojs.com/>) to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks.
I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it.
When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play.
If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started.
Can anyone help me to find the position in the video where the seek begins?
If this is not possible, I'd settle for a way to disable seeking during playback.
EDIT: adding code as requested. It's pretty simple:
```
var trackedPlayer = videojs('pvp-player');
trackedPlayer.on("play", function (e) {
console.log("Video playback started: " + trackedPlayer.currentTime());
});
trackedPlayer.on("pause", function (e) {
console.log("Video playback paused: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeking", function (e) {
console.log("Video seeking: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeked", function (e) {
console.log("Video seek ended: " + trackedPlayer.currentTime());
});
trackedPlayer.on("ended", function (e) {
console.log("Video playback ended.");
});
```
If I can get all the tracking I want I will replace console.log with ajax calls to store the data. | 2015/04/20 | [
"https://Stackoverflow.com/questions/29743729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2664914/"
] | For a more accurate solution, you can listen to the events that trigger the seek such as mousedown on progress bar, left key, right key etc., and get the current time from these events.
For example in version 7.10.2 you can do the following,
```
let seekStartTime;
player.controlBar.progressControl.on('mousedown', () => seekStartTime = player.currentTime());
player.controlBar.progressControl.seekBar.on('mousedown', () => seekStartTime = player.currentTime());
player.on('keydown', (e) => {
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
seekStartTime = player.currentTime();
}
});
console.log(seekStartTime);
```
**Note 1:** There are two seperate mousedown event listeners for progress control and seek bar. This is because the video can be seeked by clicking outside the seek bar on the progress control as well.
**Note 2:** Seeking using hotkey numbers does not pause the video. However, if necessary you can add those keydown listeners too. | Try with this code to know the length of video.
```
var duration = document.getElementById("duration");
var vid_duration = Math.round(document.getElementById("video").duration);
//alert(vid_duration);
duration.innerHTML = vid_duration;
//duration.firstChild.nodeValue = vid_duration;
``` |
29,743,729 | I am using video.js (<http://www.videojs.com/>) to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks.
I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it.
When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play.
If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started.
Can anyone help me to find the position in the video where the seek begins?
If this is not possible, I'd settle for a way to disable seeking during playback.
EDIT: adding code as requested. It's pretty simple:
```
var trackedPlayer = videojs('pvp-player');
trackedPlayer.on("play", function (e) {
console.log("Video playback started: " + trackedPlayer.currentTime());
});
trackedPlayer.on("pause", function (e) {
console.log("Video playback paused: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeking", function (e) {
console.log("Video seeking: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeked", function (e) {
console.log("Video seek ended: " + trackedPlayer.currentTime());
});
trackedPlayer.on("ended", function (e) {
console.log("Video playback ended.");
});
```
If I can get all the tracking I want I will replace console.log with ajax calls to store the data. | 2015/04/20 | [
"https://Stackoverflow.com/questions/29743729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2664914/"
] | I needed to find the start and end of a seeking action in my project and I used @Motorcykey answer and it worked, but there was a small bug. when I tried to seek to a time before the current time while the player was paused, the `position` didn't get updated. so I added just one line and it fixed it. I've tried other solutions too but so far this was the best solution that I've found. Here's the code snippet on player 'seeked'
```
player.on('seeked', function () {
completeTime = Math.floor(player.currentTime());
console.log("User came from: " + position);
console.log("User ended at: " + completeTime);
position= Math.floor(player.currentTime())
});
``` | Try with this code to know the length of video.
```
var duration = document.getElementById("duration");
var vid_duration = Math.round(document.getElementById("video").duration);
//alert(vid_duration);
duration.innerHTML = vid_duration;
//duration.firstChild.nodeValue = vid_duration;
``` |
29,743,729 | I am using video.js (<http://www.videojs.com/>) to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks.
I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it.
When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play.
If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started.
Can anyone help me to find the position in the video where the seek begins?
If this is not possible, I'd settle for a way to disable seeking during playback.
EDIT: adding code as requested. It's pretty simple:
```
var trackedPlayer = videojs('pvp-player');
trackedPlayer.on("play", function (e) {
console.log("Video playback started: " + trackedPlayer.currentTime());
});
trackedPlayer.on("pause", function (e) {
console.log("Video playback paused: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeking", function (e) {
console.log("Video seeking: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeked", function (e) {
console.log("Video seek ended: " + trackedPlayer.currentTime());
});
trackedPlayer.on("ended", function (e) {
console.log("Video playback ended.");
});
```
If I can get all the tracking I want I will replace console.log with ajax calls to store the data. | 2015/04/20 | [
"https://Stackoverflow.com/questions/29743729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2664914/"
] | You can listen to `timeupdate` und take the next to last value you got there before `seeking` is called as your source:
```
var previousTime = 0;
var currentTime = 0;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = trackedPlayer.currentTime();
});
trackedPlayer.on('seeking', function() {
console.log('seeking from', previousTime, 'to', currentTime, '; delta:', currentTime - previousTime);
});
```
This seems to work with the HTML5 tech. I have not tested with other techs.
There is, however, one glitch: the first time seeking a *paused* player yields only a small delta (and the almost-same previous value for both variables). But this shouldn’t matter much since the delta is only a few hundred milliseconds (and I gather you’re only interested in the “from” value).
**Update**
`seeked` is triggered far more infrequently than `seeking`. Try the following.
```
var previousTime = 0;
var currentTime = 0;
var seekStart = null;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = trackedPlayer.currentTime();
});
trackedPlayer.on('seeking', function() {
if(seekStart === null) {
seekStart = previousTime;
}
});
trackedPlayer.on('seeked', function() {
console.log('seeked from', seekStart, 'to', currentTime, '; delta:', currentTime - previousTime);
seekStart = null;
});
```
There are also many libraries for debouncing function calls (in this case the call to your backend). | I needed to find the same value for a project I was working on so I could determine whether or not a user was skipping forward or backward in a videojs player.
Initially, I thought to save the currentTime() a user was seeking **from** on **timeupdate** then immediately removing my timeupdate listener once **seeking** was dispatched. While this worked in some browsers like Chrome, unfortunately, I found that other browsers continued to fire timeupdate more frequently and would continue to update the currentTime() I was saving after the player actually seeked.
Here was the solution that ultimately worked across Safari/Chrome/Firefox. I have yet to test in IE.
```
var previousTime = 0,
currentTime = 0,
completeTime = 0,
position = 0;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = Math.floor(player.currentTime());
// save 'position' so long as time is moving forward with each update
if (previousTime < currentTime) {
position = previousTime;
previousTime = currentTime;
}
});
// when seeking starts
trackedPlayer.on('seeking', function() {
player.off('timeupdate', onTimeUpdate);
player.one('seeked', onSeekComplete);
});
// when seeking completes
trackedPlayer.on('seeked', function() {
completeTime = Math.floor(player.currentTime());
console.log("User came from: " + position);
console.log("User ended at: " + completeTime);
});
``` |
29,743,729 | I am using video.js (<http://www.videojs.com/>) to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks.
I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it.
When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play.
If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started.
Can anyone help me to find the position in the video where the seek begins?
If this is not possible, I'd settle for a way to disable seeking during playback.
EDIT: adding code as requested. It's pretty simple:
```
var trackedPlayer = videojs('pvp-player');
trackedPlayer.on("play", function (e) {
console.log("Video playback started: " + trackedPlayer.currentTime());
});
trackedPlayer.on("pause", function (e) {
console.log("Video playback paused: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeking", function (e) {
console.log("Video seeking: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeked", function (e) {
console.log("Video seek ended: " + trackedPlayer.currentTime());
});
trackedPlayer.on("ended", function (e) {
console.log("Video playback ended.");
});
```
If I can get all the tracking I want I will replace console.log with ajax calls to store the data. | 2015/04/20 | [
"https://Stackoverflow.com/questions/29743729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2664914/"
] | You can listen to `timeupdate` und take the next to last value you got there before `seeking` is called as your source:
```
var previousTime = 0;
var currentTime = 0;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = trackedPlayer.currentTime();
});
trackedPlayer.on('seeking', function() {
console.log('seeking from', previousTime, 'to', currentTime, '; delta:', currentTime - previousTime);
});
```
This seems to work with the HTML5 tech. I have not tested with other techs.
There is, however, one glitch: the first time seeking a *paused* player yields only a small delta (and the almost-same previous value for both variables). But this shouldn’t matter much since the delta is only a few hundred milliseconds (and I gather you’re only interested in the “from” value).
**Update**
`seeked` is triggered far more infrequently than `seeking`. Try the following.
```
var previousTime = 0;
var currentTime = 0;
var seekStart = null;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = trackedPlayer.currentTime();
});
trackedPlayer.on('seeking', function() {
if(seekStart === null) {
seekStart = previousTime;
}
});
trackedPlayer.on('seeked', function() {
console.log('seeked from', seekStart, 'to', currentTime, '; delta:', currentTime - previousTime);
seekStart = null;
});
```
There are also many libraries for debouncing function calls (in this case the call to your backend). | I know this is an old post but this is the only solution that worked for me.
```
var counter = 0;
var beforeTimeChange = 0;
function handleSeeking() {
var timeoutTime = 300;
var beforeCounter = counter + 1;
if (trackedPlayer.cache_.currentTime === trackedPlayer.duration()) {
return;
// when video starts over, calls seek
}
beforeTimeChange = beforeTimeChange || trackedPlayer.cache_.currentTime;
setTimeout(function() {
if (beforeCounter === counter) {
console.log('before seek', beforeTimeChange, '\nafter seek', trackedPlayer.currentTime() - (timeoutTime / 1000));
counter = 0;
beforeTimeChange = 0;
}
}, timeoutTime);
counter++;
}
trackedPlayer.on('seeking', handleSeeking);
``` |
29,743,729 | I am using video.js (<http://www.videojs.com/>) to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks.
I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it.
When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play.
If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started.
Can anyone help me to find the position in the video where the seek begins?
If this is not possible, I'd settle for a way to disable seeking during playback.
EDIT: adding code as requested. It's pretty simple:
```
var trackedPlayer = videojs('pvp-player');
trackedPlayer.on("play", function (e) {
console.log("Video playback started: " + trackedPlayer.currentTime());
});
trackedPlayer.on("pause", function (e) {
console.log("Video playback paused: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeking", function (e) {
console.log("Video seeking: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeked", function (e) {
console.log("Video seek ended: " + trackedPlayer.currentTime());
});
trackedPlayer.on("ended", function (e) {
console.log("Video playback ended.");
});
```
If I can get all the tracking I want I will replace console.log with ajax calls to store the data. | 2015/04/20 | [
"https://Stackoverflow.com/questions/29743729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2664914/"
] | You can listen to `timeupdate` und take the next to last value you got there before `seeking` is called as your source:
```
var previousTime = 0;
var currentTime = 0;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = trackedPlayer.currentTime();
});
trackedPlayer.on('seeking', function() {
console.log('seeking from', previousTime, 'to', currentTime, '; delta:', currentTime - previousTime);
});
```
This seems to work with the HTML5 tech. I have not tested with other techs.
There is, however, one glitch: the first time seeking a *paused* player yields only a small delta (and the almost-same previous value for both variables). But this shouldn’t matter much since the delta is only a few hundred milliseconds (and I gather you’re only interested in the “from” value).
**Update**
`seeked` is triggered far more infrequently than `seeking`. Try the following.
```
var previousTime = 0;
var currentTime = 0;
var seekStart = null;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = trackedPlayer.currentTime();
});
trackedPlayer.on('seeking', function() {
if(seekStart === null) {
seekStart = previousTime;
}
});
trackedPlayer.on('seeked', function() {
console.log('seeked from', seekStart, 'to', currentTime, '; delta:', currentTime - previousTime);
seekStart = null;
});
```
There are also many libraries for debouncing function calls (in this case the call to your backend). | For a more accurate solution, you can listen to the events that trigger the seek such as mousedown on progress bar, left key, right key etc., and get the current time from these events.
For example in version 7.10.2 you can do the following,
```
let seekStartTime;
player.controlBar.progressControl.on('mousedown', () => seekStartTime = player.currentTime());
player.controlBar.progressControl.seekBar.on('mousedown', () => seekStartTime = player.currentTime());
player.on('keydown', (e) => {
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
seekStartTime = player.currentTime();
}
});
console.log(seekStartTime);
```
**Note 1:** There are two seperate mousedown event listeners for progress control and seek bar. This is because the video can be seeked by clicking outside the seek bar on the progress control as well.
**Note 2:** Seeking using hotkey numbers does not pause the video. However, if necessary you can add those keydown listeners too. |
29,743,729 | I am using video.js (<http://www.videojs.com/>) to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks.
I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it.
When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play.
If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started.
Can anyone help me to find the position in the video where the seek begins?
If this is not possible, I'd settle for a way to disable seeking during playback.
EDIT: adding code as requested. It's pretty simple:
```
var trackedPlayer = videojs('pvp-player');
trackedPlayer.on("play", function (e) {
console.log("Video playback started: " + trackedPlayer.currentTime());
});
trackedPlayer.on("pause", function (e) {
console.log("Video playback paused: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeking", function (e) {
console.log("Video seeking: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeked", function (e) {
console.log("Video seek ended: " + trackedPlayer.currentTime());
});
trackedPlayer.on("ended", function (e) {
console.log("Video playback ended.");
});
```
If I can get all the tracking I want I will replace console.log with ajax calls to store the data. | 2015/04/20 | [
"https://Stackoverflow.com/questions/29743729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2664914/"
] | You can listen to `timeupdate` und take the next to last value you got there before `seeking` is called as your source:
```
var previousTime = 0;
var currentTime = 0;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = trackedPlayer.currentTime();
});
trackedPlayer.on('seeking', function() {
console.log('seeking from', previousTime, 'to', currentTime, '; delta:', currentTime - previousTime);
});
```
This seems to work with the HTML5 tech. I have not tested with other techs.
There is, however, one glitch: the first time seeking a *paused* player yields only a small delta (and the almost-same previous value for both variables). But this shouldn’t matter much since the delta is only a few hundred milliseconds (and I gather you’re only interested in the “from” value).
**Update**
`seeked` is triggered far more infrequently than `seeking`. Try the following.
```
var previousTime = 0;
var currentTime = 0;
var seekStart = null;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = trackedPlayer.currentTime();
});
trackedPlayer.on('seeking', function() {
if(seekStart === null) {
seekStart = previousTime;
}
});
trackedPlayer.on('seeked', function() {
console.log('seeked from', seekStart, 'to', currentTime, '; delta:', currentTime - previousTime);
seekStart = null;
});
```
There are also many libraries for debouncing function calls (in this case the call to your backend). | I needed to find the start and end of a seeking action in my project and I used @Motorcykey answer and it worked, but there was a small bug. when I tried to seek to a time before the current time while the player was paused, the `position` didn't get updated. so I added just one line and it fixed it. I've tried other solutions too but so far this was the best solution that I've found. Here's the code snippet on player 'seeked'
```
player.on('seeked', function () {
completeTime = Math.floor(player.currentTime());
console.log("User came from: " + position);
console.log("User ended at: " + completeTime);
position= Math.floor(player.currentTime())
});
``` |
2,767,139 | Can I do this in C++ (if yes, what is the syntax?):
```
void func(string* strs) {
// do something
}
func({"abc", "cde"});
```
I want to pass an array to a function, without instantiating it as a variable. | 2010/05/04 | [
"https://Stackoverflow.com/questions/2767139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/187141/"
] | It can't be done in the current C++, as defined by C++03.
The feature you are looking for is called "compound literals". It is present in C language, as defined by C99 (with C-specific capabilities, of course), but not in C++.
A similar feature is planned for C++ as well, but it is not there yet. | I don't think you can do that in C++98, but you can with [initializer\_lists](https://stackoverflow.com/questions/2357452/stdinitializer-list-as-function-argument) in C++1x. |
2,767,139 | Can I do this in C++ (if yes, what is the syntax?):
```
void func(string* strs) {
// do something
}
func({"abc", "cde"});
```
I want to pass an array to a function, without instantiating it as a variable. | 2010/05/04 | [
"https://Stackoverflow.com/questions/2767139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/187141/"
] | It can't be done in the current C++, as defined by C++03.
The feature you are looking for is called "compound literals". It is present in C language, as defined by C99 (with C-specific capabilities, of course), but not in C++.
A similar feature is planned for C++ as well, but it is not there yet. | As written, you can't do this. The function expects a pointer-to-string. Even if you were able to pass an array as a literal, the function call would generate errors because literals are considered constant (thus, the array of literals would be of type `const string*`, not `string*` as the function expects). |
2,767,139 | Can I do this in C++ (if yes, what is the syntax?):
```
void func(string* strs) {
// do something
}
func({"abc", "cde"});
```
I want to pass an array to a function, without instantiating it as a variable. | 2010/05/04 | [
"https://Stackoverflow.com/questions/2767139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/187141/"
] | It can't be done in the current C++, as defined by C++03.
The feature you are looking for is called "compound literals". It is present in C language, as defined by C99 (with C-specific capabilities, of course), but not in C++.
A similar feature is planned for C++ as well, but it is not there yet. | Use a variadic function to pass in unlimited untyped information into a function. Then do whatever you want with the passed in data, such as stuffing it into an internal array.
[variadic function](http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_C.2C_Objective-C.2C_C.2B.2B.2C_and_D) |
14,559,761 | I want to use `std::initializer_list`s in Visual Studio 2012 like a guy in [this example](http://musingstudio.com/2012/11/27/stdinitializer_list-an-even-better-way-to-populate-a-vector/) does. My operating system is Windows 8 x64.
Therefore I lately installed the [Visual C++ Compiler November 2012 CTP](http://www.microsoft.com/en-us/download/details.aspx?id=35515) and as mentioned by Microsoft, I changed the platform toolset of my project to use that new updated compiler.
But even after doing so, there is neither a `std::initializer_list` nor a `<initializer_list>` header available. But the linked website from Microsoft tells me (under the headline "Overview") that initializer lists would be available with that update. I restarted both the IDE and my PC. I am not sure if it could be caused by the fact that I am (sadly) using the German edition of Visual Studio and the compiler update is in English. What am I doing wrong?
Update: Trying to compile the line `auto a = { 0 };` which is criticized by IntelliSense the compiler output shows `'Microsoft Visual C++ Compiler Nov 2012 CTP' is for testing purposes only.` and then compiler crashes and a error window appears which reads `Microsoft (R) C/C++ Compiler Driver has stopped working`. Without any new syntax, everything compiles and works fine with the new compiler selected. | 2013/01/28 | [
"https://Stackoverflow.com/questions/14559761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1079110/"
] | (I work for Microsoft and with Dinkumware to maintain VC's Standard Library implementation.)
[danijar]
>
> I am not sure if it could be caused by the fact that I am (sadly) using the German edition of Visual Studio and the compiler update is in English.
>
>
>
Unfortunately, the English-only CTP does not support German VS.
The "compiler driver" cl.exe is what invokes the compiler front-end c1xx.dll, the compiler back-end c2.dll, and the linker link.exe. It is very unusual for the compiler driver to crash. I speculate that it's attempting to display one of the error messages that were added by the CTP, but since the CTP didn't update the German resources, the compiler driver can't load the error message and proceeds to crash.
Note that this is different from an Internal Compiler Error in the front-end or back-end, or a normal compiler error that happens to be incorrectly emitted. (Many ICEs and bogus errors have been fixed after the CTP was released.)
>
> But even after doing so, there is neither a std::initializer\_list nor a <initializer\_list> header available.
>
>
>
The CTP installed <initializer\_list> in a special location. (It was actually written by the compiler team.)
On the command line, the incantations to use the CTP and put <initializer\_list> on the include path are (assuming default locations):
```
"C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\vcvarsall.bat" x86
set PATH=C:\Program Files (x86)\Microsoft Visual C++ Compiler Nov 2012 CTP\bin;%PATH%
set INCLUDE=C:\Program Files (x86)\Microsoft Visual C++ Compiler Nov 2012 CTP\include;%INCLUDE%
```
>
> Trying to compile the line auto a = { 0 }; which is criticized by IntelliSense
>
>
>
This was documented - Intellisense was not updated by the CTP, therefore it will not recognize any of the new features.
[rubenvb]
>
> The C++ Standard Library was not updated with the compiler, leaving you without decent <tuple> and <intializer\_list> (this includes the omission of the braced init list constructors for all standard containers)
>
>
>
You may be interested to learn that we've updated the standard library to fully support scoped enums and initializer lists. This includes all initializer\_list overloads mandated by the current Working Paper (N3485), plus installing <initializer\_list> in the usual location along with all other standard headers. (It is also Dinkumware's official copy, although the differences between it and the compiler team's "fake" version were mostly cosmetic.) This stuff will be available in the next public release, whenever and whatever that is. Our next task is to update the standard library with explicit conversion operators and variadic templates, replacing our brittle simulations. | As you have noticed, the November CTP is very limited in usability for at least two reasons:
1. The compiler has numerous crash-causing bugs, such as the one you discovered.
2. The C++ Standard Library was not updated with the compiler, leaving you without decent `<tuple>` and `<intializer_list>` (this includes the omission of the braced init list constructors for *all* standard containers)
Also: the linked example is very ugly code. If you want to use this feature, use a compiler like GCC or Clang that supports this syntax. They are both available for Windows. Hacking around a half-implemented language feature by writing extra code is just stupid. |
19,995 | I don't recall ever having the problem with the iron before, but it's been a few years since I used it, as I'm just getting back into some projects since my Electronics degree.
I bought some solder for a new project (I need a lot) and it's lead-free:
```
95% Tin
4% Silver
1% Copper
```
Now, I'm not sure how tolerant the values are for melting point but I can say that it does appear to act Eutectic, like the known combination 95.5/4/0.5 ([Indalloy 246](http://www.matweb.com/search/DataSheet.aspx?MatGUID=19662ece2a4a4bb2bbe7aa522f916185)) which has a melting point of 217 degrees Celcius.
According to the manufacturer of my Iron (Antex) it has a tip temperature of 370 celcius.
I sanded down the tip yesterday with a fine grain metal sanding paper to see if the tip just needed cleaning, however it's now gone "black" instead of the shiny silver it was when I first sanded it.
The real question I wonder is where the problem lies, is it that my tip is dead, is my iron too low power or is it just that my iron is dead.
I ask because I need to know whether to replace the iron, the tip or a higher power iron. My preference is to stick with the Antex irons, and I prefer "precision" bits like the on in my current iron, so, what are the recommendations? | 2011/09/25 | [
"https://electronics.stackexchange.com/questions/19995",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/5702/"
] | Your tip is dead since you have now sanded off the special coating. It will of course still get hot, but will oxidize rapidly so that solder won't wick onto it. This will make it very difficult to solder with.
You say the tip is supposed to be 370C (700F), but is that temperature controlled or just some open loop guess? 12W sounds very low for a temperature controlled soldering station, and also not enough to heat much beyond a little solder and a wire or two at the same time. For example, my Weller WES51 temperature controller soldering station has a 50W iron. Of course most of the time it's not run at 50W, but that's what the control algorithm can cause it to put out when it senses low tip temperature.
Since you just destroyed your tip (and the iron if it has a fixed tip), maybe it's time to get a real one that has temperature control. | A 12w iron is way under-powered for leadfree. You need a temerature-controlled iron, 40-60W minimum |
38,380,164 | My project demo as link: <http://jsfiddle.net/Lvc0u55v/6741/>
I use AngularJS.
If a movie is not found, old values should not appear in the following code
```
<form style="margin-bottom: 40px;">
<ul>
<li><h2>Title: {{result().name}}</h2></li>
<li><h3>Release Date: {{result().release}}</h3></li>
<li><h3>Length: {{result().length}}</h3></li>
<li><h3>Description: {{result().description}}</h3></li>
<li><h3>IMDb Rating: {{result().rating}}</h3></li>
</ul>
</form>
```
When I write something in text value and click the button, if the movie is not found, the result page is not updated, so the old values are still showing.
For example I wrote 'x-men' in text and clicked button, I can see about X-men movie.
Then I wrote 'asdfg' and clicked the button, I can see `alert('Movie not found')` but old value is still writing in html page.
I tried `ng-if`, `ng-show` , `$state.reload()` etc. but I could not get it to work.
Code as snippet:
```js
var app = angular.module('myApp', []);
app.controller('searchMovieController', function ($scope, $http, resultFactory) {
$scope.searchMovieF = function () {
if ($scope.searchMovie.length > 0) {
$scope.api = 'http://www.omdbapi.com/?t=' + $scope.searchMovie + '&y=&plot=short&r=json';
$http.get($scope.api)
.success(function (data) {
$("#movie-name").autocomplete({
source: data.Title
});
if ((data.Error != "Movie not found!") && ( data.Error != "Must provide more than one character.")) {
var details = {
name:data.Title,
release: data.Released,
length: data.Runtime,
description: data.Plot,
rating: data.imdbRating
}
resultFactory.set(details)
}
else {
alert("Movie not found !")
}
});
} else {
alert("Please write somethings !")
}
}
});
app.controller('resultMovieController', function ($scope,resultFactory) {
$scope.result = function() {
return resultFactory.details
}
});
app.factory('resultFactory', function() {
var details = {
}
var set = function(obj) {
var objKeys = Object.keys(obj);
for(var i=0; i < objKeys.length; i++) {
details[objKeys[i]] = obj[objKeys[i]];
}
}
return {
details: details,
set: set
}
})
```
```html
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0-rc.2/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div class="bs-component" ng-controller="searchMovieController">
<form class="well form-search">
<fieldset>
<legend>Search Movie</legend>
</fieldset>
<div>
<label class="control-label" for="movie-name">Movie Name : </label>
<input type="text" id="movie-name" class="input-small" style="margin-left: 10px;" placeholder="Please write movie name" ng-model="searchMovie">
<a class="btn-sm btn-primary" style="margin-left: 10px;" ng-click="searchMovieF()">
<span class="glyphicon glyphicon-search"> Search</span>
</a>
</div>
</form>
<ul>
<li> <h2>Title: {{name}}</h2></li>
<li><h3>Release Date: {{release}}</h3></li>
<li><h3>Length: {{length}}</h3></li>
<li><h3>Description: {{description}}</h3></li>
<li><h3>IMDb Rating: {{rating}}</h3></li>
</ul>
</div>
<br><br><br><br><br><br>
<div id="forResult" class="bs-component" ng-controller="resultMovieController">
<form class="well form-search" id="formResult">
<fieldset>
<legend>Result for Search Movie</legend>
</fieldset>
</form>
<ul>
<li> <h2>Title: {{result().name}}</h2></li>
<li><h3>Release Date: {{result().release}}</h3></li>
<li><h3>Length: {{result().length}}</h3></li>
<li><h3>Description:{{result().description}}</h3></li>
<li><h3>IMDb Rating: {{result().rating}}</h3></li>
</ul>
<a ui-sref="/search-movie" class="btn-sm btn-primary" style="margin-left:20px;">
<span class="glyphicon glyphicon-circle-arrow-left">Back to Search Page</span>
</a>
</div>
``` | 2016/07/14 | [
"https://Stackoverflow.com/questions/38380164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5257578/"
] | It would appear that the resultFactory is not being set with new values unless a film is actually found. You'll have to make sure that your resultFactory is being set even when a film does not match the user's search entry.
You can simply move your resultFactory.set outside of the `if` statement and set each key to an empty string if the key is not defined in `data`. This can be done quickly per key by using two pipes (`||`) in resultFactory.set
```
resultFactory.set({
name:data.Title || '',
release: data.Released || '',
length: data.Runtime || '',
description: data.Plot || '',
rating: data.imdbRating || ''
});
```
[Here's a link to the updated JSFiddle](http://jsfiddle.net/f6uomqja/) including the fix. | You need to add this
```
var details = {
name:"",
release: "",
length: "",
description: "",
rating: ""
}
resultFactory.set(details)
```
in the else block
add the entire code:
```
var app = angular.module('myApp', []);
app.controller('searchMovieController', function ($scope, $http, resultFactory) {
$scope.searchMovieF = function () {
if ($scope.searchMovie.length > 0) {
$scope.api = 'http://www.omdbapi.com/?t=' + $scope.searchMovie + '&y=&plot=short&r=json';
$http.get($scope.api)
.success(function (data) {
$("#movie-name").autocomplete({
source: data.Title
});
if ((data.Error != "Movie not found!") && ( data.Error != "Must provide more than one character.")) {
var details = {
name:data.Title,
release: data.Released,
length: data.Runtime,
description: data.Plot,
rating: data.imdbRating
}
resultFactory.set(details)
}
else {
alert("Movie not found !")
var details = {
name:"",
release: "",
length: "",
description: "",
rating: ""
}
resultFactory.set(details)
}
});
} else {
alert("Please write somethings !")
}
}
});
app.controller('resultMovieController', function ($scope,resultFactory) {
$scope.result = function() {
return resultFactory.details
}
});
app.factory('resultFactory', function() {
var details = {
}
var set = function(obj) {
var objKeys = Object.keys(obj);
for(var i=0; i < objKeys.length; i++) {
details[objKeys[i]] = obj[objKeys[i]];
}
}
return {
details: details,
set: set
}
})
``` |
4,583,801 | This is a classical Sangaku problem, also known as old Japanese geometry problems, that I found out just recently. The figure shows a semicircle with a smaller circle and an equilateral triangle inscribed inside it. Note that the semicircle can be *any* general semicircle, but in this case it has a radius of $1$ unit. Also note that one of the vertices of the equilateral triangle lies on the center of the semicircle. I have solved this problem and I'll post my approach as an answer, in order to not clutter up this space. Please share your own approaches as well!
[![enter image description here](https://i.stack.imgur.com/48a0g.png)](https://i.stack.imgur.com/48a0g.png) | 2022/11/23 | [
"https://math.stackexchange.com/questions/4583801",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1092912/"
] | A slightly quicker step (2) skips the quadratic formula: Observe that the hypotenuse shared by your two 30-60-90 triangles has length $\frac 2{\sqrt 3} r$ (since the side lengths are proportional to $1:\sqrt 3:2$), hence
$$r + \frac 2{\sqrt 3}r = 1$$
which yields $r=2\sqrt 3-3$. | Here's my approach for the problem:
Please note that my answer uses a lemma that can be proven easily, that is, [the radii of two externally or internally tangent circles are collinear](https://youtu.be/0whTkdGBNn0).
[![enter image description here](https://i.stack.imgur.com/R518H.png)](https://i.stack.imgur.com/R518H.png)
1.) First, we join the center of the semicircle with that of the circle, and draw a perpendicular from the center of the circle to the tangent points (semicircle and the vertex of the equilateral triangle). Notice that the two triangles that are formed are congruent via the SSS property, therefore we can conclude that the line connecting two centers is an angle sector. This proves that the two triangles are in fact "$30-60-90$" triangle.
2.) Now, using the fact proven above, we can say that the base of those triangles (i.e. the side opposite to the $30^\circ$ angle) is $\frac{r}{\sqrt3}$. Finally, we can finish off the problem:
$$(1-r)^2=r^2+(\frac{r}{\sqrt3})^2$$
$$1-2r+r^2=r^2+\frac{r^2}{3}$$
$$r^2+6r-3=0$$
Since this isn't factorable, we can use the quadratic formula:
$$r=\frac{-6±\sqrt{48}}{2}$$
Since $\frac{-6-\sqrt{48}}{2}$ would be negative, we must reject that. Therefore:
$$r=-3+2\sqrt{3}$$ |
6,856,491 | There is a file named \*.iso, where `*` is any string (dot, numbers, alphabets, spl characters).
\*.iso is located at /dm2/www/html/isos/preFCS5.3/
I want to get this filename into $filename. I know it's very simple. How can I do this in Perl? | 2011/07/28 | [
"https://Stackoverflow.com/questions/6856491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/713200/"
] | Destructor of the Base class will be automatically called by the compiler, when your objet life time ends. you do not need to call it explicitly.
```
TMyObject::TMyObject() : TObject()
```
Does not inherit the constructor.
It is called as **[Member initializer list](https://stackoverflow.com/questions/6724626/c-constructor/6724639#6724639)** and it initializes the Base class object with a particular value.
When you create the object.
```
TMyObject obj;
```
The constructors will be called in order:
```
constructor of TObject
constructor of TMyObject
```
When the object life time ends the destructors will be called in the order:
```
destructor of TMyObject
destructr of TObject
```
The compiler will do so for you, do not need to call it explicitly. | If you destroy a `TMyObject` through a reference of type `TMyObject` you don't have to do anything. In case you have a pointer/reference of type `TObject` to a `TMyObject` things will go wrong. *Only* the `TObject` destructor will be called, not the `TMyObject` one:
```
TObject* p = new TMyObject;
delete p; // Only the TObject::~TObject is called, not TMyObject::~TMyObject.
```
To have the decision on what destructor to call deferred to runtime, you need to specify the destructor as `virtual` in `TObject`. Whenever you have a class that is intended to be derived from, the destructor should be virtual. Otherwise there is always a risk for resource leaks when the derived class destructor isn't called properly. |
6,856,491 | There is a file named \*.iso, where `*` is any string (dot, numbers, alphabets, spl characters).
\*.iso is located at /dm2/www/html/isos/preFCS5.3/
I want to get this filename into $filename. I know it's very simple. How can I do this in Perl? | 2011/07/28 | [
"https://Stackoverflow.com/questions/6856491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/713200/"
] | Destructor of the Base class will be automatically called by the compiler, when your objet life time ends. you do not need to call it explicitly.
```
TMyObject::TMyObject() : TObject()
```
Does not inherit the constructor.
It is called as **[Member initializer list](https://stackoverflow.com/questions/6724626/c-constructor/6724639#6724639)** and it initializes the Base class object with a particular value.
When you create the object.
```
TMyObject obj;
```
The constructors will be called in order:
```
constructor of TObject
constructor of TMyObject
```
When the object life time ends the destructors will be called in the order:
```
destructor of TMyObject
destructr of TObject
```
The compiler will do so for you, do not need to call it explicitly. | What's causing the confusion to you is that you can specifically mention "which" constructor of the base class you want to use as in the following example. But you can't/ don't need to specify the destructor.
```
TMyObject::TMyObject() : TObject()
```
You could use a different constructor, say `TObject (int i)` by writing
```
TMyObject::TMyObject() : TObject (3)
```
An object can be destructed in only one way but it can be constructed in several ways (by having different constructors).
So, in short, you don't need to mention the name of the base class destructor in the derived class destructor. As soon as you destroy the derived object (say, by doing `delete derivedObj`), it will first call the derived class destructor and then base class destructor by itself. |
6,856,491 | There is a file named \*.iso, where `*` is any string (dot, numbers, alphabets, spl characters).
\*.iso is located at /dm2/www/html/isos/preFCS5.3/
I want to get this filename into $filename. I know it's very simple. How can I do this in Perl? | 2011/07/28 | [
"https://Stackoverflow.com/questions/6856491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/713200/"
] | This can be solved at `TObject`'s level. Its destructor has to be virtual:
```
#include <Classes.hpp>
class TObject
{
__fastcall TObject();
virtual __fastcall ~TObject();
};
```
This way you can either do:
```
TObject * pobj = new TMyObject();
delete pobj;
```
or
```
TMyObject * pobj = new TMyObject();
delete pobj;
```
Both destructors will be called (`~TMyObject()` first and then `~TObject()`) and you will have no leak. | Destructor of the Base class will be automatically called by the compiler, when your objet life time ends. you do not need to call it explicitly.
```
TMyObject::TMyObject() : TObject()
```
Does not inherit the constructor.
It is called as **[Member initializer list](https://stackoverflow.com/questions/6724626/c-constructor/6724639#6724639)** and it initializes the Base class object with a particular value.
When you create the object.
```
TMyObject obj;
```
The constructors will be called in order:
```
constructor of TObject
constructor of TMyObject
```
When the object life time ends the destructors will be called in the order:
```
destructor of TMyObject
destructr of TObject
```
The compiler will do so for you, do not need to call it explicitly. |
6,856,491 | There is a file named \*.iso, where `*` is any string (dot, numbers, alphabets, spl characters).
\*.iso is located at /dm2/www/html/isos/preFCS5.3/
I want to get this filename into $filename. I know it's very simple. How can I do this in Perl? | 2011/07/28 | [
"https://Stackoverflow.com/questions/6856491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/713200/"
] | This can be solved at `TObject`'s level. Its destructor has to be virtual:
```
#include <Classes.hpp>
class TObject
{
__fastcall TObject();
virtual __fastcall ~TObject();
};
```
This way you can either do:
```
TObject * pobj = new TMyObject();
delete pobj;
```
or
```
TMyObject * pobj = new TMyObject();
delete pobj;
```
Both destructors will be called (`~TMyObject()` first and then `~TObject()`) and you will have no leak. | If you destroy a `TMyObject` through a reference of type `TMyObject` you don't have to do anything. In case you have a pointer/reference of type `TObject` to a `TMyObject` things will go wrong. *Only* the `TObject` destructor will be called, not the `TMyObject` one:
```
TObject* p = new TMyObject;
delete p; // Only the TObject::~TObject is called, not TMyObject::~TMyObject.
```
To have the decision on what destructor to call deferred to runtime, you need to specify the destructor as `virtual` in `TObject`. Whenever you have a class that is intended to be derived from, the destructor should be virtual. Otherwise there is always a risk for resource leaks when the derived class destructor isn't called properly. |
6,856,491 | There is a file named \*.iso, where `*` is any string (dot, numbers, alphabets, spl characters).
\*.iso is located at /dm2/www/html/isos/preFCS5.3/
I want to get this filename into $filename. I know it's very simple. How can I do this in Perl? | 2011/07/28 | [
"https://Stackoverflow.com/questions/6856491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/713200/"
] | This can be solved at `TObject`'s level. Its destructor has to be virtual:
```
#include <Classes.hpp>
class TObject
{
__fastcall TObject();
virtual __fastcall ~TObject();
};
```
This way you can either do:
```
TObject * pobj = new TMyObject();
delete pobj;
```
or
```
TMyObject * pobj = new TMyObject();
delete pobj;
```
Both destructors will be called (`~TMyObject()` first and then `~TObject()`) and you will have no leak. | What's causing the confusion to you is that you can specifically mention "which" constructor of the base class you want to use as in the following example. But you can't/ don't need to specify the destructor.
```
TMyObject::TMyObject() : TObject()
```
You could use a different constructor, say `TObject (int i)` by writing
```
TMyObject::TMyObject() : TObject (3)
```
An object can be destructed in only one way but it can be constructed in several ways (by having different constructors).
So, in short, you don't need to mention the name of the base class destructor in the derived class destructor. As soon as you destroy the derived object (say, by doing `delete derivedObj`), it will first call the derived class destructor and then base class destructor by itself. |
5,321,883 | I am very new to spring security . I picked up [this](https://rads.stackoverflow.com/amzn/click/com/1847199747) book and trying to execute the code .
While I do this I am getting
```
org.springframework.beans.NotReadablePropertyException: Invalid property
'principal.username' of bean class
[org.springframework.security.authentication.AnonymousAuthenticationToken]:
Bean property 'principal.username' is not readable or has an invalid getter
method:
Does the return type of the getter match the parameter type of the setter?
```
My spring-security xml config :
```
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login.do" access="permitAll"/>
<intercept-url pattern="/*" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login.do"/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service id="userService">
<user authorities="ROLE_USER" name="guest" password="guest"/>
</user-service>
</authentication-provider>
<!-- Ch 3 Change Password Service -->
<!--
<authentication-provider user-service-ref="userService"/>
-->
</authentication-manager>
```
Am I missing something ?
Let me know if you need any additional information. | 2011/03/16 | [
"https://Stackoverflow.com/questions/5321883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571718/"
] | What the error message seems to be indicating is that something is trying to access a non-existent property on an `AnonymousAuthenticationToken` ; i.e. the authentication token that spring security uses when the session is not logged in.
I suspect that the problem is actually occurring either in your servlet code, or in a JSP that is trying to access the name of the current user via a spring security tag.
The complete stacktrace for the error might give us more clues. At least it should tell us where the exception is coming from.
(For what it is worth, an `AnonymousAuthenticationToken` does have a `principal` property, but that property is not normally an object that has a `username` property. Indeed, it is often just a String.) | I am reading/following the "Spring Security 3" book. Just add the following lines to the header.jsp The problem is that principal.username does not exists if you are not logged in.
```
<div class="username">
Welcome,
<sec:authorize access="isAuthenticated()">
<strong><sec:authentication property="principal.username"/></strong>
</sec:authorize>
</div>
``` |
5,321,883 | I am very new to spring security . I picked up [this](https://rads.stackoverflow.com/amzn/click/com/1847199747) book and trying to execute the code .
While I do this I am getting
```
org.springframework.beans.NotReadablePropertyException: Invalid property
'principal.username' of bean class
[org.springframework.security.authentication.AnonymousAuthenticationToken]:
Bean property 'principal.username' is not readable or has an invalid getter
method:
Does the return type of the getter match the parameter type of the setter?
```
My spring-security xml config :
```
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login.do" access="permitAll"/>
<intercept-url pattern="/*" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login.do"/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service id="userService">
<user authorities="ROLE_USER" name="guest" password="guest"/>
</user-service>
</authentication-provider>
<!-- Ch 3 Change Password Service -->
<!--
<authentication-provider user-service-ref="userService"/>
-->
</authentication-manager>
```
Am I missing something ?
Let me know if you need any additional information. | 2011/03/16 | [
"https://Stackoverflow.com/questions/5321883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571718/"
] | What the error message seems to be indicating is that something is trying to access a non-existent property on an `AnonymousAuthenticationToken` ; i.e. the authentication token that spring security uses when the session is not logged in.
I suspect that the problem is actually occurring either in your servlet code, or in a JSP that is trying to access the name of the current user via a spring security tag.
The complete stacktrace for the error might give us more clues. At least it should tell us where the exception is coming from.
(For what it is worth, an `AnonymousAuthenticationToken` does have a `principal` property, but that property is not normally an object that has a `username` property. Indeed, it is often just a String.) | Prerequisites as follows:
1. Add spring security taglib in jsp page you want to show username,
```
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
```
2. Add spring security jars, use
```
<sec:authentication property="principal" />
```
in jsp where you want to show the username
Following will show up:
1. **anonymousUser**, means user is not logged in
2. **string representation of object**, means user is logged in
But do not print string representation of object on page.
Here's a pseudo code:
```
if principal==anonymousUser
show login button
else (do not use principal here too)
show username with logout button
``` |
5,321,883 | I am very new to spring security . I picked up [this](https://rads.stackoverflow.com/amzn/click/com/1847199747) book and trying to execute the code .
While I do this I am getting
```
org.springframework.beans.NotReadablePropertyException: Invalid property
'principal.username' of bean class
[org.springframework.security.authentication.AnonymousAuthenticationToken]:
Bean property 'principal.username' is not readable or has an invalid getter
method:
Does the return type of the getter match the parameter type of the setter?
```
My spring-security xml config :
```
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login.do" access="permitAll"/>
<intercept-url pattern="/*" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login.do"/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service id="userService">
<user authorities="ROLE_USER" name="guest" password="guest"/>
</user-service>
</authentication-provider>
<!-- Ch 3 Change Password Service -->
<!--
<authentication-provider user-service-ref="userService"/>
-->
</authentication-manager>
```
Am I missing something ?
Let me know if you need any additional information. | 2011/03/16 | [
"https://Stackoverflow.com/questions/5321883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571718/"
] | I am reading/following the "Spring Security 3" book. Just add the following lines to the header.jsp The problem is that principal.username does not exists if you are not logged in.
```
<div class="username">
Welcome,
<sec:authorize access="isAuthenticated()">
<strong><sec:authentication property="principal.username"/></strong>
</sec:authorize>
</div>
``` | Prerequisites as follows:
1. Add spring security taglib in jsp page you want to show username,
```
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
```
2. Add spring security jars, use
```
<sec:authentication property="principal" />
```
in jsp where you want to show the username
Following will show up:
1. **anonymousUser**, means user is not logged in
2. **string representation of object**, means user is logged in
But do not print string representation of object on page.
Here's a pseudo code:
```
if principal==anonymousUser
show login button
else (do not use principal here too)
show username with logout button
``` |
67,863 | The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language? | 2015/08/31 | [
"https://rpg.stackexchange.com/questions/67863",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/21781/"
] | If it was physically capable of speaking, it would be able to speak the languages it knew in life. It still retains its knowledge of them, so *knowing* how to speak a language is not the problem. The problem is that a skeleton lacks lips, a tongue, vocal cords, a voicebox, and lungs. Speaking is simply impossible.
The Monster Manual entry on skeletons says:
>
> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point.
>
>
>
From this, it seems clear that it is meant to be impossible for skeletons to communicate in **any** way other than the given nodding, shaking, and pointing. | Isn't this why we have Speak with Dead spells? The skeleton has no way of making vocalizations so cannot speak audibly but can understand language due to the magic that animates it. |
67,863 | The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language? | 2015/08/31 | [
"https://rpg.stackexchange.com/questions/67863",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/21781/"
] | If it was physically capable of speaking, it would be able to speak the languages it knew in life. It still retains its knowledge of them, so *knowing* how to speak a language is not the problem. The problem is that a skeleton lacks lips, a tongue, vocal cords, a voicebox, and lungs. Speaking is simply impossible.
The Monster Manual entry on skeletons says:
>
> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point.
>
>
>
From this, it seems clear that it is meant to be impossible for skeletons to communicate in **any** way other than the given nodding, shaking, and pointing. | By RAW default, no.
===================
As explained by others it has no basic, default, means of expressing language. It's not about learning the language, it's the capability of the spell/energy powering the skeleton(s). Undeath is not in itself an impediment to speech (see: Liches).
Therefore you need to extrapolate a bit. The RAW description quoted above seems to imply the power source provides bare-minimum world interaction capabilities. And does not extend to advanced capabilities like mimicking a voice (disembodied or otherwise).
But, the "talking skull/skeleton" trope is incredibly common. So...
By customization, yes. (Possibly with the aid of a magic item.)
===============================================================
It is your game, after all. And creativity is a core value of the gaming experience.
A skeleton is already magically animated, so if you wanted a **specific skeleton** to have the ability to speak, there are several creative ways you could explain the phenomenon.
* A magic item equipped by its creator, or even left over from its previous life. (An enchanted ring or amulet?)
* A slightly more powerful skeleton who gained the ability to speak over time via wild magic or the like.
* A skeleton created with extra riders on the creation spell by its creator. So maybe it was imbued with a secondary spell to allow a disembodied voice.
You could have all skeletons speak of that's how you want to run your world, but that'd be your own custom flavoring.
A speaking skeleton, otherwise, would be **special for some reason**. |
67,863 | The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language? | 2015/08/31 | [
"https://rpg.stackexchange.com/questions/67863",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/21781/"
] | If it was physically capable of speaking, it would be able to speak the languages it knew in life. It still retains its knowledge of them, so *knowing* how to speak a language is not the problem. The problem is that a skeleton lacks lips, a tongue, vocal cords, a voicebox, and lungs. Speaking is simply impossible.
The Monster Manual entry on skeletons says:
>
> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point.
>
>
>
From this, it seems clear that it is meant to be impossible for skeletons to communicate in **any** way other than the given nodding, shaking, and pointing. | <https://www.dandwiki.com/wiki/Skeleton_(5e_Race)> said
>
> You've managed to control the energies that sustain you to allow you speak. You can speak, read and write Common, as well as the language of your creator. A Giant Skeleton may speak Giant, a God Touched may know Celestial, a Magic Fluke may randomly grant you a language and a Raised Minion may know their wizard master's draconic.
>
>
>
so im guessing you can but i think it's for players thats race is skeleton |
67,863 | The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language? | 2015/08/31 | [
"https://rpg.stackexchange.com/questions/67863",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/21781/"
] | If it was physically capable of speaking, it would be able to speak the languages it knew in life. It still retains its knowledge of them, so *knowing* how to speak a language is not the problem. The problem is that a skeleton lacks lips, a tongue, vocal cords, a voicebox, and lungs. Speaking is simply impossible.
The Monster Manual entry on skeletons says:
>
> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point.
>
>
>
From this, it seems clear that it is meant to be impossible for skeletons to communicate in **any** way other than the given nodding, shaking, and pointing. | It is true, on pg 272 of the 5e Monster Manual, it states:
>
> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point.
>
>
>
... and D&D Beyond - [Skeleton entry](https://www.dndbeyond.com/monsters/skeleton) states ...
>
> Understands all languages it knew in life but can't speak
>
>
>
... but both of these interpretations seem to be relatively 'new' 5e expansions to d&d skeleton lore. Wrt Habitual Behaviors in the 5e MM, if "skeletons of nobles might continue in an eternally unfinished dance" && "can load and fire a catapult or trebuchet".
Also, wrt D&D Beyond, it appears to be poorly worded. If taken literally, that it simply cannot speak; then it would be able to use sign language, portions of thieves cant, or write & still communicate.
I think all of the older versions are more consistent wrt skeletons in this respect; in that the creator can command them via magic (and it ignores the medium of the command.)
Therefore we need to break up your question:
1. Can it not speak because of its undeath?
If you look at all the lore in total, the answer here would be the skeleton cannot "communicate", speaking or otherwise. If you look at 5e literally, then the two sources are possibly contradictory & you'll have to subjectively decide for your world/campaign.
2. Could it learn to speak a language?
The simple answer is no... however, again looking at all the lore, should a different necromancer, demon, etc gain control of the skeleton; the method of control would give the ability to command irrespective of language.
Relatedly, an item of consideration is whether or not skeletons are deaf, & how their "vison" works.?. In my campaigns, skeletons are "unintelligent", and are deaf; with their "vision" being more animalistic/primitive in nature (they can't read, or understand complex items <missle weapons & doors included>)...
This isn't to say a specific necromancer couldn't craft a "unique breed" of skeletons that have different features, including higher intelligence; but just that the "average" skeleton does not. |
67,863 | The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language? | 2015/08/31 | [
"https://rpg.stackexchange.com/questions/67863",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/21781/"
] | By RAW default, no.
===================
As explained by others it has no basic, default, means of expressing language. It's not about learning the language, it's the capability of the spell/energy powering the skeleton(s). Undeath is not in itself an impediment to speech (see: Liches).
Therefore you need to extrapolate a bit. The RAW description quoted above seems to imply the power source provides bare-minimum world interaction capabilities. And does not extend to advanced capabilities like mimicking a voice (disembodied or otherwise).
But, the "talking skull/skeleton" trope is incredibly common. So...
By customization, yes. (Possibly with the aid of a magic item.)
===============================================================
It is your game, after all. And creativity is a core value of the gaming experience.
A skeleton is already magically animated, so if you wanted a **specific skeleton** to have the ability to speak, there are several creative ways you could explain the phenomenon.
* A magic item equipped by its creator, or even left over from its previous life. (An enchanted ring or amulet?)
* A slightly more powerful skeleton who gained the ability to speak over time via wild magic or the like.
* A skeleton created with extra riders on the creation spell by its creator. So maybe it was imbued with a secondary spell to allow a disembodied voice.
You could have all skeletons speak of that's how you want to run your world, but that'd be your own custom flavoring.
A speaking skeleton, otherwise, would be **special for some reason**. | Isn't this why we have Speak with Dead spells? The skeleton has no way of making vocalizations so cannot speak audibly but can understand language due to the magic that animates it. |
67,863 | The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language? | 2015/08/31 | [
"https://rpg.stackexchange.com/questions/67863",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/21781/"
] | It is true, on pg 272 of the 5e Monster Manual, it states:
>
> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point.
>
>
>
... and D&D Beyond - [Skeleton entry](https://www.dndbeyond.com/monsters/skeleton) states ...
>
> Understands all languages it knew in life but can't speak
>
>
>
... but both of these interpretations seem to be relatively 'new' 5e expansions to d&d skeleton lore. Wrt Habitual Behaviors in the 5e MM, if "skeletons of nobles might continue in an eternally unfinished dance" && "can load and fire a catapult or trebuchet".
Also, wrt D&D Beyond, it appears to be poorly worded. If taken literally, that it simply cannot speak; then it would be able to use sign language, portions of thieves cant, or write & still communicate.
I think all of the older versions are more consistent wrt skeletons in this respect; in that the creator can command them via magic (and it ignores the medium of the command.)
Therefore we need to break up your question:
1. Can it not speak because of its undeath?
If you look at all the lore in total, the answer here would be the skeleton cannot "communicate", speaking or otherwise. If you look at 5e literally, then the two sources are possibly contradictory & you'll have to subjectively decide for your world/campaign.
2. Could it learn to speak a language?
The simple answer is no... however, again looking at all the lore, should a different necromancer, demon, etc gain control of the skeleton; the method of control would give the ability to command irrespective of language.
Relatedly, an item of consideration is whether or not skeletons are deaf, & how their "vison" works.?. In my campaigns, skeletons are "unintelligent", and are deaf; with their "vision" being more animalistic/primitive in nature (they can't read, or understand complex items <missle weapons & doors included>)...
This isn't to say a specific necromancer couldn't craft a "unique breed" of skeletons that have different features, including higher intelligence; but just that the "average" skeleton does not. | Isn't this why we have Speak with Dead spells? The skeleton has no way of making vocalizations so cannot speak audibly but can understand language due to the magic that animates it. |
67,863 | The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language? | 2015/08/31 | [
"https://rpg.stackexchange.com/questions/67863",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/21781/"
] | By RAW default, no.
===================
As explained by others it has no basic, default, means of expressing language. It's not about learning the language, it's the capability of the spell/energy powering the skeleton(s). Undeath is not in itself an impediment to speech (see: Liches).
Therefore you need to extrapolate a bit. The RAW description quoted above seems to imply the power source provides bare-minimum world interaction capabilities. And does not extend to advanced capabilities like mimicking a voice (disembodied or otherwise).
But, the "talking skull/skeleton" trope is incredibly common. So...
By customization, yes. (Possibly with the aid of a magic item.)
===============================================================
It is your game, after all. And creativity is a core value of the gaming experience.
A skeleton is already magically animated, so if you wanted a **specific skeleton** to have the ability to speak, there are several creative ways you could explain the phenomenon.
* A magic item equipped by its creator, or even left over from its previous life. (An enchanted ring or amulet?)
* A slightly more powerful skeleton who gained the ability to speak over time via wild magic or the like.
* A skeleton created with extra riders on the creation spell by its creator. So maybe it was imbued with a secondary spell to allow a disembodied voice.
You could have all skeletons speak of that's how you want to run your world, but that'd be your own custom flavoring.
A speaking skeleton, otherwise, would be **special for some reason**. | <https://www.dandwiki.com/wiki/Skeleton_(5e_Race)> said
>
> You've managed to control the energies that sustain you to allow you speak. You can speak, read and write Common, as well as the language of your creator. A Giant Skeleton may speak Giant, a God Touched may know Celestial, a Magic Fluke may randomly grant you a language and a Raised Minion may know their wizard master's draconic.
>
>
>
so im guessing you can but i think it's for players thats race is skeleton |
67,863 | The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language? | 2015/08/31 | [
"https://rpg.stackexchange.com/questions/67863",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/21781/"
] | By RAW default, no.
===================
As explained by others it has no basic, default, means of expressing language. It's not about learning the language, it's the capability of the spell/energy powering the skeleton(s). Undeath is not in itself an impediment to speech (see: Liches).
Therefore you need to extrapolate a bit. The RAW description quoted above seems to imply the power source provides bare-minimum world interaction capabilities. And does not extend to advanced capabilities like mimicking a voice (disembodied or otherwise).
But, the "talking skull/skeleton" trope is incredibly common. So...
By customization, yes. (Possibly with the aid of a magic item.)
===============================================================
It is your game, after all. And creativity is a core value of the gaming experience.
A skeleton is already magically animated, so if you wanted a **specific skeleton** to have the ability to speak, there are several creative ways you could explain the phenomenon.
* A magic item equipped by its creator, or even left over from its previous life. (An enchanted ring or amulet?)
* A slightly more powerful skeleton who gained the ability to speak over time via wild magic or the like.
* A skeleton created with extra riders on the creation spell by its creator. So maybe it was imbued with a secondary spell to allow a disembodied voice.
You could have all skeletons speak of that's how you want to run your world, but that'd be your own custom flavoring.
A speaking skeleton, otherwise, would be **special for some reason**. | It is true, on pg 272 of the 5e Monster Manual, it states:
>
> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point.
>
>
>
... and D&D Beyond - [Skeleton entry](https://www.dndbeyond.com/monsters/skeleton) states ...
>
> Understands all languages it knew in life but can't speak
>
>
>
... but both of these interpretations seem to be relatively 'new' 5e expansions to d&d skeleton lore. Wrt Habitual Behaviors in the 5e MM, if "skeletons of nobles might continue in an eternally unfinished dance" && "can load and fire a catapult or trebuchet".
Also, wrt D&D Beyond, it appears to be poorly worded. If taken literally, that it simply cannot speak; then it would be able to use sign language, portions of thieves cant, or write & still communicate.
I think all of the older versions are more consistent wrt skeletons in this respect; in that the creator can command them via magic (and it ignores the medium of the command.)
Therefore we need to break up your question:
1. Can it not speak because of its undeath?
If you look at all the lore in total, the answer here would be the skeleton cannot "communicate", speaking or otherwise. If you look at 5e literally, then the two sources are possibly contradictory & you'll have to subjectively decide for your world/campaign.
2. Could it learn to speak a language?
The simple answer is no... however, again looking at all the lore, should a different necromancer, demon, etc gain control of the skeleton; the method of control would give the ability to command irrespective of language.
Relatedly, an item of consideration is whether or not skeletons are deaf, & how their "vison" works.?. In my campaigns, skeletons are "unintelligent", and are deaf; with their "vision" being more animalistic/primitive in nature (they can't read, or understand complex items <missle weapons & doors included>)...
This isn't to say a specific necromancer couldn't craft a "unique breed" of skeletons that have different features, including higher intelligence; but just that the "average" skeleton does not. |
67,863 | The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language? | 2015/08/31 | [
"https://rpg.stackexchange.com/questions/67863",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/21781/"
] | It is true, on pg 272 of the 5e Monster Manual, it states:
>
> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point.
>
>
>
... and D&D Beyond - [Skeleton entry](https://www.dndbeyond.com/monsters/skeleton) states ...
>
> Understands all languages it knew in life but can't speak
>
>
>
... but both of these interpretations seem to be relatively 'new' 5e expansions to d&d skeleton lore. Wrt Habitual Behaviors in the 5e MM, if "skeletons of nobles might continue in an eternally unfinished dance" && "can load and fire a catapult or trebuchet".
Also, wrt D&D Beyond, it appears to be poorly worded. If taken literally, that it simply cannot speak; then it would be able to use sign language, portions of thieves cant, or write & still communicate.
I think all of the older versions are more consistent wrt skeletons in this respect; in that the creator can command them via magic (and it ignores the medium of the command.)
Therefore we need to break up your question:
1. Can it not speak because of its undeath?
If you look at all the lore in total, the answer here would be the skeleton cannot "communicate", speaking or otherwise. If you look at 5e literally, then the two sources are possibly contradictory & you'll have to subjectively decide for your world/campaign.
2. Could it learn to speak a language?
The simple answer is no... however, again looking at all the lore, should a different necromancer, demon, etc gain control of the skeleton; the method of control would give the ability to command irrespective of language.
Relatedly, an item of consideration is whether or not skeletons are deaf, & how their "vison" works.?. In my campaigns, skeletons are "unintelligent", and are deaf; with their "vision" being more animalistic/primitive in nature (they can't read, or understand complex items <missle weapons & doors included>)...
This isn't to say a specific necromancer couldn't craft a "unique breed" of skeletons that have different features, including higher intelligence; but just that the "average" skeleton does not. | <https://www.dandwiki.com/wiki/Skeleton_(5e_Race)> said
>
> You've managed to control the energies that sustain you to allow you speak. You can speak, read and write Common, as well as the language of your creator. A Giant Skeleton may speak Giant, a God Touched may know Celestial, a Magic Fluke may randomly grant you a language and a Raised Minion may know their wizard master's draconic.
>
>
>
so im guessing you can but i think it's for players thats race is skeleton |
30,072,278 | I am having trouble with reading in a text file full of names (some are repeated) and inputting the first and last names together on 1 line. The program works and deletes repeated names but outputs them in alphabetical order with first and last names being treated as 2 different names. Am I outputting the names wrong with:
```
string name;
while (partyList >> name)
{
NamesList.insert(name);
}
cout << "Here is the party list without repetion: " << endl;
while (!NamesList.empty()) {
cout << ' ' << *NamesList.begin() << endl;
NamesList.erase(NamesList.begin());
}
```
?
The text file is PartyList.txt and it contains:
```
Daniel Walrus
Amy Giester
Jim Carry
Gregg Lunch
Irony Max
Jim Carry
Daniel Walrus
Gregg Lunch
```
Currently my output is:
```
Amy
Carrey
Daniel
Giester
Gregg
Irony
Jim
Lunch
Max
Walrus
```
Here is my code (this is part of a larger assignment which is completed besides making the first and last names go together):
```
#include <iostream>
#include <fstream>
#include <string>
#include <set>
using namespace std;
void PartyList();
int main()
{
PartyList();
system("PAUSE");
return 0;
}
void PartyList()
{
fstream partyList;
partyList.open("PartyList.txt", fstream::in);
if (!partyList)
{
cout << "Couldn't open file!" << endl;
}
set<string> NamesList;
string name;
while (partyList >> name)
{
NamesList.insert(name);
}
cout << "Here is the party list without repetion: " << endl;
while(!NamesList.empty()) { cout << ' ' << *NamesList.begin() << endl;
NamesList.erase(NamesList.begin());
}
//cout << name << endl;
cout << endl;
}
``` | 2015/05/06 | [
"https://Stackoverflow.com/questions/30072278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4110090/"
] | The `>>` operator in `partyList >> name` only reads from `partyList` until whitespace, which includes spaces, so `name` gets the values `"Daniel"`, `"Walrus"`, `"Amy"`, etc. on iteration. If you want to read one line at a time, use
```
while (std::getline(partyList, name))
```
which gets you `"Daniel Walrus"` etc. | ```
while (partyList >> name)
```
The `>>` operator is looking here for a first blank character. That's why your names are split this way. |
47,278,674 | I recently started study opencv. I only have a bachelor's degree on engineering. I am having a hard time of understanding these 2 morphological transformation: Black Hat, Top Hat. the official documents is [here](https://docs.opencv.org/master/d9/d61/tutorial_py_morphological_ops.html)
Can some one give some advice of what is the intuition of these operation and what is it for? | 2017/11/14 | [
"https://Stackoverflow.com/questions/47278674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6898439/"
] | Hopefully you understand *”morphological opening”*. If so, the (white) Top Hat tells you the pixels that would be removed by *”opening”*.
Likewise, the Black Hat tells you the pixels that would be added by *”morphological closing”*. | See the image for explanation. Simple algebra will help here.
>
> Top hat
>
>
>
top hat = image - opening = image - (image - false +ves) = false +ves
>
> Black hat
>
>
>
black hat = image - closing = image - (image - false -ves) = false -ves
[Explanation](https://i.stack.imgur.com/3Y15r.jpg) |
11,615,082 | I'm trying to run a macro that will delete rows that don't contain a particular value in column B. Here's my code:
```
Sub deleteRows()
Dim count As Integer
count = Application.WorksheetFunction.CountA(Range("AF:AF"))
Dim i As Integer
i = 21
Do While i <= count
If (Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("OSR Platform", Range("B" & i))) = False) Then
If (Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("IAM", Range("B" & i))) = False) Then
Rows(i).EntireRow.Delete
i = i - 1
count = count - 1
End If
End If
i = i + 1
Loop
End Sub
```
Now what it SHOULD be doing is the following:
1.) Find the number of rows to go through and set that as count (this works)
2.) Start at row 21 and look for "OSR Platform" and "IAM" in column B [this kind of works (see below)]
3.) If it finds neither, delete the entire row and adjust the count and row number as necessary (this works)
For some reason, whenever the code gets to the first If statement, an error window with a red X pops up that just says "400." As far as I can tell, I have written everything syntactically soundly, but clearly there's something wrong. | 2012/07/23 | [
"https://Stackoverflow.com/questions/11615082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512308/"
] | You may want to start by looping the other way. When you delete a line, all the previous lines are shifted. You account for this, but a reverse loop is simpler (*for me anyways*) to understand than keeping track of when I've offset the current position within the loop:
`For i = count To 21 Step -1`
Also, you're relying too much on `Application.WorksheetFunction`:
`(Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("OSR Platform", Range("B" & i))) = False)`
to
`InStr(Range("B" & i).value, "OSR Platform") > 0`
`Application.WorksheetFunction` takes much more processing power, and depending on what you are trying to accomplish, this can take a significantly longer amount of time. Also for this suggested change, the code size is reduced and becomes easier to read without it.
Your `count` can also be obtained without `A.WF`:
* Excel 2000/03: `count = Range("AF65536").End(xlUp).Row`
* Excel 2007/10: `count = Range("AF1048576").End(xlUp).Row`
* Version independent: `count = Range("AF" & Rows.Count).End(xlUp).Row`
One more thing is that you can do (and *should* do in this case) is combine your `If` statements into one.
Making these changes, you end up with:
```
Sub deleteRows()
Dim count As Integer
count = Range("AF" & Rows.Count).End(xlUp).Row
Dim i As Integer
For i = count To 21 Step -1
If Len(Range("B" & i).value) > 0 Then
If InStr(Range("B" & i).value, "OSR Platform") > 0 Or InStr(Range("B" & i).value, "IAM") > 0 Then
Range("B" & i).Interior.Color = RGB(255, 0, 0)
End If
End If
Next i
End Sub
```
If this does not help, then can you step through the code line by line. Add a breakpoint, and step through with `F8`. Highlight the variables in your code, right-click, choose "add Watch...", click "OK", ([Here's an excellent resource to help you with your debugging in general](http://www.cpearson.com/excel/debug.htm)) and note the following:
* Which line hits the error?
* What is the value of `i` and `count` when that happens? (add a watch on these variables to help) | This worked for me. It uses AutoFilter, does not require looping or worksheet functions.
```
Sub DeleteRows()
Dim currentSheet As Excel.Worksheet
Dim rngfilter As Excel.Range
Dim lastrow As Long, lastcolumn As Long
Set currentSheet = ActiveSheet
' get range
lastrow = currentSheet.Cells(Excel.Rows.Count, "AF").End(xlUp).Row
lastcolumn = currentSheet.Cells(1, Excel.Columns.Count).End(xlToLeft).Column
Set rngfilter = currentSheet.Range("A1", currentSheet.Cells(lastrow, lastcolumn))
' filter by column B criteria
rngfilter.AutoFilter Field:=2, Criteria1:="<>*OSR Platform*", Operator:= _
xlAnd, Criteria2:="<>*IAM*"
' delete any visible row greater than row 21 which does not meet above criteria
rngfilter.Offset(21).SpecialCells(xlCellTypeVisible).EntireRow.Delete
' remove autofilter arrows
currentSheet.AutoFilterMode = False
End Sub
```
This code applies AutoFilter to column B to see which rows contain neither "OSR Platform" nor "IAM" in column B. Then it simply deletes the remaining rows greater than 21. Test it on a copy of your workbook first.
With a huge nod to [this OzGrid](http://www.ozgrid.com/forum/showthread.php?t=153994) thread, because I can never remember the proper syntax for selecting visible cells after filtering. |
81,217 | If you don't know that it has been sacrificed to idols, then it is okay,
1 Corinthians 10:
>
> 25Eat whatever is sold in the meat market **without raising any question** on the ground of conscience.
>
>
>
Don't ask. Just eat.
>
> 26For “the earth is the Lord’s, and the fullness thereof.” 27If one of the unbelievers invites you to dinner and you are disposed to go, eat whatever is set before you **without raising any question** on the ground of conscience.
>
>
>
Again, don't ask.
>
> 28But if someone says to you, “This has been offered in sacrifice,” then **do not eat it**, for the sake of the one who informed you, and for the sake of conscience—
>
>
>
If you know that it has been sacrificed to idols, then don't eat it in front of them.
>
> 29I do not mean your conscience, but his. For why should my liberty be determined by someone else’s conscience? 30If I partake with thankfulness, why am I denounced because of that for which I give thanks?
>
>
>
What if you know that it has been sacrificed to idols and no one else is around, is it okay to eat? | 2023/01/31 | [
"https://hermeneutics.stackexchange.com/questions/81217",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/35953/"
] | **First,** this section of scripture first appeared nearly 2,000 years ago, and was written to Christians who were surrounded by pagans who had a practice of presenting (offering) meat to their idols before taking it to the market to be sold as food. Therefore, when you ask, "Should ***we*** eat food sacrificed to idols?" you have jumped nearly 2,000 years to this day and age, I presume. I take it that you are asking Christians in the Year of our Lord 2023 whether to eat food sacrificed to idols, or not.
**Second**, where I live, I have no awareness of any food being presented before idols prior to being made available to anyone to buy. If you know of such practices, it would be helpful to either state a case (as an example of the pertinence of this question today) or to give a list of modern-day countries where this happens.
**Third,** ***the simple answer to your question*** (irrespective of any time from the middle of the first century A.D. until today) ***is "No, Christians should not."*** The matter is known to God, even if no other human knows you have eaten food that had been offered before an idol. ***Once you know, you are culpable, and God knows.*** Christians are to do everything (including their eating and drinking) for the glory of God. But, as the passage shows, there's no need to first hold an inquisition about it, asking questions, ferreting out individuals who might be suspected of the pagan practice and checking if a particular piece of food had been handled by them.
That section of scripture, however, has more to say on the matter than just that bit about food presented before an idol. It speaks of not eating meat that has not first been bled. But you do not ask about that, so I will end my answer here. | The rationale for Paul's advice comes from the principle in v21; "You cannot partake of the table of the Lord and [also] of the table of demons".
This follows on from vv 18-20. Israel were "partners in the altar" (v18, RSV) when they sacrificed, in that God and the worshippers both had their own shares in most of the sacrificed animals. Conversely, those who shared in the communal sacrificial meals of other gods were "partners with demons" (v20). It was necessary to choose. The same choice remains for Christians in that we now share in the "Lord's Supper", at the table over which the Lord presides. We must choose one or the other. The point is that we must avoid sharing in the worship of other gods, by participating in the their communal meals, and we must also avoid giving other people the impression that we are particpating indirectly.
If nobody else is involved, it seems to me that the deciding factor is what you yourself think you are doing if you get hold of meat which was previously "dedicated" to some other god. If you think you are participating in the original sacrificial meal, you are in the position of ch8 v7; "Some... eat food as really offered to an idol; and their conscience, being weak, is defiled."
But if you are giving thanks to God for your food (ch10 v30) and are confident that its previous history doesn't affect its value in the sight of God, then you are in the position of "liberty" in ch8 v8; "Food will not commend us to God". The dictum of ch10 v25, "Eat whatever is sold", can still apply even if we have asked the question anyway. In other words, it makes no difference one way or the other, unless we think it makes a difference. See the principle that runs through Galatians; we are living in liberty, not under law. |
81,217 | If you don't know that it has been sacrificed to idols, then it is okay,
1 Corinthians 10:
>
> 25Eat whatever is sold in the meat market **without raising any question** on the ground of conscience.
>
>
>
Don't ask. Just eat.
>
> 26For “the earth is the Lord’s, and the fullness thereof.” 27If one of the unbelievers invites you to dinner and you are disposed to go, eat whatever is set before you **without raising any question** on the ground of conscience.
>
>
>
Again, don't ask.
>
> 28But if someone says to you, “This has been offered in sacrifice,” then **do not eat it**, for the sake of the one who informed you, and for the sake of conscience—
>
>
>
If you know that it has been sacrificed to idols, then don't eat it in front of them.
>
> 29I do not mean your conscience, but his. For why should my liberty be determined by someone else’s conscience? 30If I partake with thankfulness, why am I denounced because of that for which I give thanks?
>
>
>
What if you know that it has been sacrificed to idols and no one else is around, is it okay to eat? | 2023/01/31 | [
"https://hermeneutics.stackexchange.com/questions/81217",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/35953/"
] | **TL;DR:** There is no reason we should care whether our food has been sacrificed to idols.
The underlying idea here is whether one is committing idolatry, which is the belief that anything, other than God or his agents, has any supernatural power or attribute.
Believing that a rabbit's foot provides good luck is a form of idolatry, but so is believing that food that has been sacrificed to an idol is somehow different from food that hasn't.
Neither the rabbit's foot nor the food have any supernatural attributes.
To avoid something because it is reputed to have a non-existent attribute is equivalent to admitting that it *does* have that attribute.
For you, it shouldn't matter at all whether the food was sacrificed, any more than you should care what the phase of the Moon is today, or what constellation was in the sky at your birth.
But, if someone gives you something and explicitly or implicitly tells you it has supernatural attributes, *then* you should refuse it.
Not because it makes any difference to you, but because it makes a difference to the other person.
By taking it, you are implicitly endorsing and encouraging false beliefs, rather than providing the good example that every Christian should be.
>
> But if someone says to you, “This has been offered in sacrifice,” then do not eat it, for the sake of the one who informed you, and for the sake of conscience —
> **I do not mean your conscience, but his.** For why should my liberty be determined by someone else’s conscience?
>
>
>
Here "conscience" means:
>
> as distinguishing between what is morally good and bad, prompting to do the former and shun the latter, commending the one, condemning the other
>
>
>
Rejecting the offered food shows the other person that you are condemning the act of sacrificing to idols.
---
Consider a non-religious analogy.
You are visiting Bavaria and when the waiter pours your coffee he proudly tells you that the pot he is holding was used by Hitler himself when he visited the inn in 1942.
What message does it send if you smile, say danke schön, and proceed to drink it?
What message does it send if you refuse the coffee? | The rationale for Paul's advice comes from the principle in v21; "You cannot partake of the table of the Lord and [also] of the table of demons".
This follows on from vv 18-20. Israel were "partners in the altar" (v18, RSV) when they sacrificed, in that God and the worshippers both had their own shares in most of the sacrificed animals. Conversely, those who shared in the communal sacrificial meals of other gods were "partners with demons" (v20). It was necessary to choose. The same choice remains for Christians in that we now share in the "Lord's Supper", at the table over which the Lord presides. We must choose one or the other. The point is that we must avoid sharing in the worship of other gods, by participating in the their communal meals, and we must also avoid giving other people the impression that we are particpating indirectly.
If nobody else is involved, it seems to me that the deciding factor is what you yourself think you are doing if you get hold of meat which was previously "dedicated" to some other god. If you think you are participating in the original sacrificial meal, you are in the position of ch8 v7; "Some... eat food as really offered to an idol; and their conscience, being weak, is defiled."
But if you are giving thanks to God for your food (ch10 v30) and are confident that its previous history doesn't affect its value in the sight of God, then you are in the position of "liberty" in ch8 v8; "Food will not commend us to God". The dictum of ch10 v25, "Eat whatever is sold", can still apply even if we have asked the question anyway. In other words, it makes no difference one way or the other, unless we think it makes a difference. See the principle that runs through Galatians; we are living in liberty, not under law. |
81,217 | If you don't know that it has been sacrificed to idols, then it is okay,
1 Corinthians 10:
>
> 25Eat whatever is sold in the meat market **without raising any question** on the ground of conscience.
>
>
>
Don't ask. Just eat.
>
> 26For “the earth is the Lord’s, and the fullness thereof.” 27If one of the unbelievers invites you to dinner and you are disposed to go, eat whatever is set before you **without raising any question** on the ground of conscience.
>
>
>
Again, don't ask.
>
> 28But if someone says to you, “This has been offered in sacrifice,” then **do not eat it**, for the sake of the one who informed you, and for the sake of conscience—
>
>
>
If you know that it has been sacrificed to idols, then don't eat it in front of them.
>
> 29I do not mean your conscience, but his. For why should my liberty be determined by someone else’s conscience? 30If I partake with thankfulness, why am I denounced because of that for which I give thanks?
>
>
>
What if you know that it has been sacrificed to idols and no one else is around, is it okay to eat? | 2023/01/31 | [
"https://hermeneutics.stackexchange.com/questions/81217",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/35953/"
] | **First,** this section of scripture first appeared nearly 2,000 years ago, and was written to Christians who were surrounded by pagans who had a practice of presenting (offering) meat to their idols before taking it to the market to be sold as food. Therefore, when you ask, "Should ***we*** eat food sacrificed to idols?" you have jumped nearly 2,000 years to this day and age, I presume. I take it that you are asking Christians in the Year of our Lord 2023 whether to eat food sacrificed to idols, or not.
**Second**, where I live, I have no awareness of any food being presented before idols prior to being made available to anyone to buy. If you know of such practices, it would be helpful to either state a case (as an example of the pertinence of this question today) or to give a list of modern-day countries where this happens.
**Third,** ***the simple answer to your question*** (irrespective of any time from the middle of the first century A.D. until today) ***is "No, Christians should not."*** The matter is known to God, even if no other human knows you have eaten food that had been offered before an idol. ***Once you know, you are culpable, and God knows.*** Christians are to do everything (including their eating and drinking) for the glory of God. But, as the passage shows, there's no need to first hold an inquisition about it, asking questions, ferreting out individuals who might be suspected of the pagan practice and checking if a particular piece of food had been handled by them.
That section of scripture, however, has more to say on the matter than just that bit about food presented before an idol. It speaks of not eating meat that has not first been bled. But you do not ask about that, so I will end my answer here. | Underlying the OP question is an issue of reconciling the attitude of Acts (and Revelation) with that of Paul. Acts and Revelation forbid eating food offered to idols. For Paul, the pagan deities are not real, and their idols have no power. So he says:
>
> As to the eating of food offered to idols, we know that an idol has
> no real existence and that there is no God but one... We are no
> worse off if we do not eat, and no better off if we do. (1 Cor. 8:4,7)
>
>
>
But Acts is quite clear that for Christians, abstaining from such for is a requirement:
>
> For it has seemed good to the Holy Spirit and to us to lay upon you no
> greater burden than these necessary things: that you abstain from
> what has been sacrificed to idols and from blood and from what is
> strangled and from unchastity. If you keep yourselves from these, you
> will do well. (Acts 15:28-29)
>
>
>
And the Book of Revelation condemns eating such foods in no uncertain terms:
>
> You tolerate the woman Jez′ebel, who
> calls herself a prophetess and is teaching and beguiling my servants
> to practice immorality and to eat food sacrificed to idols. (Rev. 2:20)
>
>
>
Paul's solution to the problem was although no food is forbidden, a person should also respect the sensitivities of believers who think the pagan deities have real power. So he says:
>
> Only take care lest this liberty of yours somehow become a stumbling
> block to the weak. For if any one sees you, a man of knowledge, at
> table in an idol’s temple, might he not be encouraged, if his
> conscience is weak, to 'eat food offered to idols?' And so by your
> knowledge this weak man is destroyed, the brother for whom Christ
> died. Thus, sinning against your brethren and wounding their
> conscience when it is weak, you sin against Christ. Therefore, if food
> is a cause of my brother’s falling, I will never eat meat, lest I
> cause my brother to fall. (1 Cor. 8:9-13)
>
>
>
[![Photo of a Buddhist service with food on a table along with a statue of Buddha](https://i.stack.imgur.com/cruQS.jpg "Photo of a Buddhist service with food on a table along with a statue of Buddha")](https://i.stack.imgur.com/cruQS.jpg "Photo of a Buddhist service with food on a table along with a statue of Buddha")
In the first century, Christians had to decide whether to follow the letter of the rule given in Acts or to accept Paul's teaching that since idols have no power, we are free to eat foods offered to idols unless a fellow Christian's faith is threatened by such a thing. Today, the issue is generally moot. But when a fellow believer might be offended if I were to eat food offered to Krishna or Buddha, I need to decide whether it is a greater sin to turn down the food my host presents or to, in Paul's words, "tempt" fellow Christian to eat a supposedly forbidden food and thereby compromise his faith. |
81,217 | If you don't know that it has been sacrificed to idols, then it is okay,
1 Corinthians 10:
>
> 25Eat whatever is sold in the meat market **without raising any question** on the ground of conscience.
>
>
>
Don't ask. Just eat.
>
> 26For “the earth is the Lord’s, and the fullness thereof.” 27If one of the unbelievers invites you to dinner and you are disposed to go, eat whatever is set before you **without raising any question** on the ground of conscience.
>
>
>
Again, don't ask.
>
> 28But if someone says to you, “This has been offered in sacrifice,” then **do not eat it**, for the sake of the one who informed you, and for the sake of conscience—
>
>
>
If you know that it has been sacrificed to idols, then don't eat it in front of them.
>
> 29I do not mean your conscience, but his. For why should my liberty be determined by someone else’s conscience? 30If I partake with thankfulness, why am I denounced because of that for which I give thanks?
>
>
>
What if you know that it has been sacrificed to idols and no one else is around, is it okay to eat? | 2023/01/31 | [
"https://hermeneutics.stackexchange.com/questions/81217",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/35953/"
] | **TL;DR:** There is no reason we should care whether our food has been sacrificed to idols.
The underlying idea here is whether one is committing idolatry, which is the belief that anything, other than God or his agents, has any supernatural power or attribute.
Believing that a rabbit's foot provides good luck is a form of idolatry, but so is believing that food that has been sacrificed to an idol is somehow different from food that hasn't.
Neither the rabbit's foot nor the food have any supernatural attributes.
To avoid something because it is reputed to have a non-existent attribute is equivalent to admitting that it *does* have that attribute.
For you, it shouldn't matter at all whether the food was sacrificed, any more than you should care what the phase of the Moon is today, or what constellation was in the sky at your birth.
But, if someone gives you something and explicitly or implicitly tells you it has supernatural attributes, *then* you should refuse it.
Not because it makes any difference to you, but because it makes a difference to the other person.
By taking it, you are implicitly endorsing and encouraging false beliefs, rather than providing the good example that every Christian should be.
>
> But if someone says to you, “This has been offered in sacrifice,” then do not eat it, for the sake of the one who informed you, and for the sake of conscience —
> **I do not mean your conscience, but his.** For why should my liberty be determined by someone else’s conscience?
>
>
>
Here "conscience" means:
>
> as distinguishing between what is morally good and bad, prompting to do the former and shun the latter, commending the one, condemning the other
>
>
>
Rejecting the offered food shows the other person that you are condemning the act of sacrificing to idols.
---
Consider a non-religious analogy.
You are visiting Bavaria and when the waiter pours your coffee he proudly tells you that the pot he is holding was used by Hitler himself when he visited the inn in 1942.
What message does it send if you smile, say danke schön, and proceed to drink it?
What message does it send if you refuse the coffee? | Underlying the OP question is an issue of reconciling the attitude of Acts (and Revelation) with that of Paul. Acts and Revelation forbid eating food offered to idols. For Paul, the pagan deities are not real, and their idols have no power. So he says:
>
> As to the eating of food offered to idols, we know that an idol has
> no real existence and that there is no God but one... We are no
> worse off if we do not eat, and no better off if we do. (1 Cor. 8:4,7)
>
>
>
But Acts is quite clear that for Christians, abstaining from such for is a requirement:
>
> For it has seemed good to the Holy Spirit and to us to lay upon you no
> greater burden than these necessary things: that you abstain from
> what has been sacrificed to idols and from blood and from what is
> strangled and from unchastity. If you keep yourselves from these, you
> will do well. (Acts 15:28-29)
>
>
>
And the Book of Revelation condemns eating such foods in no uncertain terms:
>
> You tolerate the woman Jez′ebel, who
> calls herself a prophetess and is teaching and beguiling my servants
> to practice immorality and to eat food sacrificed to idols. (Rev. 2:20)
>
>
>
Paul's solution to the problem was although no food is forbidden, a person should also respect the sensitivities of believers who think the pagan deities have real power. So he says:
>
> Only take care lest this liberty of yours somehow become a stumbling
> block to the weak. For if any one sees you, a man of knowledge, at
> table in an idol’s temple, might he not be encouraged, if his
> conscience is weak, to 'eat food offered to idols?' And so by your
> knowledge this weak man is destroyed, the brother for whom Christ
> died. Thus, sinning against your brethren and wounding their
> conscience when it is weak, you sin against Christ. Therefore, if food
> is a cause of my brother’s falling, I will never eat meat, lest I
> cause my brother to fall. (1 Cor. 8:9-13)
>
>
>
[![Photo of a Buddhist service with food on a table along with a statue of Buddha](https://i.stack.imgur.com/cruQS.jpg "Photo of a Buddhist service with food on a table along with a statue of Buddha")](https://i.stack.imgur.com/cruQS.jpg "Photo of a Buddhist service with food on a table along with a statue of Buddha")
In the first century, Christians had to decide whether to follow the letter of the rule given in Acts or to accept Paul's teaching that since idols have no power, we are free to eat foods offered to idols unless a fellow Christian's faith is threatened by such a thing. Today, the issue is generally moot. But when a fellow believer might be offended if I were to eat food offered to Krishna or Buddha, I need to decide whether it is a greater sin to turn down the food my host presents or to, in Paul's words, "tempt" fellow Christian to eat a supposedly forbidden food and thereby compromise his faith. |
34,833,269 | Im trying to compare 2 Lists of the type Results, and it constantly just returns the entire list of results, it doesnt seem to filter anything out.
This is the code :
```
List<Results> Veranderingen = resultaten2.Except(resultaten).ToList();
foreach(Results x in Veranderingen)
{
MessageBox.Show("Nieuwe Data gevonden: " + x.titel + "Van de website" + x.url + "");
}
```
The code where the lists gets filled is this ( Less important ) :
```
private void Lijst2invullen()
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\martijn\Dropbox\Proftaak Periode 2 Identity\Database11.accdb;
Persist Security Info=False;";
connection.Open();
OleDbCommand cmd2 = new OleDbCommand();
cmd2.Connection = connection;
cmd2.CommandText = "SELECT ZoekcriteriaID from Zoekcriteria WHERE ZoekCriteria = '" + Convert.ToString(cbzoektermselecteren.Text) + "';";
OleDbDataReader reader2 = cmd2.ExecuteReader();
if (reader2.Read())
{
refreshid2 = Convert.ToInt32(reader2["ZoekcriteriaID"]);
}
OleDbCommand command5 = new OleDbCommand();
command5.Connection = connection;
command5.CommandText = "SELECT Titel, Webadress from Resultaat WHERE ZoekcriteriaID = " + refreshid2 + ";";
OleDbDataReader reader3 = command5.ExecuteReader();
while (reader3.Read())
{
Results result = new Results();
result.url = Convert.ToString(reader3["Webadress"]);
result.titel = Convert.ToString(reader3["Titel"]);
resultaten2.Add(result);
}
reader3.Close();
label1.Text = "Ziet er goed uit!";
}
private void Lijst1invullen()
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\martijn\Dropbox\Proftaak Periode 2 Identity\Database11.accdb;
Persist Security Info=False;";
connection.Open();
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = connection;
cmd1.CommandText = "SELECT ZoekcriteriaID from Zoekcriteria WHERE ZoekCriteria = '" + Convert.ToString(cbzoektermselecteren.Text) + "';";
OleDbDataReader reader1 = cmd1.ExecuteReader();
if (reader1.Read())
{
refreshid = Convert.ToInt32(reader1["ZoekcriteriaID"]);
}
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT Titel, Webadress from Resultaat WHERE ZoekcriteriaID = " + refreshid + ";";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Results result = new Results();
result.url = Convert.ToString(reader["Webadress"]);
result.titel = Convert.ToString(reader["Titel"]);
resultaten.Add(result);
}
reader.Close();
reader1.Close();
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = "DELETE * FROM Resultaat WHERE ZoekcriteriaID = " + refreshid + ";";
command2.ExecuteNonQuery();
OleDbCommand command3 = new OleDbCommand();
command3.Connection = connection;
command3.CommandText = "DELETE * FROM Zoekcriteria WHERE ZoekCriteriaID = " + refreshid + ";";
command3.ExecuteNonQuery();
search.zoekterm = cbzoektermselecteren.Text;
search.InsertZoekcriteria();
search.searchding();
}
```
I think I'm doing something wrong in the syntax of the Except method could anyone help me out? | 2016/01/16 | [
"https://Stackoverflow.com/questions/34833269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5789654/"
] | There are two ways to compare (for equality) two `Results` objects (and all reference type objects in general):
* The first way is to compare the values of the properties of the two `Results` objects.
* The second way is to compare the references themselves. And by that I mean that two `Results` objects are equal if they are actually a single object but you have two references to it. For example, you can create a single `Results` object and put it in two lists.
The objects in the two lists are clearly different objects, so I am guessing that you want to use the first way of comparison.
By default, equality check of reference type objects in C# is of the second type. However, you can override this behavior if you want.
One way of overriding this behavior is to override the `Equals` and `GetHashCode` methods in the class. Here is an example:
```
public class Results
{
public string url { get; set; }
public string title { get; set; }
public override bool Equals(object obj)
{
Results other = obj as Results;
if (other == null)
return false;
return other.url == this.url && other.title == this.title;
}
public override int GetHashCode()
{
return new {url, title}.GetHashCode();
}
}
```
This way, we are telling the system how it should test equality for objects of this type. | I'm sure Yacoub's answer would work and is probably the preferred solution in most cases, but in case you can't modify the Results class, here is another way to do it. Define an implementation of IEqualityComparer for Results, and then pass it as the second argument of the Except method.
EDIT:
```
class Results {
public string FirstName { get; set; }
public string LastName { get; set; }
}
class ResultsEqualityComparer : IEqualityComparer<Results> {
public bool Equals(Results res1, Results res2) {
return (res1.FirstName == res2.FirstName && res1.LastName == res2.LastName);
}
public int GetHashCode(Results res) {
return new { res.FirstName, res.LastName }.GetHashCode();
}
}
```
// and here's the example of code passing the ResultsComparer to Except:
```
var resultaten = new List<Results>() {
new Results() {FirstName="Bob", LastName="Smith"},
new Results() {FirstName="Ted", LastName="Wilson"},
new Results() {FirstName="Alice", LastName="Wilson"},
new Results() {FirstName="Carol", LastName="Smith"}
};
var resultaten2 = new List<Results>() {
new Results() {FirstName="William", LastName="Smith"},
new Results() {FirstName="Ted", LastName="Wilson"},
new Results() {FirstName="Gerhardt", LastName="Wilson"},
new Results() {FirstName="Carol", LastName="Smith"}
};
var comparer = new ResultsEqualityComparer();
List<Results> Veranderingen = resultaten2.Except(resultaten, comparer).ToList();
foreach (var x in Veranderingen) {
Console.WriteLine(x.FirstName + " " + x.LastName);
}
```
// prints out:
William Smith
Gerhardt Wilson |
6,290,013 | I have a class that takes a List in the constructor;
```
public class MyClass {
private List<Structure> structures;
public MyClass(List<Structure> structures) {
this.structures = structures;
}
}
```
that I need to instantiate via reflection. How do I define the call to class.getConstructor() to find this?
Regards | 2011/06/09 | [
"https://Stackoverflow.com/questions/6290013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497087/"
] | This should work:
```
Constructor<MyClass> constructor = MyClass.class.getConstructor(List.class);
```
or
```
Constructor constructor = MyClass.class.getConstructor(new Class[]{List.class});
```
for Java 1.4.x or less | You can find it just by passing in `List.class`. For example:
```
import java.util.*;
import java.lang.reflect.*;
public class Test {
public static void main(String[] args) throws Exception {
Class<?> clazz = MyClass.class;
Constructor<?> ctor = clazz.getConstructor(List.class);
ctor.newInstance(new Object[] { null });
}
}
```
If you need to validate the generic parameter types, you can use [`getGenericParameterTypes`](http://download.oracle.com/javase/6/docs/api/java/lang/reflect/Constructor.html#getGenericParameterTypes%28%29) and examine the `Type[]` which it returns. For example:
```
Type[] types = ctor.getGenericParameterTypes();
System.out.println(types[0]); // Prints java.util.List<Structure>
```
You don't need to specify the type argument when you call `getConstructor` because you can't overload the constructor by using parameters with *just* different type parameters. Those parameter types would have the same *type erasure*. For example, if you try to add another constructor with this signature:
```
public MyClass(List<String> structures)
```
you'll get an error like this:
>
> MyClass.java:7: name clash: `MyClass(java.util.List<java.lang.String>)` and
> `MyClass(java.util.List<Structure>)` have the same erasure
>
>
> |
15,718,694 | I am trying to cast varchar to bigint. Then inserting it into an int column. I found that I am not getting expected value. Then I tried the following statements:
```
DECLARE @varData VARCHAR(50)
SET @varData = '0000019.33'
select cast(@varData *cast(100 as float) as bigint)
select cast(@varData *cast(100 as float) as varchar)
select cast(cast(@varData *cast(100 as float) as varchar) as float)
```
Results:
```
1932
1933
1933
```
I am not able to understand why this difference is coming. But when I change the value to `0000029.33` then there is no difference in results.
I am stuck and do not have any idea why it's so happening. Help needed..!!! | 2013/03/30 | [
"https://Stackoverflow.com/questions/15718694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2227059/"
] | please see this [Difference between numeric,float and decimal in sql server](https://stackoverflow.com/questions/1056323/difference-between-numeric-float-and-decimal-in-sql-server)
For you question, you should try CAST @vardata as numeric, like this
```
SELECT CAST(CAST(@varData AS numeric(27,9)) * 100 AS bigint)
``` | it happens because sql round the data, so lets say if u pick the wrong integer instead of 2.97 u will get 3.
now try to imagine how much data will be lost if u want to convert just 0.000002 :)
hope u understand better now
```
DECLARE @varData VARCHAR(50),
@float float,
@bigint bigint
SET @varData = '0000019.33'
set @bigint = convert ( bigint, (convert ( float, @vardata )) )
print @bigint
--or
set @float= convert ( float, @vardata )
set @bigint=convert ( bigint, @float)
print @bigint
``` |
76,907 | What's the meaning of fasts, is it only a physical deed of abstain from food and drinks? Because often in scriptures it's listed or placed in context of prayer, repentance, mourning or done to show a certain depending on HaShem. What has a physical deed of abstaining from food and drinks has to do with all of this? It helps us humble ourselves or afflict ourselves but where does this lead to, what is it's meaning to do this through fasting? | 2016/10/14 | [
"https://judaism.stackexchange.com/questions/76907",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/4762/"
] | I come from the mindset that no law is strictly physical/spiritual. They blur into one another and provide benefits which merge those aspects.
Fasting is powerful in a spiritual sense because you are choosing to take control of a baser instinct. Hunger is as basic as breathing or sleepiness, so by choosing to overrule that instinct in reflection of a spiritual observance/exercise you are strengthening your divine traits and suppressing primal traits. Torah teaches that the **Nefesh HaBehamit** "animal soul" is in conflict with our **Nefesh Ha'elokit** (divine soul)
If you are interested in a more detailed explanation of the parts of the soul, you can read more in the Tanya at this link:
**<http://www.chabad.org/library/tanya/tanya_cdo/aid/7880/jewish/Chapter-1.htm>**
These comprise two different sections of our soul which are in a battle for control. By doing spiritual exercises (such as fasting) you can drive down the animalistic urges and raise yourself to a higher state of craving. You can move from craving that which is harmful to craving that which is beneficial if you practice and focus your time/energy. Fasting is just one of those exercises.
Fasting also has a symbolism associated with it in relation to the pain that hunger causes. When we observe **Tisha B'Av** (just one example) we fast. This holiday is a memorial in reflection various wrongs of Jewish history. One of the main reflections is on the loss of the holy temples (first and second).
Some reading regarding Tisha B'Av and the tradition of the observance:
**<http://www.chabad.org/library/article_cdo/aid/946703/jewish/What-happened-on-the-Ninth-of-Av.htm>**
This hunger pain is symbolic of the spiritual pain of our people. We sit in hunger and reflect on this pain and attach that pain to the wrongs and errors of Jewish history. By doing that, we take an impersonal history and we connect to it. I can't know what it was like to lose the holy temple because I never had the holy temple. That doesn't mean I can't reflect on what that loss has done to my ancestors and my peers of today.
By connecting the pain of our people to a pain which is rooted in our biology, we groom ourselves to make the suffering of our past a part of who we are. That strengthens us and drives us to honor the past, make peace with the present, and overcome the trials and tribulations of the future.
A very detailed reading regarding the purpose of fasting in relation to Judaism:
**<http://www.aish.com/atr/What_is_the_Purpose_of_Fasting.html>**
**From a physical/scientific standpoint.**
Fasting has been found to promote health benefits when done in a controlled manner over regulated periods of time. They recently discovered that if an individual fasts for a period of three days, their immune system resets itself.
**<http://www.telegraph.co.uk/science/2016/03/12/fasting-for-three-days-can-regenerate-entire-immune-system-study/>**
Your body uses the time without food to correct issues on a biological level.
Keep in mind, these are controlled fasts which are not extended beyond this period of time. Going beyond this period of time can harm you if you withhold sustenance for too long. Our bodies need nutrition to function correctly. | Fasting is a way of attaining a more spiritual state/frame of mind by disconnecting from physical pleasures. This more spiritual state is more conducive to Teshuva. See Nesivos Olam: Nesiv Hateshuva chapter 7 (beginning from the second paragraph) and Derech Hashem part 4 chapter 8:5 (regarding Yom Kippur).
However, today it is not recommended to fast (apart from the biblically/rabbinically mandated fasts) because it weakens the body and impairs the ability to think and learn Torah (Krina D'igrissa 1:16,17). |
76,907 | What's the meaning of fasts, is it only a physical deed of abstain from food and drinks? Because often in scriptures it's listed or placed in context of prayer, repentance, mourning or done to show a certain depending on HaShem. What has a physical deed of abstaining from food and drinks has to do with all of this? It helps us humble ourselves or afflict ourselves but where does this lead to, what is it's meaning to do this through fasting? | 2016/10/14 | [
"https://judaism.stackexchange.com/questions/76907",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/4762/"
] | R' Hirsch writes in Horeb that the purpose of all fast days is Teshuva, and gives the following explanation (ch. 33, Dayan Grunfeld's translation):
>
> Fasting, i.e. abstaining from all kinds of nourishment for one day, should help in mastering the animal in man, in calling a halt to striving for self-gratification and in showing that a firm will can well remain the victor. It should also bring home the thought whether what made it possible for us to control our impulses and cravings - or, at any rate, the most pressing ones - for one day, could not make it possible for every day; and if we cannot control all such impulses, then at least we should shun the impure, the exuberant and the forbidden. Fasting, therefore, should contribute towards the eradication of one of the sources of sin, pleasure-seeking.
>
>
>
Fasting is meant to demonstrate to ourselves the ability and purpose of not indulging in the physicality which leads to sin. | Fasting is a way of attaining a more spiritual state/frame of mind by disconnecting from physical pleasures. This more spiritual state is more conducive to Teshuva. See Nesivos Olam: Nesiv Hateshuva chapter 7 (beginning from the second paragraph) and Derech Hashem part 4 chapter 8:5 (regarding Yom Kippur).
However, today it is not recommended to fast (apart from the biblically/rabbinically mandated fasts) because it weakens the body and impairs the ability to think and learn Torah (Krina D'igrissa 1:16,17). |
40,211 | Как правильно говорить "Ты хотел опята?" или "Ты хотел опят?". Есть ли какое-то правило употребления в том или ином случае? | 2014/10/08 | [
"https://rus.stackexchange.com/questions/40211",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/4200/"
] | Конечно "опят". Мн.ч. р.п. "Нет опят". Ещё эти грибы во множественном числе могут называться "опёнки".
Ваш вопрос напомнил мне приезжих отдыхающих, которые на пляже говорят: "Я хочу раки, а ты будешь раки?". Это же изнасилование русского языка.
Хотя, поразмыслив, дополню, зависит от контекста:
Можно сказать, например: "Я слышал, что ты проголодался. Ты хотел опят? Жаль, но они кончились". Тут будет родительный падеж.
А можно сказать: "Какие грибы ты думал увидеть в лесу? Слышал, ты хотел найти опята? Извини, они тут не растут". Тогда будет винительный падеж. | Не все так просто.
"*Ты же сама приготовила из крабов, а я так люблю **крабы**!*" – цитата из всем известного фильма.
Чем крабы хуже опят? Люблю крабы, хочу опята...
Думаю, что оба варианта верны. Что с крабами, что с опятами. |
40,211 | Как правильно говорить "Ты хотел опята?" или "Ты хотел опят?". Есть ли какое-то правило употребления в том или ином случае? | 2014/10/08 | [
"https://rus.stackexchange.com/questions/40211",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/4200/"
] | ***"Ты хочешь опят?"*** и ***"Ты хочешь опята?"*** - оба варианта возможны. Первое сейчас употребляется много чаще. Но это частота определяется не столько даже разницей в смысле (она есть, но не четкая), сколько традицией и аналогией.
//======
Попробую пояснить, хотя это довольно муторно...
Вообще-то вопрос этот из серии "если кит - и вдруг на слона - кто кого сборет?"
Глагол "хотеть" может управлять и родительным, и винительным падежом.
Давайте разберемся сначала с единственным числом.
Для одушевленных существительных падежи совпадают: *"Ты хочешь щенка?"* - и никаких вопросов не порождают.
Для неодушевленного уже сложнее. Глагол "хотеть", возможно как раз под влиянием формы для одушевленных объектов, опционально изменил управление с винительного на родительный - оставаясь при этом глаголом переходным. Первая тенденция требует одной формы, второй факт - другой. "*Ты хочешь ножик?*" - *"Ты хочешь **о**рдена?"*. Между этими двумя случаями есть небольшая смысловая разница, грамматисты её прекрасно знают, я здесь полный разбор опускаю, ограничусь частным указанием, что первое тут означает конкретное реальное желание, второе - отдаленное, абстрактное или несбыточное. Но это не строго.
Множественное число в принципе работает по тем же правилам, но в силу традиции частота родительного падежа сильно перевешивает. В тех же контекстах *"Ты хочешь ножиков"* будет употребляться чаще, чем *"ты хочешь ножики?"*. Возможно потому, что категория конкретности у множественного числа заметно ниже, чем у единственного. Тем не менее винительный падеж все еще вполне возможен, особенно в тех случаях, когда множественное число имеет смысловой (не грамматический!) оттенок собирательности: *"Ты хочешь помидоры?"* и *"Ты хочешь помидоров?"* равноправны. А смысловое различие идет уже не по линии "конкретное"-"абстрактное", а по разделу "общее-частное".
Перейдем к грибам. Тоже издали.
*"Ты хочешь (жареные) подосиновики, подберезовики, шампиньоны, маслята?"* - никаких проблем. Как блюдо, кушанье... Шампиньоны, вроде, не жарят, но с грамматикой все в порядке.
*"Ты хочешь (жареных) подосиновиков, шампиньонов, подберезовиков, маслят?"* - тем более все ОК. Особенно, если речь идет о небольшой порции.
С "лисичками" хуже. Лисичка - слово грамматически одушевленное. Поэтому форма "лисичек" преобладает, хотя и *"хочешь лисички?"* вполне возможна.
Что ж такого происходит с опятами-опенками, что заставляет большинство носителей языка говорить именно *"Хочешь опят?"* вопреки всем вышевысказанным грамматическим соображениям?
Попробуем разобраться. Как было показано, сами по себе соображения о падеже и/или одушевленности ничего не определяют. Но, как совершенно верно заметила Екатерина, "опята" - это форма особая. Исторически "опята" было неправильным, слово "опенок" не имеет суффикса "-енок-": "-ен-" - от "пня", корень - "пен". Это абсолютно препятствовало образованию формы "опята", нормативным считалось "опенки" - и этим они отличались от "маслят". Поэтому *"хочешь опенки?"* (В.п) вполне успешно конкурировало с *"хочешь опенков"* (Р.п.)- и, видимо, даже преобладало.
Но дальше под влиянием *"масленок"-"маслята"* и т.п. де-факто произошло переразложение слова *"опенок"*, *"-енок-"* стало восприниматься как суффикс, порождающий во множественном числе новую форму "опята". И вот для этой-то новой формы, для которой соверешенно отсутствовала грамматическая традиция разделения родительного и винительного падежей, равно как само ощущение её неодушевленности, появилось закрепленное простой использования *"хочешь опят"* - как субъективно единственная возможная форма в обоих падежах и всех значениях. Но грамматически более правильную *"Хочешь опята?"* для винительного падежа (равно как и саму возможность использования винительного падежа для неодушевленных существительных) никто не отменял. Поэтому *"Ты хочешь опята?"* никак нельзя лишать прав на нормативность.
И в заключение. Разговоры про форму винительного падежа для всякой снеди редко проходят мимо ставшей знаменитой у филологов фразы "А я так люблю крабы" из "Иронии судьбы".
Так вот, будьте уверены, герой Мягкова сказал все правильно. Во всяком случае - с точки зрения грамматики.
Я здесь этим заявлением и ограничусь. | Правильно: ты хочешь/хотел опят (Р.п.). Неправильно: ты хочешь/хотел опята (В.п.)
ПОЯСНЕНИЕ
Ряд глаголов: хотеть, ждать, требовать, желать, просить - имеют колеблющуюся переходность. Это означает, что объект, которым управляет глагол, может употребляться в В.п.(переходный глагол) и в Р.п. (непереходный глагол).
Винительный падеж обозначает полный охват предмета действием, а родительный падеж обозначает действие, касающееся границ предмета (отложительно-достигательное значение Р.падежа).
Сравним: я хочу конфету (В.п., эту конкретную конфету) - я хочу конфет (Р.п., не все конфеты, которые существуют, а вообще конфет). |
40,211 | Как правильно говорить "Ты хотел опята?" или "Ты хотел опят?". Есть ли какое-то правило употребления в том или ином случае? | 2014/10/08 | [
"https://rus.stackexchange.com/questions/40211",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/4200/"
] | Конечно "опят". Мн.ч. р.п. "Нет опят". Ещё эти грибы во множественном числе могут называться "опёнки".
Ваш вопрос напомнил мне приезжих отдыхающих, которые на пляже говорят: "Я хочу раки, а ты будешь раки?". Это же изнасилование русского языка.
Хотя, поразмыслив, дополню, зависит от контекста:
Можно сказать, например: "Я слышал, что ты проголодался. Ты хотел опят? Жаль, но они кончились". Тут будет родительный падеж.
А можно сказать: "Какие грибы ты думал увидеть в лесу? Слышал, ты хотел найти опята? Извини, они тут не растут". Тогда будет винительный падеж. | ..Падежи..
В данном случае - винительный. |
40,211 | Как правильно говорить "Ты хотел опята?" или "Ты хотел опят?". Есть ли какое-то правило употребления в том или ином случае? | 2014/10/08 | [
"https://rus.stackexchange.com/questions/40211",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/4200/"
] | Правильно: ***Ты хотел опят?***
Дело в том, что существительное ОПЯТА (ед.ОПЁНОК) не совсем обычное. Оно склоняется так же, как существительные КОТЯТА, МЕДВЕЖАТА и другие одушевлённые существительные с суффиксом -ат, ят. Существительные МАСЛЁНОК - МАСЛЯТА относятся к этой же группе.
***Ср.: Ты видел котят. - Ты хотел опят.*** | Не все так просто.
"*Ты же сама приготовила из крабов, а я так люблю **крабы**!*" – цитата из всем известного фильма.
Чем крабы хуже опят? Люблю крабы, хочу опята...
Думаю, что оба варианта верны. Что с крабами, что с опятами. |
40,211 | Как правильно говорить "Ты хотел опята?" или "Ты хотел опят?". Есть ли какое-то правило употребления в том или ином случае? | 2014/10/08 | [
"https://rus.stackexchange.com/questions/40211",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/4200/"
] | ***"Ты хочешь опят?"*** и ***"Ты хочешь опята?"*** - оба варианта возможны. Первое сейчас употребляется много чаще. Но это частота определяется не столько даже разницей в смысле (она есть, но не четкая), сколько традицией и аналогией.
//======
Попробую пояснить, хотя это довольно муторно...
Вообще-то вопрос этот из серии "если кит - и вдруг на слона - кто кого сборет?"
Глагол "хотеть" может управлять и родительным, и винительным падежом.
Давайте разберемся сначала с единственным числом.
Для одушевленных существительных падежи совпадают: *"Ты хочешь щенка?"* - и никаких вопросов не порождают.
Для неодушевленного уже сложнее. Глагол "хотеть", возможно как раз под влиянием формы для одушевленных объектов, опционально изменил управление с винительного на родительный - оставаясь при этом глаголом переходным. Первая тенденция требует одной формы, второй факт - другой. "*Ты хочешь ножик?*" - *"Ты хочешь **о**рдена?"*. Между этими двумя случаями есть небольшая смысловая разница, грамматисты её прекрасно знают, я здесь полный разбор опускаю, ограничусь частным указанием, что первое тут означает конкретное реальное желание, второе - отдаленное, абстрактное или несбыточное. Но это не строго.
Множественное число в принципе работает по тем же правилам, но в силу традиции частота родительного падежа сильно перевешивает. В тех же контекстах *"Ты хочешь ножиков"* будет употребляться чаще, чем *"ты хочешь ножики?"*. Возможно потому, что категория конкретности у множественного числа заметно ниже, чем у единственного. Тем не менее винительный падеж все еще вполне возможен, особенно в тех случаях, когда множественное число имеет смысловой (не грамматический!) оттенок собирательности: *"Ты хочешь помидоры?"* и *"Ты хочешь помидоров?"* равноправны. А смысловое различие идет уже не по линии "конкретное"-"абстрактное", а по разделу "общее-частное".
Перейдем к грибам. Тоже издали.
*"Ты хочешь (жареные) подосиновики, подберезовики, шампиньоны, маслята?"* - никаких проблем. Как блюдо, кушанье... Шампиньоны, вроде, не жарят, но с грамматикой все в порядке.
*"Ты хочешь (жареных) подосиновиков, шампиньонов, подберезовиков, маслят?"* - тем более все ОК. Особенно, если речь идет о небольшой порции.
С "лисичками" хуже. Лисичка - слово грамматически одушевленное. Поэтому форма "лисичек" преобладает, хотя и *"хочешь лисички?"* вполне возможна.
Что ж такого происходит с опятами-опенками, что заставляет большинство носителей языка говорить именно *"Хочешь опят?"* вопреки всем вышевысказанным грамматическим соображениям?
Попробуем разобраться. Как было показано, сами по себе соображения о падеже и/или одушевленности ничего не определяют. Но, как совершенно верно заметила Екатерина, "опята" - это форма особая. Исторически "опята" было неправильным, слово "опенок" не имеет суффикса "-енок-": "-ен-" - от "пня", корень - "пен". Это абсолютно препятствовало образованию формы "опята", нормативным считалось "опенки" - и этим они отличались от "маслят". Поэтому *"хочешь опенки?"* (В.п) вполне успешно конкурировало с *"хочешь опенков"* (Р.п.)- и, видимо, даже преобладало.
Но дальше под влиянием *"масленок"-"маслята"* и т.п. де-факто произошло переразложение слова *"опенок"*, *"-енок-"* стало восприниматься как суффикс, порождающий во множественном числе новую форму "опята". И вот для этой-то новой формы, для которой соверешенно отсутствовала грамматическая традиция разделения родительного и винительного падежей, равно как само ощущение её неодушевленности, появилось закрепленное простой использования *"хочешь опят"* - как субъективно единственная возможная форма в обоих падежах и всех значениях. Но грамматически более правильную *"Хочешь опята?"* для винительного падежа (равно как и саму возможность использования винительного падежа для неодушевленных существительных) никто не отменял. Поэтому *"Ты хочешь опята?"* никак нельзя лишать прав на нормативность.
И в заключение. Разговоры про форму винительного падежа для всякой снеди редко проходят мимо ставшей знаменитой у филологов фразы "А я так люблю крабы" из "Иронии судьбы".
Так вот, будьте уверены, герой Мягкова сказал все правильно. Во всяком случае - с точки зрения грамматики.
Я здесь этим заявлением и ограничусь. | ..Падежи..
В данном случае - винительный. |
40,211 | Как правильно говорить "Ты хотел опята?" или "Ты хотел опят?". Есть ли какое-то правило употребления в том или ином случае? | 2014/10/08 | [
"https://rus.stackexchange.com/questions/40211",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/4200/"
] | Правильно: ты хочешь/хотел опят (Р.п.). Неправильно: ты хочешь/хотел опята (В.п.)
ПОЯСНЕНИЕ
Ряд глаголов: хотеть, ждать, требовать, желать, просить - имеют колеблющуюся переходность. Это означает, что объект, которым управляет глагол, может употребляться в В.п.(переходный глагол) и в Р.п. (непереходный глагол).
Винительный падеж обозначает полный охват предмета действием, а родительный падеж обозначает действие, касающееся границ предмета (отложительно-достигательное значение Р.падежа).
Сравним: я хочу конфету (В.п., эту конкретную конфету) - я хочу конфет (Р.п., не все конфеты, которые существуют, а вообще конфет). | ..Падежи..
В данном случае - винительный. |
40,211 | Как правильно говорить "Ты хотел опята?" или "Ты хотел опят?". Есть ли какое-то правило употребления в том или ином случае? | 2014/10/08 | [
"https://rus.stackexchange.com/questions/40211",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/4200/"
] | Не все так просто.
"*Ты же сама приготовила из крабов, а я так люблю **крабы**!*" – цитата из всем известного фильма.
Чем крабы хуже опят? Люблю крабы, хочу опята...
Думаю, что оба варианта верны. Что с крабами, что с опятами. | ..Падежи..
В данном случае - винительный. |
40,211 | Как правильно говорить "Ты хотел опята?" или "Ты хотел опят?". Есть ли какое-то правило употребления в том или ином случае? | 2014/10/08 | [
"https://rus.stackexchange.com/questions/40211",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/4200/"
] | Правильно: ***Ты хотел опят?***
Дело в том, что существительное ОПЯТА (ед.ОПЁНОК) не совсем обычное. Оно склоняется так же, как существительные КОТЯТА, МЕДВЕЖАТА и другие одушевлённые существительные с суффиксом -ат, ят. Существительные МАСЛЁНОК - МАСЛЯТА относятся к этой же группе.
***Ср.: Ты видел котят. - Ты хотел опят.*** | Правильно: ты хочешь/хотел опят (Р.п.). Неправильно: ты хочешь/хотел опята (В.п.)
ПОЯСНЕНИЕ
Ряд глаголов: хотеть, ждать, требовать, желать, просить - имеют колеблющуюся переходность. Это означает, что объект, которым управляет глагол, может употребляться в В.п.(переходный глагол) и в Р.п. (непереходный глагол).
Винительный падеж обозначает полный охват предмета действием, а родительный падеж обозначает действие, касающееся границ предмета (отложительно-достигательное значение Р.падежа).
Сравним: я хочу конфету (В.п., эту конкретную конфету) - я хочу конфет (Р.п., не все конфеты, которые существуют, а вообще конфет). |
40,211 | Как правильно говорить "Ты хотел опята?" или "Ты хотел опят?". Есть ли какое-то правило употребления в том или ином случае? | 2014/10/08 | [
"https://rus.stackexchange.com/questions/40211",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/4200/"
] | Конечно "опят". Мн.ч. р.п. "Нет опят". Ещё эти грибы во множественном числе могут называться "опёнки".
Ваш вопрос напомнил мне приезжих отдыхающих, которые на пляже говорят: "Я хочу раки, а ты будешь раки?". Это же изнасилование русского языка.
Хотя, поразмыслив, дополню, зависит от контекста:
Можно сказать, например: "Я слышал, что ты проголодался. Ты хотел опят? Жаль, но они кончились". Тут будет родительный падеж.
А можно сказать: "Какие грибы ты думал увидеть в лесу? Слышал, ты хотел найти опята? Извини, они тут не растут". Тогда будет винительный падеж. | Правильно: ты хочешь/хотел опят (Р.п.). Неправильно: ты хочешь/хотел опята (В.п.)
ПОЯСНЕНИЕ
Ряд глаголов: хотеть, ждать, требовать, желать, просить - имеют колеблющуюся переходность. Это означает, что объект, которым управляет глагол, может употребляться в В.п.(переходный глагол) и в Р.п. (непереходный глагол).
Винительный падеж обозначает полный охват предмета действием, а родительный падеж обозначает действие, касающееся границ предмета (отложительно-достигательное значение Р.падежа).
Сравним: я хочу конфету (В.п., эту конкретную конфету) - я хочу конфет (Р.п., не все конфеты, которые существуют, а вообще конфет). |
40,211 | Как правильно говорить "Ты хотел опята?" или "Ты хотел опят?". Есть ли какое-то правило употребления в том или ином случае? | 2014/10/08 | [
"https://rus.stackexchange.com/questions/40211",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/4200/"
] | ***"Ты хочешь опят?"*** и ***"Ты хочешь опята?"*** - оба варианта возможны. Первое сейчас употребляется много чаще. Но это частота определяется не столько даже разницей в смысле (она есть, но не четкая), сколько традицией и аналогией.
//======
Попробую пояснить, хотя это довольно муторно...
Вообще-то вопрос этот из серии "если кит - и вдруг на слона - кто кого сборет?"
Глагол "хотеть" может управлять и родительным, и винительным падежом.
Давайте разберемся сначала с единственным числом.
Для одушевленных существительных падежи совпадают: *"Ты хочешь щенка?"* - и никаких вопросов не порождают.
Для неодушевленного уже сложнее. Глагол "хотеть", возможно как раз под влиянием формы для одушевленных объектов, опционально изменил управление с винительного на родительный - оставаясь при этом глаголом переходным. Первая тенденция требует одной формы, второй факт - другой. "*Ты хочешь ножик?*" - *"Ты хочешь **о**рдена?"*. Между этими двумя случаями есть небольшая смысловая разница, грамматисты её прекрасно знают, я здесь полный разбор опускаю, ограничусь частным указанием, что первое тут означает конкретное реальное желание, второе - отдаленное, абстрактное или несбыточное. Но это не строго.
Множественное число в принципе работает по тем же правилам, но в силу традиции частота родительного падежа сильно перевешивает. В тех же контекстах *"Ты хочешь ножиков"* будет употребляться чаще, чем *"ты хочешь ножики?"*. Возможно потому, что категория конкретности у множественного числа заметно ниже, чем у единственного. Тем не менее винительный падеж все еще вполне возможен, особенно в тех случаях, когда множественное число имеет смысловой (не грамматический!) оттенок собирательности: *"Ты хочешь помидоры?"* и *"Ты хочешь помидоров?"* равноправны. А смысловое различие идет уже не по линии "конкретное"-"абстрактное", а по разделу "общее-частное".
Перейдем к грибам. Тоже издали.
*"Ты хочешь (жареные) подосиновики, подберезовики, шампиньоны, маслята?"* - никаких проблем. Как блюдо, кушанье... Шампиньоны, вроде, не жарят, но с грамматикой все в порядке.
*"Ты хочешь (жареных) подосиновиков, шампиньонов, подберезовиков, маслят?"* - тем более все ОК. Особенно, если речь идет о небольшой порции.
С "лисичками" хуже. Лисичка - слово грамматически одушевленное. Поэтому форма "лисичек" преобладает, хотя и *"хочешь лисички?"* вполне возможна.
Что ж такого происходит с опятами-опенками, что заставляет большинство носителей языка говорить именно *"Хочешь опят?"* вопреки всем вышевысказанным грамматическим соображениям?
Попробуем разобраться. Как было показано, сами по себе соображения о падеже и/или одушевленности ничего не определяют. Но, как совершенно верно заметила Екатерина, "опята" - это форма особая. Исторически "опята" было неправильным, слово "опенок" не имеет суффикса "-енок-": "-ен-" - от "пня", корень - "пен". Это абсолютно препятствовало образованию формы "опята", нормативным считалось "опенки" - и этим они отличались от "маслят". Поэтому *"хочешь опенки?"* (В.п) вполне успешно конкурировало с *"хочешь опенков"* (Р.п.)- и, видимо, даже преобладало.
Но дальше под влиянием *"масленок"-"маслята"* и т.п. де-факто произошло переразложение слова *"опенок"*, *"-енок-"* стало восприниматься как суффикс, порождающий во множественном числе новую форму "опята". И вот для этой-то новой формы, для которой соверешенно отсутствовала грамматическая традиция разделения родительного и винительного падежей, равно как само ощущение её неодушевленности, появилось закрепленное простой использования *"хочешь опят"* - как субъективно единственная возможная форма в обоих падежах и всех значениях. Но грамматически более правильную *"Хочешь опята?"* для винительного падежа (равно как и саму возможность использования винительного падежа для неодушевленных существительных) никто не отменял. Поэтому *"Ты хочешь опята?"* никак нельзя лишать прав на нормативность.
И в заключение. Разговоры про форму винительного падежа для всякой снеди редко проходят мимо ставшей знаменитой у филологов фразы "А я так люблю крабы" из "Иронии судьбы".
Так вот, будьте уверены, герой Мягкова сказал все правильно. Во всяком случае - с точки зрения грамматики.
Я здесь этим заявлением и ограничусь. | Не все так просто.
"*Ты же сама приготовила из крабов, а я так люблю **крабы**!*" – цитата из всем известного фильма.
Чем крабы хуже опят? Люблю крабы, хочу опята...
Думаю, что оба варианта верны. Что с крабами, что с опятами. |
14,749,629 | ```
<style type="text/css">
<!--
.style1 {
color: #666666;
font-weight: bold;
}
.style8 {font-size: 12px; color: #333333; }
.style9 {
font-size: 12px;
font-weight: bold;
color: #FFFFFF;
}
.style12 {font-size: 12px; font-weight: bold; color: #666666; }
.style13 {font-size: 12px; font-weight: bold; color: #0066FF; }
.style14 {
color: #0043A8;
font-size: 16px;
}
.style15 {color: #FFFFFF}
.style16 {color: #990000}
.style18 {color: #990000; font-size: 12px; }
.style20 {font-size: 12px; font-weight: bold; color: #575757; }
-->
</style>
```
above stylesheet is enclosed in `<!-- -->` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like <http://www.w3schools.com/css/css_howto.asp> which I think is very valid reference) | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1684670/"
] | This is done to avoid displaying the script content in some (old) browsers which don't know about `<style>` markup. See [this](http://lachy.id.au/log/2005/05/script-comments). | Few browsers consider the `non-HTML` codes as plain text. This comment is used to guide that browser i.e the code is commented so that `browsers` will not display it as html output. |
14,749,629 | ```
<style type="text/css">
<!--
.style1 {
color: #666666;
font-weight: bold;
}
.style8 {font-size: 12px; color: #333333; }
.style9 {
font-size: 12px;
font-weight: bold;
color: #FFFFFF;
}
.style12 {font-size: 12px; font-weight: bold; color: #666666; }
.style13 {font-size: 12px; font-weight: bold; color: #0066FF; }
.style14 {
color: #0043A8;
font-size: 16px;
}
.style15 {color: #FFFFFF}
.style16 {color: #990000}
.style18 {color: #990000; font-size: 12px; }
.style20 {font-size: 12px; font-weight: bold; color: #575757; }
-->
</style>
```
above stylesheet is enclosed in `<!-- -->` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like <http://www.w3schools.com/css/css_howto.asp> which I think is very valid reference) | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1684670/"
] | that's not a comment... it's a way to hide such text block from old browsers parser (mainly IE6-)
It's the same as using the [CDATA](http://en.wikipedia.org/wiki/CDATA) technique on the `<script>` tag... to **protect bad parsing of the data** from really weird engines (mainly IE) :)
though the **correct way** would be using:
for styles
==========
```
<style type="text/css">
/*<![CDATA[*/
body { color: yellow; }
/*]]>*/
</style>
```
for scripts
===========
```
<script type="text/javascript">
//<![CDATA[
$(function() { ... });
//]]>
</script>
```
using `CDATA` in both cases is the **correct and safe way**, the *comment* way it's just a trick to accomplish the same end result.
---
Now, regarding your **I think is very valid reference** when pointing out W3Schools, have a look at this:
>
> <http://w3fools.com/>
>
>
> | This is done to avoid displaying the script content in some (old) browsers which don't know about `<style>` markup. See [this](http://lachy.id.au/log/2005/05/script-comments). |
14,749,629 | ```
<style type="text/css">
<!--
.style1 {
color: #666666;
font-weight: bold;
}
.style8 {font-size: 12px; color: #333333; }
.style9 {
font-size: 12px;
font-weight: bold;
color: #FFFFFF;
}
.style12 {font-size: 12px; font-weight: bold; color: #666666; }
.style13 {font-size: 12px; font-weight: bold; color: #0066FF; }
.style14 {
color: #0043A8;
font-size: 16px;
}
.style15 {color: #FFFFFF}
.style16 {color: #990000}
.style18 {color: #990000; font-size: 12px; }
.style20 {font-size: 12px; font-weight: bold; color: #575757; }
-->
</style>
```
above stylesheet is enclosed in `<!-- -->` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like <http://www.w3schools.com/css/css_howto.asp> which I think is very valid reference) | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1684670/"
] | It is an antiquated method of hiding content from browsers who are older than the standard that introduced `<style>` or `<script>` tags.
There is no valid use for such a habit anymore and in fact will cause more problems than it fixes.
Unless you are developing a website for peolpe living in the 1990's (like the editors at w3schools)... don't do it! | This is done to avoid displaying the script content in some (old) browsers which don't know about `<style>` markup. See [this](http://lachy.id.au/log/2005/05/script-comments). |
14,749,629 | ```
<style type="text/css">
<!--
.style1 {
color: #666666;
font-weight: bold;
}
.style8 {font-size: 12px; color: #333333; }
.style9 {
font-size: 12px;
font-weight: bold;
color: #FFFFFF;
}
.style12 {font-size: 12px; font-weight: bold; color: #666666; }
.style13 {font-size: 12px; font-weight: bold; color: #0066FF; }
.style14 {
color: #0043A8;
font-size: 16px;
}
.style15 {color: #FFFFFF}
.style16 {color: #990000}
.style18 {color: #990000; font-size: 12px; }
.style20 {font-size: 12px; font-weight: bold; color: #575757; }
-->
</style>
```
above stylesheet is enclosed in `<!-- -->` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like <http://www.w3schools.com/css/css_howto.asp> which I think is very valid reference) | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1684670/"
] | It's a hack for older browsers that didn't support CSS/style tag... See <http://www.w3.org/TR/html4/present/styles.html#h-14.5> | Few browsers consider the `non-HTML` codes as plain text. This comment is used to guide that browser i.e the code is commented so that `browsers` will not display it as html output. |
14,749,629 | ```
<style type="text/css">
<!--
.style1 {
color: #666666;
font-weight: bold;
}
.style8 {font-size: 12px; color: #333333; }
.style9 {
font-size: 12px;
font-weight: bold;
color: #FFFFFF;
}
.style12 {font-size: 12px; font-weight: bold; color: #666666; }
.style13 {font-size: 12px; font-weight: bold; color: #0066FF; }
.style14 {
color: #0043A8;
font-size: 16px;
}
.style15 {color: #FFFFFF}
.style16 {color: #990000}
.style18 {color: #990000; font-size: 12px; }
.style20 {font-size: 12px; font-weight: bold; color: #575757; }
-->
</style>
```
above stylesheet is enclosed in `<!-- -->` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like <http://www.w3schools.com/css/css_howto.asp> which I think is very valid reference) | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1684670/"
] | that's not a comment... it's a way to hide such text block from old browsers parser (mainly IE6-)
It's the same as using the [CDATA](http://en.wikipedia.org/wiki/CDATA) technique on the `<script>` tag... to **protect bad parsing of the data** from really weird engines (mainly IE) :)
though the **correct way** would be using:
for styles
==========
```
<style type="text/css">
/*<![CDATA[*/
body { color: yellow; }
/*]]>*/
</style>
```
for scripts
===========
```
<script type="text/javascript">
//<![CDATA[
$(function() { ... });
//]]>
</script>
```
using `CDATA` in both cases is the **correct and safe way**, the *comment* way it's just a trick to accomplish the same end result.
---
Now, regarding your **I think is very valid reference** when pointing out W3Schools, have a look at this:
>
> <http://w3fools.com/>
>
>
> | Few browsers consider the `non-HTML` codes as plain text. This comment is used to guide that browser i.e the code is commented so that `browsers` will not display it as html output. |
14,749,629 | ```
<style type="text/css">
<!--
.style1 {
color: #666666;
font-weight: bold;
}
.style8 {font-size: 12px; color: #333333; }
.style9 {
font-size: 12px;
font-weight: bold;
color: #FFFFFF;
}
.style12 {font-size: 12px; font-weight: bold; color: #666666; }
.style13 {font-size: 12px; font-weight: bold; color: #0066FF; }
.style14 {
color: #0043A8;
font-size: 16px;
}
.style15 {color: #FFFFFF}
.style16 {color: #990000}
.style18 {color: #990000; font-size: 12px; }
.style20 {font-size: 12px; font-weight: bold; color: #575757; }
-->
</style>
```
above stylesheet is enclosed in `<!-- -->` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like <http://www.w3schools.com/css/css_howto.asp> which I think is very valid reference) | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1684670/"
] | It is an antiquated method of hiding content from browsers who are older than the standard that introduced `<style>` or `<script>` tags.
There is no valid use for such a habit anymore and in fact will cause more problems than it fixes.
Unless you are developing a website for peolpe living in the 1990's (like the editors at w3schools)... don't do it! | Few browsers consider the `non-HTML` codes as plain text. This comment is used to guide that browser i.e the code is commented so that `browsers` will not display it as html output. |
14,749,629 | ```
<style type="text/css">
<!--
.style1 {
color: #666666;
font-weight: bold;
}
.style8 {font-size: 12px; color: #333333; }
.style9 {
font-size: 12px;
font-weight: bold;
color: #FFFFFF;
}
.style12 {font-size: 12px; font-weight: bold; color: #666666; }
.style13 {font-size: 12px; font-weight: bold; color: #0066FF; }
.style14 {
color: #0043A8;
font-size: 16px;
}
.style15 {color: #FFFFFF}
.style16 {color: #990000}
.style18 {color: #990000; font-size: 12px; }
.style20 {font-size: 12px; font-weight: bold; color: #575757; }
-->
</style>
```
above stylesheet is enclosed in `<!-- -->` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like <http://www.w3schools.com/css/css_howto.asp> which I think is very valid reference) | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1684670/"
] | that's not a comment... it's a way to hide such text block from old browsers parser (mainly IE6-)
It's the same as using the [CDATA](http://en.wikipedia.org/wiki/CDATA) technique on the `<script>` tag... to **protect bad parsing of the data** from really weird engines (mainly IE) :)
though the **correct way** would be using:
for styles
==========
```
<style type="text/css">
/*<![CDATA[*/
body { color: yellow; }
/*]]>*/
</style>
```
for scripts
===========
```
<script type="text/javascript">
//<![CDATA[
$(function() { ... });
//]]>
</script>
```
using `CDATA` in both cases is the **correct and safe way**, the *comment* way it's just a trick to accomplish the same end result.
---
Now, regarding your **I think is very valid reference** when pointing out W3Schools, have a look at this:
>
> <http://w3fools.com/>
>
>
> | It's a hack for older browsers that didn't support CSS/style tag... See <http://www.w3.org/TR/html4/present/styles.html#h-14.5> |
14,749,629 | ```
<style type="text/css">
<!--
.style1 {
color: #666666;
font-weight: bold;
}
.style8 {font-size: 12px; color: #333333; }
.style9 {
font-size: 12px;
font-weight: bold;
color: #FFFFFF;
}
.style12 {font-size: 12px; font-weight: bold; color: #666666; }
.style13 {font-size: 12px; font-weight: bold; color: #0066FF; }
.style14 {
color: #0043A8;
font-size: 16px;
}
.style15 {color: #FFFFFF}
.style16 {color: #990000}
.style18 {color: #990000; font-size: 12px; }
.style20 {font-size: 12px; font-weight: bold; color: #575757; }
-->
</style>
```
above stylesheet is enclosed in `<!-- -->` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like <http://www.w3schools.com/css/css_howto.asp> which I think is very valid reference) | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1684670/"
] | It is an antiquated method of hiding content from browsers who are older than the standard that introduced `<style>` or `<script>` tags.
There is no valid use for such a habit anymore and in fact will cause more problems than it fixes.
Unless you are developing a website for peolpe living in the 1990's (like the editors at w3schools)... don't do it! | It's a hack for older browsers that didn't support CSS/style tag... See <http://www.w3.org/TR/html4/present/styles.html#h-14.5> |
14,749,629 | ```
<style type="text/css">
<!--
.style1 {
color: #666666;
font-weight: bold;
}
.style8 {font-size: 12px; color: #333333; }
.style9 {
font-size: 12px;
font-weight: bold;
color: #FFFFFF;
}
.style12 {font-size: 12px; font-weight: bold; color: #666666; }
.style13 {font-size: 12px; font-weight: bold; color: #0066FF; }
.style14 {
color: #0043A8;
font-size: 16px;
}
.style15 {color: #FFFFFF}
.style16 {color: #990000}
.style18 {color: #990000; font-size: 12px; }
.style20 {font-size: 12px; font-weight: bold; color: #575757; }
-->
</style>
```
above stylesheet is enclosed in `<!-- -->` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like <http://www.w3schools.com/css/css_howto.asp> which I think is very valid reference) | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1684670/"
] | that's not a comment... it's a way to hide such text block from old browsers parser (mainly IE6-)
It's the same as using the [CDATA](http://en.wikipedia.org/wiki/CDATA) technique on the `<script>` tag... to **protect bad parsing of the data** from really weird engines (mainly IE) :)
though the **correct way** would be using:
for styles
==========
```
<style type="text/css">
/*<![CDATA[*/
body { color: yellow; }
/*]]>*/
</style>
```
for scripts
===========
```
<script type="text/javascript">
//<![CDATA[
$(function() { ... });
//]]>
</script>
```
using `CDATA` in both cases is the **correct and safe way**, the *comment* way it's just a trick to accomplish the same end result.
---
Now, regarding your **I think is very valid reference** when pointing out W3Schools, have a look at this:
>
> <http://w3fools.com/>
>
>
> | It is an antiquated method of hiding content from browsers who are older than the standard that introduced `<style>` or `<script>` tags.
There is no valid use for such a habit anymore and in fact will cause more problems than it fixes.
Unless you are developing a website for peolpe living in the 1990's (like the editors at w3schools)... don't do it! |
43,527,850 | This is my link for getting one random article using Wiki API:
```
https://en.wikipedia.org/w/api.php?%20format=json&action=query&prop=extracts&exsentences=2&exintro=&explaintext=&generator=random&grnnamespace=0
```
I need to get from it the first two sentences of the first section, and it works pretty well.
---
I want to use this kind of link and search this random article in a specific category. This is what I have tried after searching online:
```
https://en.wikipedia.org/w/api.php?%20format=json&action=query&prop=extracts&exsentences=2&exintro=&explaintext=&generator=random&grnnamespace=0&cmtitle=Category:Music
```
(I have added this part to the original link: `cmtitle=Category:Music` )
It doesn't work for me.
It gets the random article like the first link (not under a wanted category, which is Music in this link). | 2017/04/20 | [
"https://Stackoverflow.com/questions/43527850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7483311/"
] | There is no API to get a random category member (and using a parameter from some unrelated API module is certainly not going to help). You could screen scrape [Special:RandomInCategory](https://en.wikipedia.org/wiki/Special:RandomInCategory) (or turn it into an API module - [patches welcome](https://phabricator.wikimedia.org/T63840) :) | try to use `cmlimit` to get all of the catgeorymembers, then use a programming language, like [Python](https://python.org) to request the page, then store every catgeory in an array, and use the `random` module to get a random catgeorymember from the array you stored them in. then you can use it in a link to get the specific page for the categorymember or anything else that you need. |
41,725,613 | Being new to systematic debugging, I asked myself what these three terms mean:
1. **Debugging**
2. **Profiling**
3. **Tracing**
Anyone could provide definitions? | 2017/01/18 | [
"https://Stackoverflow.com/questions/41725613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3757139/"
] | Well... as I was typing the tags for my question, it appeared that stack overflow already had defined the terms in the tags description. Here their definitions which I found very good:
>
> **[Remote debugging](https://stackoverflow.com/tags/remote-debugging/info)** is the process of running a debug session in a local development environment attached to a remotely deployed application.
>
>
> **[Profiling](https://stackoverflow.com/tags/profiling/info)** is the process of measuring an application or system by running an analysis tool called a profiler. Profiling tools can focus on many aspects: functions call times and count, memory usage, cpu load, and resource usage.
>
>
> **[Tracing](https://stackoverflow.com/tags/tracing/info)** is a specialized use of logging to record information about a program's execution.
>
>
> | In addition to the answer from Samuel:
1. **Debugging** is the process of looking for bugs and their cause in applications. a bug can be an error or just some unexpected behaviour (e.g. a user complains that he/she receives an error when he/she uses an invalid date format). typically a debugger is used that can pause the execution of an application, examine variables and manipulate them.
2. **Profiling** is a dynamic analysis process that collects information about the execution of an application. the type of information that is collected depends on your use case, e.g. the number of requests. the result of profiling is a profile with the collected information. the source for a profile can be exact events (see tracing below) or a sample of events that occured.
because the data is aggregated in a profile it is irrelevant when and in which order the events happened.
3. **Tracing** "trace is a log of events within to the program"(Whitham). those events can be ordered chronologically. thats why they often contain a timestamp. Tracing is the process of generating and collecting those events. the use case is typically flow analysis.
example tracing vs profiling:
```
Trace:
[2021-06-12T11:22:09.815479Z] [INFO] [Thread-1] Request started
[2021-06-12T11:22:09.935612Z] [INFO] [Thread-1] Request finished
[2021-06-12T11:22:59.344566Z] [INFO] [Thread-1] Request started
[2021-06-12T11:22:59.425697Z] [INFO] [Thread-1] Request finished
Profile:
2 "Request finished" Events
2 "Request started" Events
```
so if tracing and profiling measure the same events you can construct a profile from a trace but not the other way around.
source
Whitham: <https://www.jwhitham.org/2016/02/profiling-versus-tracing.html>
IPM: <http://ipm-hpc.sourceforge.net/profilingvstracing.html> |
41,843,490 | Everytime I get different output when I run this program.
Is there any way to get consistent output with in run method only?
```
public class MultiBasic1 {
public static void main(String[] args) {
ChildThread th1=new ChildThread();
ChildThread th2= new ChildThread();
ChildThread th3= new ChildThread();
ChildThread th4= new ChildThread();
th1.start();
th2.start();
th3.start();
th4.start();
}
}
class ChildThread extends Thread{
synchronized public void run(){
for(int i=1; i<=5; i++)
System.out.println(i);
}
}
``` | 2017/01/25 | [
"https://Stackoverflow.com/questions/41843490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Because you're creating a new instance of `ChildThread`, each thread is allowed to access the `run` method without restriction, as there is only one thread actually accessing the method.
To demonstrate how `synchronized` works, you'd need to have some kind shared resource, such as a `Object` which each thread could interact with
```
public class Test {
public static void main(String[] args) {
Action action = new Action();
Thread t1 = new Thread(new Runner(action), "1");
Thread t2 = new Thread(new Runner(action), "2");
Thread t3 = new Thread(new Runner(action), "3");
Thread t4 = new Thread(new Runner(action), "4");
Thread t5 = new Thread(new Runner(action), "5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
public static class Runner implements Runnable {
private Action action;
public Runner(Action action) {
this.action = action;
}
@Override
public void run() {
action.makeItSo();
}
}
public static class Action {
public synchronized void makeItSo() {
for (int index = 0; index < 10; index++) {
System.out.println(Thread.currentThread().getName() + " - " + index);
}
}
}
}
```
The above example demonstrates that only one thread can run within the `makeItSo` method, but also, that there is no guarantee over which thread will be allowed to run (ie the order) | Here there is even no need of synchronization since you are using different objects for calling the run method.
Synchronization works when multiples threads of one object is in picture.
Above example will be more meaningful if you do something like below.
```
public class MultiBasic1 {
public static void main(String[] args) {
ChildThread th1=new ChildThread();
Thread t1 = new Thread(th1);
Thread t2 = new Thread(th1);
Thread t3 = new Thread(th1);
Thread t4 = new Thread(th1);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class ChildThread extends Thread{
synchronized public void run(){
for(int i=1; i<=5; i++)
System.out.println(i);
}
}
``` |
41,843,490 | Everytime I get different output when I run this program.
Is there any way to get consistent output with in run method only?
```
public class MultiBasic1 {
public static void main(String[] args) {
ChildThread th1=new ChildThread();
ChildThread th2= new ChildThread();
ChildThread th3= new ChildThread();
ChildThread th4= new ChildThread();
th1.start();
th2.start();
th3.start();
th4.start();
}
}
class ChildThread extends Thread{
synchronized public void run(){
for(int i=1; i<=5; i++)
System.out.println(i);
}
}
``` | 2017/01/25 | [
"https://Stackoverflow.com/questions/41843490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Why you are getting different output?
Answer:
synchronized requires an object on which lock is attained before entering the synchronized block or method.
In this case lock is being attained on the objects on which the method is executed hence thread 1 is locking on object th1, thread 2 is locking on th2 and so on.
therefore, all the threads are locking onto different objects and are allowed to run simultaneously.
How to get consistent output?
Answer
option 1: you can use join to join the threads to main thread
public class MultiBasic1 {
```
public static void main(String[] args) throws InterruptedException {
ChildThread th1=new ChildThread();
ChildThread th2= new ChildThread();
ChildThread th3= new ChildThread();
ChildThread th4= new ChildThread();
th1.setName("A");
th2.setName("B");
th3.setName("C");
th4.setName("D");
th1.start();
th1.join();
th2.start();
th2.join();
th3.start();
th3.join();
th4.start();
th4.join();
}
```
}
class ChildThread extends Thread{
```
public void run(){
for(int i=1; i<=5; i++)
System.out.println(i + " " + getName());
}
```
}
option 2: provide shared object for synchronized block to synchronize the threads
public class MultiBasic1 {
```
public static void main(String[] args) throws InterruptedException {
ChildThread th1=new ChildThread();
ChildThread th2= new ChildThread();
ChildThread th3= new ChildThread();
ChildThread th4= new ChildThread();
th1.setName("A");
th2.setName("B");
th3.setName("C");
th4.setName("D");
th1.start();
th2.start();
th3.start();
th4.start();
}
```
}
class ChildThread extends Thread{
```
private static final Object lock = new Object();
public void run(){
synchronized (lock) {
for(int i=1; i<=5; i++)
System.out.println(i + " " + getName());
}
}
```
} | Here there is even no need of synchronization since you are using different objects for calling the run method.
Synchronization works when multiples threads of one object is in picture.
Above example will be more meaningful if you do something like below.
```
public class MultiBasic1 {
public static void main(String[] args) {
ChildThread th1=new ChildThread();
Thread t1 = new Thread(th1);
Thread t2 = new Thread(th1);
Thread t3 = new Thread(th1);
Thread t4 = new Thread(th1);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class ChildThread extends Thread{
synchronized public void run(){
for(int i=1; i<=5; i++)
System.out.println(i);
}
}
``` |
41,843,490 | Everytime I get different output when I run this program.
Is there any way to get consistent output with in run method only?
```
public class MultiBasic1 {
public static void main(String[] args) {
ChildThread th1=new ChildThread();
ChildThread th2= new ChildThread();
ChildThread th3= new ChildThread();
ChildThread th4= new ChildThread();
th1.start();
th2.start();
th3.start();
th4.start();
}
}
class ChildThread extends Thread{
synchronized public void run(){
for(int i=1; i<=5; i++)
System.out.println(i);
}
}
``` | 2017/01/25 | [
"https://Stackoverflow.com/questions/41843490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Because you're creating a new instance of `ChildThread`, each thread is allowed to access the `run` method without restriction, as there is only one thread actually accessing the method.
To demonstrate how `synchronized` works, you'd need to have some kind shared resource, such as a `Object` which each thread could interact with
```
public class Test {
public static void main(String[] args) {
Action action = new Action();
Thread t1 = new Thread(new Runner(action), "1");
Thread t2 = new Thread(new Runner(action), "2");
Thread t3 = new Thread(new Runner(action), "3");
Thread t4 = new Thread(new Runner(action), "4");
Thread t5 = new Thread(new Runner(action), "5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
public static class Runner implements Runnable {
private Action action;
public Runner(Action action) {
this.action = action;
}
@Override
public void run() {
action.makeItSo();
}
}
public static class Action {
public synchronized void makeItSo() {
for (int index = 0; index < 10; index++) {
System.out.println(Thread.currentThread().getName() + " - " + index);
}
}
}
}
```
The above example demonstrates that only one thread can run within the `makeItSo` method, but also, that there is no guarantee over which thread will be allowed to run (ie the order) | Why you are getting different output?
Answer:
synchronized requires an object on which lock is attained before entering the synchronized block or method.
In this case lock is being attained on the objects on which the method is executed hence thread 1 is locking on object th1, thread 2 is locking on th2 and so on.
therefore, all the threads are locking onto different objects and are allowed to run simultaneously.
How to get consistent output?
Answer
option 1: you can use join to join the threads to main thread
public class MultiBasic1 {
```
public static void main(String[] args) throws InterruptedException {
ChildThread th1=new ChildThread();
ChildThread th2= new ChildThread();
ChildThread th3= new ChildThread();
ChildThread th4= new ChildThread();
th1.setName("A");
th2.setName("B");
th3.setName("C");
th4.setName("D");
th1.start();
th1.join();
th2.start();
th2.join();
th3.start();
th3.join();
th4.start();
th4.join();
}
```
}
class ChildThread extends Thread{
```
public void run(){
for(int i=1; i<=5; i++)
System.out.println(i + " " + getName());
}
```
}
option 2: provide shared object for synchronized block to synchronize the threads
public class MultiBasic1 {
```
public static void main(String[] args) throws InterruptedException {
ChildThread th1=new ChildThread();
ChildThread th2= new ChildThread();
ChildThread th3= new ChildThread();
ChildThread th4= new ChildThread();
th1.setName("A");
th2.setName("B");
th3.setName("C");
th4.setName("D");
th1.start();
th2.start();
th3.start();
th4.start();
}
```
}
class ChildThread extends Thread{
```
private static final Object lock = new Object();
public void run(){
synchronized (lock) {
for(int i=1; i<=5; i++)
System.out.println(i + " " + getName());
}
}
```
} |
55,123,258 | I have Grafana and postgres installed and connected. I use grafana to display charts of data I add to postgres. My postgres database has a table with records from multiple sources. The schema looks like this:
```
time | source | bid | ask
12:01 | bitmex | 10 | 11
12:01 | deribit| 10 | 11
12:02 | bitmex | 9 | 11
```
The exact times per source are different. I’m able to plot different lines for every source:
[![enter image description here](https://i.stack.imgur.com/rLc08.png)](https://i.stack.imgur.com/rLc08.png)
I’m looking to plot the difference (grouped per minute) of two different sources. I think I need to select grouped minutes where “source = x” and the same where “source = y” and subtract those, while keeping the time macros from Grafana in there to keep the whole thing speedy. Can anyone point me in the right direction? I don't think this is at all possible with the "graphical query builder" in grafana. | 2019/03/12 | [
"https://Stackoverflow.com/questions/55123258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/843033/"
] | I wrote some basic example and I used your XML file.. You can examine that..
**XML file**
```
<?xml version="1.0"?>
<ArrayOfInternship xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Internship>
<Title>Marketing</Title>
<Start>2019-03-08T00:00:00</Start>
<End>2019-04-12T00:00:00</End>
<Supervisor>John Smith</Supervisor>
<Comments>Web site makeover.</Comments>
</Internship>
<Internship>
<Title>Marketing 2</Title>
<Start>2019-03-08T00:00:00</Start>
<End>2019-04-12T00:00:00</End>
<Supervisor>John Smith</Supervisor>
<Comments>Web site makeover.</Comments>
</Internship>
</ArrayOfInternship>
```
**this is the model which one is you will use**
```
public class InternshipModel
{
public string Title { get; set; }
public string Start { get; set; }
public string End{ get; set; }
public string Supervisor{ get; set; }
public string Comments{ get; set; }
}
```
**this part pars xml file and add to listbox**
```
// Loading from a file, you can also load from a stream
var xml = XDocument.Load(@"InternList.xml");
// Query the data and write out a subset of contacts
var query = (from c in xml.Root.Descendants("Internship")
select new InternshipModel
{
Title = c.Element("Title").Value,
Start = c.Element("Start").Value,
End = c.Element("End").Value,
Supervisor = c.Element("Supervisor").Value,
Comments = c.Element("Comments").Value
}).ToList();
foreach (InternshipModel model in query)
{
listBox1.Items.Add("Title: " + model.Title +
"Start: " + model.Start +
"End: " + model.End +
"Supervisor: " + model.Supervisor +
"Comments: " + model.Comments);
}
``` | One possible solution
```
XmlDocument xmldocIntern = new XmlDocument();
xmldocIntern.Load(@"InternList.xml");
var oc = new ListBox.ObjectCollection(lstBxListIntern, xmldocIntern.DocumentElement.GetElementsByTagName("Title").Cast<XmlNode>().Select(node => node.InnerText).ToArray());
``` |
55,123,258 | I have Grafana and postgres installed and connected. I use grafana to display charts of data I add to postgres. My postgres database has a table with records from multiple sources. The schema looks like this:
```
time | source | bid | ask
12:01 | bitmex | 10 | 11
12:01 | deribit| 10 | 11
12:02 | bitmex | 9 | 11
```
The exact times per source are different. I’m able to plot different lines for every source:
[![enter image description here](https://i.stack.imgur.com/rLc08.png)](https://i.stack.imgur.com/rLc08.png)
I’m looking to plot the difference (grouped per minute) of two different sources. I think I need to select grouped minutes where “source = x” and the same where “source = y” and subtract those, while keeping the time macros from Grafana in there to keep the whole thing speedy. Can anyone point me in the right direction? I don't think this is at all possible with the "graphical query builder" in grafana. | 2019/03/12 | [
"https://Stackoverflow.com/questions/55123258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/843033/"
] | I think you may be having an issue with trying to get the value of the Title tag because you're trying to grab the first attribute of every XML element but the only element that has an attribute is `ArrayOfInternship`.
There are a couple of ways that you could extract all of the titles from all Internship elements in the array.
First would be looping and uses the `XmlDocument` class like what your code uses
```
XmlDocument doc = new XmlDocument();
doc.Load(@"InternList.xml");
// Loop over child nodes of <ArrayOfInternship>...
foreach (XmlNode node in doc.DocumentElement)
{
// Loop over the child nodes of the <Internship> nodes
foreach (XmlNode child in node.ChildNodes)
{
if (child.Name.Equals("Title", StringComparison.OrdinalIgnoreCase))
{
lstBxListIntern.Items.Add(child.InnerText);
}
}
}
```
The second solution that I came up with and personally like better because it's more succinct. You probably want to utilize the above solution since you are a beginner and it will most likely be easier for you to read. But here's the other solution using LINQ to XML.
```
XElement xml = XElement.Load(@"InternList.xml");
var titles = xml.Descendants("Title")
.Select(x => x.Value)
.ToList();
lstBxListIntern.Items.AddRange(titles);
```
Let me know if you need any clarification on what I mentioned and I'll be happy to clarify. | One possible solution
```
XmlDocument xmldocIntern = new XmlDocument();
xmldocIntern.Load(@"InternList.xml");
var oc = new ListBox.ObjectCollection(lstBxListIntern, xmldocIntern.DocumentElement.GetElementsByTagName("Title").Cast<XmlNode>().Select(node => node.InnerText).ToArray());
``` |
37,742,717 | I'm uploading one csv file to the server. The file is reading the data and saving into the database but, the problem with my server is the maximum execution time is 180sec. I'm unable to upload all my data in the csv within 180sec. Server is showing like"**Service is unavailable**" after 180 sec. So i decided to complete the **csv upload in the background**. I tried few plugins but i'm getting errors like plugin not found and few other. I need a solution in the **cakephp.** Thanks in advance | 2016/06/10 | [
"https://Stackoverflow.com/questions/37742717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6448903/"
] | I doubt the upload itself takes 180 seconds. You should rethink your design and collect the data first and then write it to the database, maybe using bulk insert if available in cakephp. | You can extend the execution time like this.
```
ini_set('max_execution_time', 600); //600 seconds = 10 minutes
```
Put this at the top of the CSV upload script. You can change the second parameter according to your need. |
37,742,717 | I'm uploading one csv file to the server. The file is reading the data and saving into the database but, the problem with my server is the maximum execution time is 180sec. I'm unable to upload all my data in the csv within 180sec. Server is showing like"**Service is unavailable**" after 180 sec. So i decided to complete the **csv upload in the background**. I tried few plugins but i'm getting errors like plugin not found and few other. I need a solution in the **cakephp.** Thanks in advance | 2016/06/10 | [
"https://Stackoverflow.com/questions/37742717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6448903/"
] | I doubt the upload itself takes 180 seconds. You should rethink your design and collect the data first and then write it to the database, maybe using bulk insert if available in cakephp. | Step 1 – Data Base Connection
At first we need to connect to database…
File Name: connection.php
```
<?php
$db = mysql_connect("Database", "username", "password") or die("Could not connect.");
if(!$db)
die("no db");
if(!mysql_select_db("Databasename",$db))
die("No database selected.");
?>
```
Step 2 – upload page
Making connection to data base by calling the connection.php, clean the table of its old data, insert new uploaded data into table…
File Name: upload.php
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Upload page</title>
<style type="text/css">
body {
background: #E3F4FC;
font: normal 14px/30px Helvetica, Arial, sans-serif;
color: #2b2b2b;
}
a {
color:#898989;
font-size:14px;
font-weight:bold;
text-decoration:none;
}
a:hover {
color:#CC0033;
}
h1 {
font: bold 14px Helvetica, Arial, sans-serif;
color: #CC0033;
}
h2 {
font: bold 14px Helvetica, Arial, sans-serif;
color: #898989;
}
#container {
background: #CCC;
margin: 100px auto;
width: 945px;
}
#form {padding: 20px 150px;}
#form input {margin-bottom: 20px;}
</style>
</head>
<body>
<div id="container">
<div id="form">
<?php
include "connection.php"; //Connect to Database
$deleterecords = "TRUNCATE TABLE tablename"; //empty the table of its current records
mysql_query($deleterecords);
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into tablename(item1,item2,item3,item4,item5) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
//view upload form
}else {
print "Upload new csv by browsing to file and clicking on Upload<br />\n";
print "<form enctype='multipart/form-data' action='upload.php' method='post'>";
print "File name to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
</div>
</div>
</body>
</html>
``` |
36,251,112 | I have a list of files:
```
PS S:\temp> dir
Directory: S:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 3/28/2016 2:07 AM 0 00001_asdfasdfsa df.txt
-a--- 3/28/2016 2:07 AM 0 00002_asdfasdfsa df - Copy (3).txt
-a--- 3/28/2016 2:07 AM 0 00003_asdfasdfsa df - Copy.txt
-a--- 3/28/2016 2:07 AM 0 00004_asdfasdfsa df - Copy (6).txt
-a--- 3/28/2016 2:07 AM 0 00005_asdfasdfsa df - Copy (5).txt
-a--- 3/28/2016 2:07 AM 0 00006_asdfasdfsa df - Copy (4).txt
-a--- 3/28/2016 2:07 AM 0 00007_asdfasdfsa df - Copy (2).txt
-a--- 3/28/2016 2:07 AM 0 700006_asdfasdfsa df - Copy (4) - Copy.txt
PS S:\temp>
```
I want to renamem those that start with five numbers and an underline. The new name will add a number I specified to the leading numbers of those file names. For example, if I add 10, the new names would be:
```
PS S:\temp> dir
Directory: S:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 3/28/2016 2:07 AM 0 00011_asdfasdfsa df.txt
-a--- 3/28/2016 2:07 AM 0 00012_asdfasdfsa df - Copy (3).txt
-a--- 3/28/2016 2:07 AM 0 00013_asdfasdfsa df - Copy.txt
-a--- 3/28/2016 2:07 AM 0 00014_asdfasdfsa df - Copy (6).txt
-a--- 3/28/2016 2:07 AM 0 00015_asdfasdfsa df - Copy (5).txt
-a--- 3/28/2016 2:07 AM 0 00016_asdfasdfsa df - Copy (4).txt
-a--- 3/28/2016 2:07 AM 0 00017_asdfasdfsa df - Copy (2).txt
-a--- 3/28/2016 2:07 AM 0 700006_asdfasdfsa df - Copy (4) - Copy.txt
PS S:\temp>
```
Now my PowerShell code is:
```
dir * | ?{$_.name -match '^\d{5}_.+'} | Rename-Item -NewName {$_.name -replace '^(\d{5})(_.+)', ((([convert]::ToInt32('$1', 10) + 12).ToString("00000")) + '$2')} -whatif
```
I can't find any errors in my code. But when I run it, I got the following error message:
```
Rename-Item : The input to the script block for parameter 'NewName' failed. Exception calling "ToInt32" with "2" argument(s): "Could not find any recognizable digits."
At line:1 char:62
+ dir * | ?{$_.name -match '^\d{5}_.+'} | Rename-Item -NewName {$_.name -replace ' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (S:\temp\00001_asdfasdfsa df.txt:PSObject) [Rename-Item], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentInvocationFailed,Microsoft.PowerShell.Commands.RenameItemCommand
```
My question is, where I am wrong? Is it because I should not use functions in the replacement part of the `replace` operator? If so, how to write complex logic in `-newname{}`? Thanks. | 2016/03/27 | [
"https://Stackoverflow.com/questions/36251112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170931/"
] | You cannot use `-replace` and massage the data at the time of the substitution. Your replacement was failing as the string literal `$1` cannot be converted to integer. As discussed in a similar question: [Passing a function to Powershell's (replace) function](https://stackoverflow.com/questions/8163061/passing-a-function-to-powershells-replace-function) you can use a scriptblock and the .nNet regex static method `Replace`.
```
$replaceBlock = {
# Groups 0 contains the whole match. 1 is the first group... and so on.
([convert]::ToInt32($args[0].Groups[1],10) + 12).ToString("00000") + $args[0].Groups[2]
}
Get-ChildItem | Where-Object{$_.name -match '^\d{5}_.+'} | Rename-Item -NewName {
[Regex]::Replace($_.name, '^(\d{5})(_.+)', $replaceBlock)
} -whatif
```
You can use the script block inline but getting it out makes for a little cleaner code. However I would likely use `-match` and the returned `$matches` object to do the same thing.
```
Get-ChildItem | Where-Object{$_.name -match '^(\d{5})(_.+)'} | Rename-Item -NewName {
([int]$Matches[1] + 12).ToString("00000") + $Matches[2]
} -whatif
```
Note that I updated the `where-object` to have capture groups. | Haha, I got an answer.
```
dir * | ?{$_.name -match '^\d{5}_.+'} | Rename-Item -NewName {(([convert]::toint32($_.name.substring(0, 5), 10) + 12).ToString("00000")) + $_.name.substring(5)} -whatif
```
Just found that I can use any code in the `-newname{}` block. But I still don't understand why my `-replace` way did not work. |
25,457,631 | Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image.
But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image.
And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why.
![enter image description here](https://i.stack.imgur.com/I325u.png)
Do you know how can I have an effect like this my image below?
![enter image description here](https://i.stack.imgur.com/kL9DV.png)
**I forget to create a fiddle with my issue:** <http://jsfiddle.net/ejjtepfo/2/>
**My Html:**
```
<div class="modal">
<h2>Title of news</h2>
<span id="data">20/10/2014</span><br />
<img class="img" src=""/>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p>
<div class="clear_p"></div>
<div id="pdfs">
<h3>Links</h3>
<ul class="links">
<li> <a href=""></a>Link 1</li>
<li> <a href=""></a>Link 2</li>http://jsfiddle.net/#tidy
<li> <a href=""></a>Link 3</li>
</ul>
</div>
</div>
``` | 2014/08/23 | [
"https://Stackoverflow.com/questions/25457631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3026353/"
] | Just add **float:right; position:relative** for your paragraph and adjust the width of paragraph if it is positioning below the image. | Add `overflow:hidden` to your paragraph’s formatting. |
25,457,631 | Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image.
But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image.
And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why.
![enter image description here](https://i.stack.imgur.com/I325u.png)
Do you know how can I have an effect like this my image below?
![enter image description here](https://i.stack.imgur.com/kL9DV.png)
**I forget to create a fiddle with my issue:** <http://jsfiddle.net/ejjtepfo/2/>
**My Html:**
```
<div class="modal">
<h2>Title of news</h2>
<span id="data">20/10/2014</span><br />
<img class="img" src=""/>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p>
<div class="clear_p"></div>
<div id="pdfs">
<h3>Links</h3>
<ul class="links">
<li> <a href=""></a>Link 1</li>
<li> <a href=""></a>Link 2</li>http://jsfiddle.net/#tidy
<li> <a href=""></a>Link 3</li>
</ul>
</div>
</div>
``` | 2014/08/23 | [
"https://Stackoverflow.com/questions/25457631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3026353/"
] | You can set the left margin of `<p>` equal to the width of the image
html
```
<img src="" />
<p>...</p>
```
css
```
img {
float: left;
width: 100px;
}
p {
margin-left: 100px;
}
``` | Add `overflow:hidden` to your paragraph’s formatting. |
25,457,631 | Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image.
But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image.
And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why.
![enter image description here](https://i.stack.imgur.com/I325u.png)
Do you know how can I have an effect like this my image below?
![enter image description here](https://i.stack.imgur.com/kL9DV.png)
**I forget to create a fiddle with my issue:** <http://jsfiddle.net/ejjtepfo/2/>
**My Html:**
```
<div class="modal">
<h2>Title of news</h2>
<span id="data">20/10/2014</span><br />
<img class="img" src=""/>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p>
<div class="clear_p"></div>
<div id="pdfs">
<h3>Links</h3>
<ul class="links">
<li> <a href=""></a>Link 1</li>
<li> <a href=""></a>Link 2</li>http://jsfiddle.net/#tidy
<li> <a href=""></a>Link 3</li>
</ul>
</div>
</div>
``` | 2014/08/23 | [
"https://Stackoverflow.com/questions/25457631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3026353/"
] | DEMO: <http://jsfiddle.net/wL6jua0L/>
-------------------------------------
Uses box-sizing:border-box, padding and negative margin. Assumes, as in the OP, that the image is fixed to 200px wide, which means with a 5px border, you add the actual width you want it since border-box includes the borders and padding. Regarding the gap below it on the other screen shot, if you change your paragraph line-height to 24px, it won't be there or you can manipulate the image height. Google vertical rhythm and images.
![enter image description here](https://i.stack.imgur.com/KfA5P.png)
```
.modal .img {
width:210px;
height:230px;
border:5px solid #f3f3f3;
margin:18px -220px 0 0;
box-sizing:border-box;
float:left;
}
.modal p{
box-sizing:border-box;
font-size: 16px;
text-align:left;
line-height:25px;
float:left;
padding:0 10px 0 230px;
}
``` | You can set the left margin of `<p>` equal to the width of the image
html
```
<img src="" />
<p>...</p>
```
css
```
img {
float: left;
width: 100px;
}
p {
margin-left: 100px;
}
``` |
25,457,631 | Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image.
But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image.
And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why.
![enter image description here](https://i.stack.imgur.com/I325u.png)
Do you know how can I have an effect like this my image below?
![enter image description here](https://i.stack.imgur.com/kL9DV.png)
**I forget to create a fiddle with my issue:** <http://jsfiddle.net/ejjtepfo/2/>
**My Html:**
```
<div class="modal">
<h2>Title of news</h2>
<span id="data">20/10/2014</span><br />
<img class="img" src=""/>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p>
<div class="clear_p"></div>
<div id="pdfs">
<h3>Links</h3>
<ul class="links">
<li> <a href=""></a>Link 1</li>
<li> <a href=""></a>Link 2</li>http://jsfiddle.net/#tidy
<li> <a href=""></a>Link 3</li>
</ul>
</div>
</div>
``` | 2014/08/23 | [
"https://Stackoverflow.com/questions/25457631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3026353/"
] | DEMO: <http://jsfiddle.net/wL6jua0L/>
-------------------------------------
Uses box-sizing:border-box, padding and negative margin. Assumes, as in the OP, that the image is fixed to 200px wide, which means with a 5px border, you add the actual width you want it since border-box includes the borders and padding. Regarding the gap below it on the other screen shot, if you change your paragraph line-height to 24px, it won't be there or you can manipulate the image height. Google vertical rhythm and images.
![enter image description here](https://i.stack.imgur.com/KfA5P.png)
```
.modal .img {
width:210px;
height:230px;
border:5px solid #f3f3f3;
margin:18px -220px 0 0;
box-sizing:border-box;
float:left;
}
.modal p{
box-sizing:border-box;
font-size: 16px;
text-align:left;
line-height:25px;
float:left;
padding:0 10px 0 230px;
}
``` | You could wrap the paragraph in a div tag:
```
<img src="http://www.peacethroughpie.org/wp-content/uploads/2013/09/baked-pie.jpg">
<div><p> ... </p></div>
```
Then you could set the div to a width of 100% - width of image and float it to the right.
```
img {
float: left;
width: 20%;
}
div {
display: block;
width: 80%;
float: right;
}
```
It would look like this:
<http://imgur.com/zL5v33z> |
25,457,631 | Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image.
But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image.
And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why.
![enter image description here](https://i.stack.imgur.com/I325u.png)
Do you know how can I have an effect like this my image below?
![enter image description here](https://i.stack.imgur.com/kL9DV.png)
**I forget to create a fiddle with my issue:** <http://jsfiddle.net/ejjtepfo/2/>
**My Html:**
```
<div class="modal">
<h2>Title of news</h2>
<span id="data">20/10/2014</span><br />
<img class="img" src=""/>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p>
<div class="clear_p"></div>
<div id="pdfs">
<h3>Links</h3>
<ul class="links">
<li> <a href=""></a>Link 1</li>
<li> <a href=""></a>Link 2</li>http://jsfiddle.net/#tidy
<li> <a href=""></a>Link 3</li>
</ul>
</div>
</div>
``` | 2014/08/23 | [
"https://Stackoverflow.com/questions/25457631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3026353/"
] | You could wrap the paragraph in a div tag:
```
<img src="http://www.peacethroughpie.org/wp-content/uploads/2013/09/baked-pie.jpg">
<div><p> ... </p></div>
```
Then you could set the div to a width of 100% - width of image and float it to the right.
```
img {
float: left;
width: 20%;
}
div {
display: block;
width: 80%;
float: right;
}
```
It would look like this:
<http://imgur.com/zL5v33z> | Add `overflow:hidden` to your paragraph’s formatting. |
25,457,631 | Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image.
But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image.
And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why.
![enter image description here](https://i.stack.imgur.com/I325u.png)
Do you know how can I have an effect like this my image below?
![enter image description here](https://i.stack.imgur.com/kL9DV.png)
**I forget to create a fiddle with my issue:** <http://jsfiddle.net/ejjtepfo/2/>
**My Html:**
```
<div class="modal">
<h2>Title of news</h2>
<span id="data">20/10/2014</span><br />
<img class="img" src=""/>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p>
<div class="clear_p"></div>
<div id="pdfs">
<h3>Links</h3>
<ul class="links">
<li> <a href=""></a>Link 1</li>
<li> <a href=""></a>Link 2</li>http://jsfiddle.net/#tidy
<li> <a href=""></a>Link 3</li>
</ul>
</div>
</div>
``` | 2014/08/23 | [
"https://Stackoverflow.com/questions/25457631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3026353/"
] | DEMO: <http://jsfiddle.net/wL6jua0L/>
-------------------------------------
Uses box-sizing:border-box, padding and negative margin. Assumes, as in the OP, that the image is fixed to 200px wide, which means with a 5px border, you add the actual width you want it since border-box includes the borders and padding. Regarding the gap below it on the other screen shot, if you change your paragraph line-height to 24px, it won't be there or you can manipulate the image height. Google vertical rhythm and images.
![enter image description here](https://i.stack.imgur.com/KfA5P.png)
```
.modal .img {
width:210px;
height:230px;
border:5px solid #f3f3f3;
margin:18px -220px 0 0;
box-sizing:border-box;
float:left;
}
.modal p{
box-sizing:border-box;
font-size: 16px;
text-align:left;
line-height:25px;
float:left;
padding:0 10px 0 230px;
}
``` | Just add **float:right; position:relative** for your paragraph and adjust the width of paragraph if it is positioning below the image. |
25,457,631 | Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image.
But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image.
And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why.
![enter image description here](https://i.stack.imgur.com/I325u.png)
Do you know how can I have an effect like this my image below?
![enter image description here](https://i.stack.imgur.com/kL9DV.png)
**I forget to create a fiddle with my issue:** <http://jsfiddle.net/ejjtepfo/2/>
**My Html:**
```
<div class="modal">
<h2>Title of news</h2>
<span id="data">20/10/2014</span><br />
<img class="img" src=""/>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</p>
<div class="clear_p"></div>
<div id="pdfs">
<h3>Links</h3>
<ul class="links">
<li> <a href=""></a>Link 1</li>
<li> <a href=""></a>Link 2</li>http://jsfiddle.net/#tidy
<li> <a href=""></a>Link 3</li>
</ul>
</div>
</div>
``` | 2014/08/23 | [
"https://Stackoverflow.com/questions/25457631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3026353/"
] | DEMO: <http://jsfiddle.net/wL6jua0L/>
-------------------------------------
Uses box-sizing:border-box, padding and negative margin. Assumes, as in the OP, that the image is fixed to 200px wide, which means with a 5px border, you add the actual width you want it since border-box includes the borders and padding. Regarding the gap below it on the other screen shot, if you change your paragraph line-height to 24px, it won't be there or you can manipulate the image height. Google vertical rhythm and images.
![enter image description here](https://i.stack.imgur.com/KfA5P.png)
```
.modal .img {
width:210px;
height:230px;
border:5px solid #f3f3f3;
margin:18px -220px 0 0;
box-sizing:border-box;
float:left;
}
.modal p{
box-sizing:border-box;
font-size: 16px;
text-align:left;
line-height:25px;
float:left;
padding:0 10px 0 230px;
}
``` | Add a div for your image in html file and add this in your css
```
#image{
width:210px;
height:1000px;
float:left;
}
``` |