qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
17,197,129 | I have a datagrid which populates a datatable, I want to export the DataTable to excel on click of a button. I am using MVVM for this application. So is it ok to implement the export feature in my view?
Secondly, as i am using xaml and desktop application, how do i capture the grid and its details.
Can any one suggest me some pointers? I am new to this.
Thanks,
Sagar | 2013/06/19 | [
"https://Stackoverflow.com/questions/17197129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1653540/"
] | This is what i have done and it helped me:
```
private readonly ICommand m_ExportButtonClick;
private string ExcelFilePath = "";
public ICommand ExportButtonClick { get { return m_ExportButtonClick; } }
private void OnRunExport()
{
try
{
if (queryDatatable == null || queryDatatable.Columns.Count == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
Excell.Application excelApp = new Excell.Application();
excelApp.Workbooks.Add();
// single worksheet
Excell._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (int i = 0; i < queryDatatable.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = queryDatatable.Columns[i].ColumnName;
}
// rows
for (int i = 0; i < queryDatatable.Rows.Count; i++)
{
// to do: format datetime values before printing
for (int j = 0; j < queryDatatable.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = queryDatatable.Rows[i][j];
}
}
// check fielpath
if (ExcelFilePath != null && ExcelFilePath != "")
{
try
{
workSheet.SaveAs(ExcelFilePath);
excelApp.Quit();
MessageBox.Show("Excel file saved!");
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
+ ex.Message);
}
}
else // no filepath is given, the file opens up and the user can save it accordingly.
{
excelApp.Visible = true;
}
}
catch (Exception ex)
{
MessageBox.Show("There is no data to export. Please check your query/ Contact administrator." + ex.Message);
}
}
#endregion
``` | Here's an extension method to output to any DataTable to a csv (which excel can open)
```vb
Imports System.Text
Imports System.IO
Imports System.Runtime.CompilerServices
Module ExtensionMethods
<Extension()> _
Public Sub OutputAsCSV(ByVal dt As DataTable, ByVal filePath As String)
Dim sb As New StringBuilder()
'write column names to string builder
Dim columnNames As String() = (From col As DataColumn In dt.Columns Select col.ColumnName).ToArray
sb.AppendLine(String.Join(",", columnNames))
'write cell value in each row to string builder
For Each row As DataRow In dt.Rows
Dim fields As String() = (From cell In row.ItemArray Select CStr(cell)).ToArray
sb.AppendLine(String.Join(",", fields))
Next
'write string builder to file
File.WriteAllText(filePath, sb.ToString())
End Sub
End Module
``` |
17,197,129 | I have a datagrid which populates a datatable, I want to export the DataTable to excel on click of a button. I am using MVVM for this application. So is it ok to implement the export feature in my view?
Secondly, as i am using xaml and desktop application, how do i capture the grid and its details.
Can any one suggest me some pointers? I am new to this.
Thanks,
Sagar | 2013/06/19 | [
"https://Stackoverflow.com/questions/17197129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1653540/"
] | This is what i have done and it helped me:
```
private readonly ICommand m_ExportButtonClick;
private string ExcelFilePath = "";
public ICommand ExportButtonClick { get { return m_ExportButtonClick; } }
private void OnRunExport()
{
try
{
if (queryDatatable == null || queryDatatable.Columns.Count == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
Excell.Application excelApp = new Excell.Application();
excelApp.Workbooks.Add();
// single worksheet
Excell._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (int i = 0; i < queryDatatable.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = queryDatatable.Columns[i].ColumnName;
}
// rows
for (int i = 0; i < queryDatatable.Rows.Count; i++)
{
// to do: format datetime values before printing
for (int j = 0; j < queryDatatable.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = queryDatatable.Rows[i][j];
}
}
// check fielpath
if (ExcelFilePath != null && ExcelFilePath != "")
{
try
{
workSheet.SaveAs(ExcelFilePath);
excelApp.Quit();
MessageBox.Show("Excel file saved!");
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
+ ex.Message);
}
}
else // no filepath is given, the file opens up and the user can save it accordingly.
{
excelApp.Visible = true;
}
}
catch (Exception ex)
{
MessageBox.Show("There is no data to export. Please check your query/ Contact administrator." + ex.Message);
}
}
#endregion
``` | Try googling around a little. This is a very common problem and has been asked a lot already. Here's a good answer from this [SO question](https://stackoverflow.com/questions/3283204/convert-datatable-to-excel-2007-xlsx)
```cs
public static void ExportToExcel<T>(IEnumerable<T> exportData)
{
Excel.ApplicationClass excel = new Excel.ApplicationClass();
Excel.Workbook workbook = excel.Application.Workbooks.Add(true);
PropertyInfo[] pInfos = typeof(T).GetProperties();
if (pInfos != null && pInfos.Count() > 0)
{
int iCol = 0;
int iRow = 0;
foreach (PropertyInfo eachPInfo in pInfos.Where(W => W.CanRead == true))
{
// Add column headings...
iCol++;
excel.Cells[1, iCol] = eachPInfo.Name;
}
foreach (T item in exportData)
{
iRow++;
// add each row's cell data...
iCol = 0;
foreach (PropertyInfo eachPInfo in pInfos.Where(W => W.CanRead == true))
{
iCol++;
excel.Cells[iRow + 1, iCol] = eachPInfo.GetValue(item, null);
}
}
// Global missing reference for objects we are not defining...
object missing = System.Reflection.Missing.Value;
// If wanting to Save the workbook...
string filePath = System.IO.Path.GetTempPath() + DateTime.Now.Ticks.ToString() + ".xlsm";
workbook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled, missing, missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
// If wanting to make Excel visible and activate the worksheet...
excel.Visible = true;
Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet;
excel.Rows.EntireRow.AutoFit();
excel.Columns.EntireColumn.AutoFit();
((Excel._Worksheet)worksheet).Activate();
}
}
``` |
71,940,399 | I want to create an trigger inside an procedure. but after some research I got to know that it is not possible. can u suggest me another way I can achieve the below actions. (I cant share exact data and queries due to some reason. please refer similar queries.)
***What I want***
I have created an temporary table containing data i need.
eg. `CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;`
I want to inset data in table `table2` when data is inserted in temp1, which i can achieve by creating a `TRIGGER`. but the problem is I want to give a value in `table2` which will be dynamic and will be taken from nodejs backend. so i created a `PROCEDURE` which takes parameter `neededId`. but i cant created trigger inside a procedure. is their any other way i can achieve this?
***Procedure I Created***
*here `neededId` is the foreign key I get from backend to insert*
```
DELIMITER $$
USE `DB`$$
CREATE PROCEDURE `MyProcedure` (IN neededID int)
BEGIN
DROP TABLE IF EXISTS temp1;
CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;
DROP TRIGGER IF EXISTS myTrigger;
CREATE TRIGGER myTrigger AFTER INSERT ON temp1 FOR EACH ROW
BEGIN
INSERT into table2("value1", "value2", neededId);
END;
END$$
DELIMITER ;
``` | 2022/04/20 | [
"https://Stackoverflow.com/questions/71940399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17349359/"
] | ```
const idx = headings.findIndex(el => el.text === 3 && el.type === "♠")
headings.splice(idx,1)
``` | You can also use filter
```
const newHeadings = headings.filter(item => !item.type === "♠")
```
If you also want to check for the value of `i`
```
const newHeadings = headings.filter((item, index)=> !(item.type === "♠" && item.text == (index + 1)))
```
This returns a new array and does not modify original |
71,940,399 | I want to create an trigger inside an procedure. but after some research I got to know that it is not possible. can u suggest me another way I can achieve the below actions. (I cant share exact data and queries due to some reason. please refer similar queries.)
***What I want***
I have created an temporary table containing data i need.
eg. `CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;`
I want to inset data in table `table2` when data is inserted in temp1, which i can achieve by creating a `TRIGGER`. but the problem is I want to give a value in `table2` which will be dynamic and will be taken from nodejs backend. so i created a `PROCEDURE` which takes parameter `neededId`. but i cant created trigger inside a procedure. is their any other way i can achieve this?
***Procedure I Created***
*here `neededId` is the foreign key I get from backend to insert*
```
DELIMITER $$
USE `DB`$$
CREATE PROCEDURE `MyProcedure` (IN neededID int)
BEGIN
DROP TABLE IF EXISTS temp1;
CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;
DROP TRIGGER IF EXISTS myTrigger;
CREATE TRIGGER myTrigger AFTER INSERT ON temp1 FOR EACH ROW
BEGIN
INSERT into table2("value1", "value2", neededId);
END;
END$$
DELIMITER ;
``` | 2022/04/20 | [
"https://Stackoverflow.com/questions/71940399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17349359/"
] | ```
const idx = headings.findIndex(el => el.text === 3 && el.type === "♠")
headings.splice(idx,1)
``` | There are multiple ways to do it.
You can use `filter` or `splice` method to do it.
[filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
Here you can filter all other element then 3 and "♠" and assign it to new array.
[findIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex)
Here find index of your element and use `splice` on array
```js
let headings = [];
for (let i = 1; i <= 13; i++) {
headings.push({
text: i,
type: "♠",
});
};
let newHeadingsFilter = headings.filter(x => !(x.text === 3 && x.type == "♠"));
console.log(newHeadingsFilter);
let index = headings.findIndex(x => x.text == 3 && x.type == "♠");
headings.splice(index, 1);
console.log(headings);
``` |
71,940,399 | I want to create an trigger inside an procedure. but after some research I got to know that it is not possible. can u suggest me another way I can achieve the below actions. (I cant share exact data and queries due to some reason. please refer similar queries.)
***What I want***
I have created an temporary table containing data i need.
eg. `CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;`
I want to inset data in table `table2` when data is inserted in temp1, which i can achieve by creating a `TRIGGER`. but the problem is I want to give a value in `table2` which will be dynamic and will be taken from nodejs backend. so i created a `PROCEDURE` which takes parameter `neededId`. but i cant created trigger inside a procedure. is their any other way i can achieve this?
***Procedure I Created***
*here `neededId` is the foreign key I get from backend to insert*
```
DELIMITER $$
USE `DB`$$
CREATE PROCEDURE `MyProcedure` (IN neededID int)
BEGIN
DROP TABLE IF EXISTS temp1;
CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;
DROP TRIGGER IF EXISTS myTrigger;
CREATE TRIGGER myTrigger AFTER INSERT ON temp1 FOR EACH ROW
BEGIN
INSERT into table2("value1", "value2", neededId);
END;
END$$
DELIMITER ;
``` | 2022/04/20 | [
"https://Stackoverflow.com/questions/71940399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17349359/"
] | ```
const idx = headings.findIndex(el => el.text === 3 && el.type === "♠")
headings.splice(idx,1)
``` | Use `lodash`'s [`_.remove`](https://lodash.com/docs/4.17.15#remove):
```js
const headings = _.range(1, 13).map(i => ({text: i, type: "♠"}));
_.remove(headings, {text: 3, type: "♠"});
console.log(headings);
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
```
This removes all matching elements, not just the first one. |
71,940,399 | I want to create an trigger inside an procedure. but after some research I got to know that it is not possible. can u suggest me another way I can achieve the below actions. (I cant share exact data and queries due to some reason. please refer similar queries.)
***What I want***
I have created an temporary table containing data i need.
eg. `CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;`
I want to inset data in table `table2` when data is inserted in temp1, which i can achieve by creating a `TRIGGER`. but the problem is I want to give a value in `table2` which will be dynamic and will be taken from nodejs backend. so i created a `PROCEDURE` which takes parameter `neededId`. but i cant created trigger inside a procedure. is their any other way i can achieve this?
***Procedure I Created***
*here `neededId` is the foreign key I get from backend to insert*
```
DELIMITER $$
USE `DB`$$
CREATE PROCEDURE `MyProcedure` (IN neededID int)
BEGIN
DROP TABLE IF EXISTS temp1;
CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;
DROP TRIGGER IF EXISTS myTrigger;
CREATE TRIGGER myTrigger AFTER INSERT ON temp1 FOR EACH ROW
BEGIN
INSERT into table2("value1", "value2", neededId);
END;
END$$
DELIMITER ;
``` | 2022/04/20 | [
"https://Stackoverflow.com/questions/71940399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17349359/"
] | There are multiple ways to do it.
You can use `filter` or `splice` method to do it.
[filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
Here you can filter all other element then 3 and "♠" and assign it to new array.
[findIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex)
Here find index of your element and use `splice` on array
```js
let headings = [];
for (let i = 1; i <= 13; i++) {
headings.push({
text: i,
type: "♠",
});
};
let newHeadingsFilter = headings.filter(x => !(x.text === 3 && x.type == "♠"));
console.log(newHeadingsFilter);
let index = headings.findIndex(x => x.text == 3 && x.type == "♠");
headings.splice(index, 1);
console.log(headings);
``` | You can also use filter
```
const newHeadings = headings.filter(item => !item.type === "♠")
```
If you also want to check for the value of `i`
```
const newHeadings = headings.filter((item, index)=> !(item.type === "♠" && item.text == (index + 1)))
```
This returns a new array and does not modify original |
71,940,399 | I want to create an trigger inside an procedure. but after some research I got to know that it is not possible. can u suggest me another way I can achieve the below actions. (I cant share exact data and queries due to some reason. please refer similar queries.)
***What I want***
I have created an temporary table containing data i need.
eg. `CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;`
I want to inset data in table `table2` when data is inserted in temp1, which i can achieve by creating a `TRIGGER`. but the problem is I want to give a value in `table2` which will be dynamic and will be taken from nodejs backend. so i created a `PROCEDURE` which takes parameter `neededId`. but i cant created trigger inside a procedure. is their any other way i can achieve this?
***Procedure I Created***
*here `neededId` is the foreign key I get from backend to insert*
```
DELIMITER $$
USE `DB`$$
CREATE PROCEDURE `MyProcedure` (IN neededID int)
BEGIN
DROP TABLE IF EXISTS temp1;
CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;
DROP TRIGGER IF EXISTS myTrigger;
CREATE TRIGGER myTrigger AFTER INSERT ON temp1 FOR EACH ROW
BEGIN
INSERT into table2("value1", "value2", neededId);
END;
END$$
DELIMITER ;
``` | 2022/04/20 | [
"https://Stackoverflow.com/questions/71940399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17349359/"
] | There are multiple ways to do it.
You can use `filter` or `splice` method to do it.
[filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
Here you can filter all other element then 3 and "♠" and assign it to new array.
[findIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex)
Here find index of your element and use `splice` on array
```js
let headings = [];
for (let i = 1; i <= 13; i++) {
headings.push({
text: i,
type: "♠",
});
};
let newHeadingsFilter = headings.filter(x => !(x.text === 3 && x.type == "♠"));
console.log(newHeadingsFilter);
let index = headings.findIndex(x => x.text == 3 && x.type == "♠");
headings.splice(index, 1);
console.log(headings);
``` | Use `lodash`'s [`_.remove`](https://lodash.com/docs/4.17.15#remove):
```js
const headings = _.range(1, 13).map(i => ({text: i, type: "♠"}));
_.remove(headings, {text: 3, type: "♠"});
console.log(headings);
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
```
This removes all matching elements, not just the first one. |
1,078,704 | I am using XUbuntu 18.04 and I am struggling to install my scanner. I have tried everything i have been able to find on both Brother homepage and AskUbuntu.
I have newest brsaneconfig4, brscan-skey and rules.
Command `brsaneconfig4 -`q returns:
```
(...)
Devices on network
0 DCP-7055W "DCP-7055W" I:192.168.1.28
```
Command `scanimage -L` returns:
```
device `brother4:net1;dev0' is a Brother DCP-7055W DCP-7055W
```
While command `brscan-skey -l` returns:
```
DCP-7055W : brother4:net1;dev0 : 192.168.1.28 Not responded
```
I have `libsane-brother4.so` installed in `/usr/lib64/sane`, `/usr/lib/sane` and `/usr/lib/x86_64-linux-gnu/sane`
Command `dpkg -l | grep Brother` returns:
```
ii brother-udev-rule-type1 1.0.2 all Brother udev rule type 1
ii brscan-skey 0.2.4-1 amd64 Brother Linux scanner S-KEY tool
ii brscan4 0.4.6-1 amd64 Brother Scanner Driver
ii dcp7055wcupswrapper:i386 3.0.1-1 i386 Brother DCP-7055W CUPS wrapper driver
ii dcp7055wlpr:i386 3.0.1-1 i386 Brother DCP-7055W LPR driver
ii printer-driver-brlaser 4-1 amd64 printer driver for (some) Brother laser printers
ii printer-driver-ptouch 1.4.2-3 amd64 printer driver Brother P-touch label printers
```
and my `libsane` file has following content:
```
#
# udev rules
#
ACTION!="add", GOTO="brother_mfp_end"
SUBSYSTEM=="usb", GOTO="brother_mfp_udev_1"
SUBSYSTEM!="usb_device", GOTO="brother_mfp_end"
LABEL="brother_mfp_udev_1"
SYSFS{idVendor}=="04f9", GOTO="brother_mfp_udev_2"
ATTRS{idVendor}=="04f9", GOTO="brother_mfp_udev_2"
GOTO="brother_mfp_end"
LABEL="brother_mfp_udev_2"
ATTRS{bInterfaceClass}!="0ff", GOTO="brother_mfp_end"
ATTRS{bInterfaceSubClass}!="0ff", GOTO="brother_mfp_end"
ATTRS{bInterfaceProtocol}!="0ff", GOTO="brother_mfp_end"
#MODE="0666"
#GROUP="scanner"
ENV{libsane_matched}="yes"
#SYMLINK+="scanner-%k"
LABEL="brother_mfp_end"
```
I have tried everything without any significant success. At some point I have had working scanner, but after reboot it was no longer visible in SimpleScan. How can i make this work? What is missing? | 2018/09/26 | [
"https://askubuntu.com/questions/1078704",
"https://askubuntu.com",
"https://askubuntu.com/users/864165/"
] | I came across the posting [Brother MFC-L2700DW printer can print, can’t scan](https://askubuntu.com/questions/970831/brother-mfc-l2700dw-printer-can-print-cant-scan) by oscar1919 on Ask Ubuntu. I have a Brother multi-function printer but a different model than that specified by Oscar.
Oscar indicated that some of the installation files may be copied into the wrong folder. For 64-bit Linux, the instructions were to check that the folder /usr/lib/x86\_64-linux-gnu/sane exists.
However, In my case, this folder was indeed present, but it was empty. The subsequent instructions were, essentially to copy the files libsane-brother\* from the /usr/lib64/sane/ folder to /usr/lib/x86\_64-linux-gnu/sane.
On my system, the three files to be copied were: libsane-brother2.so, libsane-brother2.so.1 and libsane-brother2.so.1.0.7.
Once these files were located in the /usr/lib/x86\_64-linux-gnu/sane folder, Simple Scan sprung to life and scanned a test document. | Additional answer here which works on every Ubuntu version so far.
On brother website, there's a package that does that's called "Driver install tool".
1. download it
2. run in terminal
3. provide your model by typing it's name i.e: `DCP-9015CDW`
follow the installer to also install a scanner drivers after printer is done. After the installer is done, simplescan will pick the scanner up without reboot.
The only "catch" is:
if you want to install it over WiFi, make sure your printer has a static IP assigned on your router, and use that IP during install (one of the options is to provide the installer with the IP of the machine).
If the IP of the driver changes, there's a chance you will have to redo your brsaneconfig everytime that happens so it's better to assign static IP to the printer/scanner.
Had no issues since.
Example download page for DCP-9015CDW:
<https://support.brother.com/g/b/downloadlist.aspx?c=gb&lang=en&prod=dcp9015cdw_eu&os=128>
(listed under "Utilities" section) |
1,078,704 | I am using XUbuntu 18.04 and I am struggling to install my scanner. I have tried everything i have been able to find on both Brother homepage and AskUbuntu.
I have newest brsaneconfig4, brscan-skey and rules.
Command `brsaneconfig4 -`q returns:
```
(...)
Devices on network
0 DCP-7055W "DCP-7055W" I:192.168.1.28
```
Command `scanimage -L` returns:
```
device `brother4:net1;dev0' is a Brother DCP-7055W DCP-7055W
```
While command `brscan-skey -l` returns:
```
DCP-7055W : brother4:net1;dev0 : 192.168.1.28 Not responded
```
I have `libsane-brother4.so` installed in `/usr/lib64/sane`, `/usr/lib/sane` and `/usr/lib/x86_64-linux-gnu/sane`
Command `dpkg -l | grep Brother` returns:
```
ii brother-udev-rule-type1 1.0.2 all Brother udev rule type 1
ii brscan-skey 0.2.4-1 amd64 Brother Linux scanner S-KEY tool
ii brscan4 0.4.6-1 amd64 Brother Scanner Driver
ii dcp7055wcupswrapper:i386 3.0.1-1 i386 Brother DCP-7055W CUPS wrapper driver
ii dcp7055wlpr:i386 3.0.1-1 i386 Brother DCP-7055W LPR driver
ii printer-driver-brlaser 4-1 amd64 printer driver for (some) Brother laser printers
ii printer-driver-ptouch 1.4.2-3 amd64 printer driver Brother P-touch label printers
```
and my `libsane` file has following content:
```
#
# udev rules
#
ACTION!="add", GOTO="brother_mfp_end"
SUBSYSTEM=="usb", GOTO="brother_mfp_udev_1"
SUBSYSTEM!="usb_device", GOTO="brother_mfp_end"
LABEL="brother_mfp_udev_1"
SYSFS{idVendor}=="04f9", GOTO="brother_mfp_udev_2"
ATTRS{idVendor}=="04f9", GOTO="brother_mfp_udev_2"
GOTO="brother_mfp_end"
LABEL="brother_mfp_udev_2"
ATTRS{bInterfaceClass}!="0ff", GOTO="brother_mfp_end"
ATTRS{bInterfaceSubClass}!="0ff", GOTO="brother_mfp_end"
ATTRS{bInterfaceProtocol}!="0ff", GOTO="brother_mfp_end"
#MODE="0666"
#GROUP="scanner"
ENV{libsane_matched}="yes"
#SYMLINK+="scanner-%k"
LABEL="brother_mfp_end"
```
I have tried everything without any significant success. At some point I have had working scanner, but after reboot it was no longer visible in SimpleScan. How can i make this work? What is missing? | 2018/09/26 | [
"https://askubuntu.com/questions/1078704",
"https://askubuntu.com",
"https://askubuntu.com/users/864165/"
] | I came across the posting [Brother MFC-L2700DW printer can print, can’t scan](https://askubuntu.com/questions/970831/brother-mfc-l2700dw-printer-can-print-cant-scan) by oscar1919 on Ask Ubuntu. I have a Brother multi-function printer but a different model than that specified by Oscar.
Oscar indicated that some of the installation files may be copied into the wrong folder. For 64-bit Linux, the instructions were to check that the folder /usr/lib/x86\_64-linux-gnu/sane exists.
However, In my case, this folder was indeed present, but it was empty. The subsequent instructions were, essentially to copy the files libsane-brother\* from the /usr/lib64/sane/ folder to /usr/lib/x86\_64-linux-gnu/sane.
On my system, the three files to be copied were: libsane-brother2.so, libsane-brother2.so.1 and libsane-brother2.so.1.0.7.
Once these files were located in the /usr/lib/x86\_64-linux-gnu/sane folder, Simple Scan sprung to life and scanned a test document. | Adding your username to the group that owns the scanner, `lp` in my case, may also be needed.
`sudo adduser $USER lp`. |
1,078,704 | I am using XUbuntu 18.04 and I am struggling to install my scanner. I have tried everything i have been able to find on both Brother homepage and AskUbuntu.
I have newest brsaneconfig4, brscan-skey and rules.
Command `brsaneconfig4 -`q returns:
```
(...)
Devices on network
0 DCP-7055W "DCP-7055W" I:192.168.1.28
```
Command `scanimage -L` returns:
```
device `brother4:net1;dev0' is a Brother DCP-7055W DCP-7055W
```
While command `brscan-skey -l` returns:
```
DCP-7055W : brother4:net1;dev0 : 192.168.1.28 Not responded
```
I have `libsane-brother4.so` installed in `/usr/lib64/sane`, `/usr/lib/sane` and `/usr/lib/x86_64-linux-gnu/sane`
Command `dpkg -l | grep Brother` returns:
```
ii brother-udev-rule-type1 1.0.2 all Brother udev rule type 1
ii brscan-skey 0.2.4-1 amd64 Brother Linux scanner S-KEY tool
ii brscan4 0.4.6-1 amd64 Brother Scanner Driver
ii dcp7055wcupswrapper:i386 3.0.1-1 i386 Brother DCP-7055W CUPS wrapper driver
ii dcp7055wlpr:i386 3.0.1-1 i386 Brother DCP-7055W LPR driver
ii printer-driver-brlaser 4-1 amd64 printer driver for (some) Brother laser printers
ii printer-driver-ptouch 1.4.2-3 amd64 printer driver Brother P-touch label printers
```
and my `libsane` file has following content:
```
#
# udev rules
#
ACTION!="add", GOTO="brother_mfp_end"
SUBSYSTEM=="usb", GOTO="brother_mfp_udev_1"
SUBSYSTEM!="usb_device", GOTO="brother_mfp_end"
LABEL="brother_mfp_udev_1"
SYSFS{idVendor}=="04f9", GOTO="brother_mfp_udev_2"
ATTRS{idVendor}=="04f9", GOTO="brother_mfp_udev_2"
GOTO="brother_mfp_end"
LABEL="brother_mfp_udev_2"
ATTRS{bInterfaceClass}!="0ff", GOTO="brother_mfp_end"
ATTRS{bInterfaceSubClass}!="0ff", GOTO="brother_mfp_end"
ATTRS{bInterfaceProtocol}!="0ff", GOTO="brother_mfp_end"
#MODE="0666"
#GROUP="scanner"
ENV{libsane_matched}="yes"
#SYMLINK+="scanner-%k"
LABEL="brother_mfp_end"
```
I have tried everything without any significant success. At some point I have had working scanner, but after reboot it was no longer visible in SimpleScan. How can i make this work? What is missing? | 2018/09/26 | [
"https://askubuntu.com/questions/1078704",
"https://askubuntu.com",
"https://askubuntu.com/users/864165/"
] | Additional answer here which works on every Ubuntu version so far.
On brother website, there's a package that does that's called "Driver install tool".
1. download it
2. run in terminal
3. provide your model by typing it's name i.e: `DCP-9015CDW`
follow the installer to also install a scanner drivers after printer is done. After the installer is done, simplescan will pick the scanner up without reboot.
The only "catch" is:
if you want to install it over WiFi, make sure your printer has a static IP assigned on your router, and use that IP during install (one of the options is to provide the installer with the IP of the machine).
If the IP of the driver changes, there's a chance you will have to redo your brsaneconfig everytime that happens so it's better to assign static IP to the printer/scanner.
Had no issues since.
Example download page for DCP-9015CDW:
<https://support.brother.com/g/b/downloadlist.aspx?c=gb&lang=en&prod=dcp9015cdw_eu&os=128>
(listed under "Utilities" section) | Adding your username to the group that owns the scanner, `lp` in my case, may also be needed.
`sudo adduser $USER lp`. |
71,110 | Some people erased three author names including mine from a paper previously submitted (and rejected by three different journals) and got it accepted by Case Reports In Emergency Medicine.
I presented the publishing editor of the journal multiple clear proofs of the plagiarism. Although the journal declares that it complies with COPE, the publishing editor is dragging feet not to publish a retraction about this article despite the proofs. Instead, they are trying to overlook the situation by involving the politically driven hospital administration from where the paper was submitted from. This in turn caused violation of my rights both as a human and as a researcher. I am currently subjected to serious mobbing by the hospital administration secondary to the inconclusive behaviour of the journal. This mobbing includes the change in my workplace and an official warning because "I ruined reputation of the hospital by contacting the publishing editor".
I also sent a message to COPE but there is no response.
Would anyone suggest any further action? | 2016/06/10 | [
"https://academia.stackexchange.com/questions/71110",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/56431/"
] | Working with the editor, until that process is finished, is probably the only thing to do at first. It will undoubtedly be a long process, with delays, so patience and persistence will be necessary. Try not to let the mobbing get to you, and try to remain calm and professional at all times, despite any pressure others may exert.
If the editors, in the end, are unable to come to a resolution you accept, then the options will be (essentially) to escalate the situation or to let it go. But making an action of that kind while the editors are still working would be premature, in my opinion. | I always get down voted for saying this, but outside of Academia, if there is a very cut and dry case of someone trying to take ownership of works that you hold copyright in, then it would go to court and be handled in about a month or so (in Germany).
I appreciate that going to court is something that is considered the absolute last option in Academia, rather than the first option everywhere else, but in my opinion this is a terrible mistake. We don't tell academic's to just "research the problem and fix it yourself" when their car breaks down. We don't ask academics to "go through the correct channels" if a teacher is caught abusing a student. No, we extend our arms out to the rest of society and get the professionals to sort it out. People who are experts in dealing with these issues. But for whatever reason, many academics think that because they are intellectual, they must by default know everything there is about intellectual property law, and can handle these sorts of issues in their weekly committee meetings. Or perhaps they think they can handle the issue with more grace and finesse than the justice system. Maybe. But I have heard the same logical argument used by both the military and religious groups, who ultimately put justice secondary to some other objective - like saving face or maintaining the hierarchy of power.
Regardless of whether the journal/hospital does come to the right decision in the end, by not exercising your right as the copyright holder to justice through the justice system, you are handing unwarranted power to the publishers and academic establishment handling your case, and disenfranchising the people who have spent their lives thinking about copyright disputes and their fare/proper outcomes. All to avoid some perceived stigma over using real lawyers. |
71,110 | Some people erased three author names including mine from a paper previously submitted (and rejected by three different journals) and got it accepted by Case Reports In Emergency Medicine.
I presented the publishing editor of the journal multiple clear proofs of the plagiarism. Although the journal declares that it complies with COPE, the publishing editor is dragging feet not to publish a retraction about this article despite the proofs. Instead, they are trying to overlook the situation by involving the politically driven hospital administration from where the paper was submitted from. This in turn caused violation of my rights both as a human and as a researcher. I am currently subjected to serious mobbing by the hospital administration secondary to the inconclusive behaviour of the journal. This mobbing includes the change in my workplace and an official warning because "I ruined reputation of the hospital by contacting the publishing editor".
I also sent a message to COPE but there is no response.
Would anyone suggest any further action? | 2016/06/10 | [
"https://academia.stackexchange.com/questions/71110",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/56431/"
] | Working with the editor, until that process is finished, is probably the only thing to do at first. It will undoubtedly be a long process, with delays, so patience and persistence will be necessary. Try not to let the mobbing get to you, and try to remain calm and professional at all times, despite any pressure others may exert.
If the editors, in the end, are unable to come to a resolution you accept, then the options will be (essentially) to escalate the situation or to let it go. But making an action of that kind while the editors are still working would be premature, in my opinion. | Search for legal help from an expert in I.P. , expose them publicly and hope for the best.
This doesn't mean that you'll be able to prove the rights if you didn't took enough precautions to protect your paper and ignorance by this side is hard to prove in court.
The next time though, you can publish your own thesis/essay/book and get an ISBN with total rights and you might still be able to publish your work before it gets published since "accepted" doesn't exactly mean "released" or "printed"(this isn't clear in the question).
After years of oppression, I find this as the only way to get proper recognition since many of those cheap "book makers with ISBN" can print your work "in hours" and you can begin to spread your own knowledge at your own pace and people will think twice before abusing with your intellectual property. |
71,110 | Some people erased three author names including mine from a paper previously submitted (and rejected by three different journals) and got it accepted by Case Reports In Emergency Medicine.
I presented the publishing editor of the journal multiple clear proofs of the plagiarism. Although the journal declares that it complies with COPE, the publishing editor is dragging feet not to publish a retraction about this article despite the proofs. Instead, they are trying to overlook the situation by involving the politically driven hospital administration from where the paper was submitted from. This in turn caused violation of my rights both as a human and as a researcher. I am currently subjected to serious mobbing by the hospital administration secondary to the inconclusive behaviour of the journal. This mobbing includes the change in my workplace and an official warning because "I ruined reputation of the hospital by contacting the publishing editor".
I also sent a message to COPE but there is no response.
Would anyone suggest any further action? | 2016/06/10 | [
"https://academia.stackexchange.com/questions/71110",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/56431/"
] | I always get down voted for saying this, but outside of Academia, if there is a very cut and dry case of someone trying to take ownership of works that you hold copyright in, then it would go to court and be handled in about a month or so (in Germany).
I appreciate that going to court is something that is considered the absolute last option in Academia, rather than the first option everywhere else, but in my opinion this is a terrible mistake. We don't tell academic's to just "research the problem and fix it yourself" when their car breaks down. We don't ask academics to "go through the correct channels" if a teacher is caught abusing a student. No, we extend our arms out to the rest of society and get the professionals to sort it out. People who are experts in dealing with these issues. But for whatever reason, many academics think that because they are intellectual, they must by default know everything there is about intellectual property law, and can handle these sorts of issues in their weekly committee meetings. Or perhaps they think they can handle the issue with more grace and finesse than the justice system. Maybe. But I have heard the same logical argument used by both the military and religious groups, who ultimately put justice secondary to some other objective - like saving face or maintaining the hierarchy of power.
Regardless of whether the journal/hospital does come to the right decision in the end, by not exercising your right as the copyright holder to justice through the justice system, you are handing unwarranted power to the publishers and academic establishment handling your case, and disenfranchising the people who have spent their lives thinking about copyright disputes and their fare/proper outcomes. All to avoid some perceived stigma over using real lawyers. | Search for legal help from an expert in I.P. , expose them publicly and hope for the best.
This doesn't mean that you'll be able to prove the rights if you didn't took enough precautions to protect your paper and ignorance by this side is hard to prove in court.
The next time though, you can publish your own thesis/essay/book and get an ISBN with total rights and you might still be able to publish your work before it gets published since "accepted" doesn't exactly mean "released" or "printed"(this isn't clear in the question).
After years of oppression, I find this as the only way to get proper recognition since many of those cheap "book makers with ISBN" can print your work "in hours" and you can begin to spread your own knowledge at your own pace and people will think twice before abusing with your intellectual property. |
34,695,078 | I'm having a problem updating php in Linux Redhat.
I updated by
```
yum install php56w
```
But it says there's no repository for php56w.
So I updated httpd by
```
yum update httpd
```
But since then, all websites(which is using php) are not working, they're showing 500 Internal server error.
This seems to be permission error, but I've no idea how to fix.
Anyone please help. | 2016/01/09 | [
"https://Stackoverflow.com/questions/34695078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4319602/"
] | Which RHEL version?
If it's RHEL 6 and you're upgrading the PHP version, you should use the PHP 5.6 software collection (<https://access.redhat.com/products/Red_Hat_Enterprise_Linux/Developer/#dev-page=5>).
If it's RHEL 7 - I don't recall the default PHP version. :/ | If you want PHP versions which are not considered stable enough by RedHat you will need to enable the EPEL repository and then install php like you tried before.
Do the following for enabling EPEL repo, make sure you are a root user:
ON RHEL/CentOS 7 64 Bit:
```
wget http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-9.noarch.rpm
rpm -ivh epel-release-7-9.noarch.rpm
```
[For more information check this site about EPEL](https://www.tecmint.com/how-to-enable-epel-repository-for-rhel-centos-6-5/) |
22,486,798 | The following MPMoviePlayerController will not present in my iOS application.
I am trying to make it appear when my tableView row is selected:
```
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:videoUrl]];
[player setFullscreen:YES];
[player play];
[self.tableView addSubview:player.view];
}
```
Any ideas? | 2014/03/18 | [
"https://Stackoverflow.com/questions/22486798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3434331/"
] | `$result` is a boolean because the query you are executing is failing! A failed query gives off boolean `'false'`.
Check you query. Try setting $start with a value before using it in your query. | Set $start = 1 before your query try again.
```
$start = 1;
``` |
424,214 | Where can I exponentiate a $3\times 3$ matrix like $\left[\begin{array}{ccc}
0 & 1 & 0\\
1 & 0 & 0\\
0 & 0 & 0
\end{array}\right]$
online?
Is there some website where this is possible?
Thank you very much. | 2013/06/19 | [
"https://math.stackexchange.com/questions/424214",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/83056/"
] | Depending on which matrix exponential you want, you can use:
* [*Wolfram Alpha 1st option: $e^{A}$*](http://www.wolframalpha.com/input/?i=matrixexp%28%7B%7B0%2C1%2C0%7D%2C%7B1%2C0%2C0%7D%2C%7B0%2C0%2C0%7D%7D%29)
* [*Wolfram Alpha 2nd option: $e^{At}$*](http://www.wolframalpha.com/input/?i=matrixexp%28t+%7B%7B0%2C1%2C0%7D%2C%7B1%2C0%2C0%7D%2C%7B0%2C0%2C0%7D%7D%29)
This is actually a command in Mathematica.
I would be surprised if were not available in other [*CAS programs*](http://en.wikipedia.org/wiki/List_of_computer_algebra_systems) and some of those are online, like [*Sage*](http://www.sagemath.org/doc/reference/matrices/sage/matrix/matrix_symbolic_dense.html), [*Maxima*](http://www.ma.utexas.edu/pipermail/maxima/2006/003031.html) and others. | Somewhat perversely, could I suggest you first try analytically, by [Sylvester's formula](https://en.wikipedia.org/wiki/Sylvester%27s_formula), or, more specifically, [simpler methods as below](https://en.wikipedia.org/wiki/Matrix_exponential#Computing_the_matrix_exponential)?
Still, in your specific case, this would be overkill: your matrix is trivially diagonalizable,
$$M=\left[\begin{array}{ccc}
0 & 1 & 0\\
1 & 0 & 0\\
0 & 0 & 0
\end{array}\right]=\frac{1}{\sqrt2}\left[\begin{array}{ccc}
1 & 1 & 0\\
1 & -1 & 0\\
0 & 0 & {\sqrt2}
\end{array}\right] ~~
\left[\begin{array}{ccc}
1 & 0 & 0\\
0 & -1 & 0\\
0 & 0 & 0
\end{array}\right]~\frac{1}{\sqrt2}\left[\begin{array}{ccc}
1 & 1 & 0\\
1 & -1 & 0\\
0 & 0 & {\sqrt2}
\end{array}\right]\equiv R^{-1} D R,$$
for the obviously defined diagonal matrix *D* and diagonalizing rotations *R*.
It then immediately follows that
$$
\exp M= R^{-1} e^D R= \left[\begin{array}{ccc}
\cosh 1 & \sinh 1 & 0\\
\sinh 1 & \cosh 1 & 0\\
0 & 0 & 1
\end{array}\right].
$$
Sylvester's formula generalizes to non-diagonalizable matrices, but my sense is you are dealing with diagonalizable ones. |
66,184,300 | I have a df with customer\_id, year, order and a few other but unimportant columns. Every time when i get a new order, my code creates a new row, so there can be more than one row for each customer\_id. I want to create a new column 'actually', which includes 'True' if a customer\_id bought in 2020 or 2021. My Code is:
```
#Run through all customers and check if they bought in 2020 or 2021
investors = df["customer_id"].unique()
df["actually"] = np.nan
for i in investors:
selected_df = df.loc[df["customer_id"] == i]
for year in selected_df['year'].unique():
if "2021" in str(year) or "2020" in str(year):
df.loc[df["customer_id"] == i, "actually"] = "True"
break
#Want just latest orders / customers
df = df.loc[df["actually"] == "True"]
```
This works fine, but quite slow. I want to use Pandas groupby function, but didnt find a working way so far. Also i avoid loops. Anyone an idea? | 2021/02/13 | [
"https://Stackoverflow.com/questions/66184300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11203274/"
] | you can create the column name 'Actually' something like this.
```
list1=df['Customer_id'][df.year==2020].unique()
list2=df['Customer_id'][df.year==2021].unique()
df['Actually']=df['Customer_id'].apply( lambda x : x in list1 or x in list2)
``` | You can use apply method, to avoid loops:
```
df['actually']=df['customer_id'].apply(lambda x: df[df.customer_id==x]['year'].str.contains('2020').any() or df[df.customer_id==x]['year'].str.contains('2021').any())
``` |
66,184,300 | I have a df with customer\_id, year, order and a few other but unimportant columns. Every time when i get a new order, my code creates a new row, so there can be more than one row for each customer\_id. I want to create a new column 'actually', which includes 'True' if a customer\_id bought in 2020 or 2021. My Code is:
```
#Run through all customers and check if they bought in 2020 or 2021
investors = df["customer_id"].unique()
df["actually"] = np.nan
for i in investors:
selected_df = df.loc[df["customer_id"] == i]
for year in selected_df['year'].unique():
if "2021" in str(year) or "2020" in str(year):
df.loc[df["customer_id"] == i, "actually"] = "True"
break
#Want just latest orders / customers
df = df.loc[df["actually"] == "True"]
```
This works fine, but quite slow. I want to use Pandas groupby function, but didnt find a working way so far. Also i avoid loops. Anyone an idea? | 2021/02/13 | [
"https://Stackoverflow.com/questions/66184300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11203274/"
] | Based on my understanding of your scaenario, here is a simple code:
```py
import pandas as pd
# Sample data to recreate the scenarion
data = {'customer_id': ['c1','c2','c1','c4','c3','c3'], 'year': [2019, 2018,2021,2012,2020,2021], 'order': ['A1','A2','A3','A4','A5','A6']}
df = pd.DataFrame.from_dict(data)
# Creating the new column (initially all false)
df['actually'] = False
# Filling only required rows with True
df.loc[(df['year']==2020) | (df['year']==2021), 'actually'] = True
print(df)
```
Which will produce:
```bash
customer_id year order actually
0 c1 2019 A1 False
1 c2 2018 A2 False
2 c1 2021 A3 True
3 c4 2012 A4 False
4 c3 2020 A5 True
5 c3 2021 A6 True
``` | You can use apply method, to avoid loops:
```
df['actually']=df['customer_id'].apply(lambda x: df[df.customer_id==x]['year'].str.contains('2020').any() or df[df.customer_id==x]['year'].str.contains('2021').any())
``` |
66,184,300 | I have a df with customer\_id, year, order and a few other but unimportant columns. Every time when i get a new order, my code creates a new row, so there can be more than one row for each customer\_id. I want to create a new column 'actually', which includes 'True' if a customer\_id bought in 2020 or 2021. My Code is:
```
#Run through all customers and check if they bought in 2020 or 2021
investors = df["customer_id"].unique()
df["actually"] = np.nan
for i in investors:
selected_df = df.loc[df["customer_id"] == i]
for year in selected_df['year'].unique():
if "2021" in str(year) or "2020" in str(year):
df.loc[df["customer_id"] == i, "actually"] = "True"
break
#Want just latest orders / customers
df = df.loc[df["actually"] == "True"]
```
This works fine, but quite slow. I want to use Pandas groupby function, but didnt find a working way so far. Also i avoid loops. Anyone an idea? | 2021/02/13 | [
"https://Stackoverflow.com/questions/66184300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11203274/"
] | you can create the column name 'Actually' something like this.
```
list1=df['Customer_id'][df.year==2020].unique()
list2=df['Customer_id'][df.year==2021].unique()
df['Actually']=df['Customer_id'].apply( lambda x : x in list1 or x in list2)
``` | Based on my understanding of your scaenario, here is a simple code:
```py
import pandas as pd
# Sample data to recreate the scenarion
data = {'customer_id': ['c1','c2','c1','c4','c3','c3'], 'year': [2019, 2018,2021,2012,2020,2021], 'order': ['A1','A2','A3','A4','A5','A6']}
df = pd.DataFrame.from_dict(data)
# Creating the new column (initially all false)
df['actually'] = False
# Filling only required rows with True
df.loc[(df['year']==2020) | (df['year']==2021), 'actually'] = True
print(df)
```
Which will produce:
```bash
customer_id year order actually
0 c1 2019 A1 False
1 c2 2018 A2 False
2 c1 2021 A3 True
3 c4 2012 A4 False
4 c3 2020 A5 True
5 c3 2021 A6 True
``` |
6,590,891 | I want to create a computed column that is the concatenation of several other columns. In the below example, fulladdress is null in the result set when any of the 'real' columns is null. How can I adjust the computed column function to take into account the nullable columns?
```
CREATE TABLE Locations
(
[id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[fulladdress] AS (((([address]+[address2])+[city])+[state])+[zip]),
[address] [varchar](50) NULL,
[address2] [varchar](50) NULL,
[city] [varchar](50) NULL,
[state] [varchar](50) NULL,
[zip] [varchar](50) NULL
)
```
Thanks in advance | 2011/07/06 | [
"https://Stackoverflow.com/questions/6590891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156611/"
] | This gets messy pretty quick, but here's a start:
```
ISNULL(address,'') + ' '
+ ISNULL(address2,'') + ' '
+ ISNULL(city,'') + ' '
+ ISNULL(state,'') + ' '
+ ISNULL(zip,'')
```
(If `isnull` doesn't work, you can try `coalesce`. If neither work, share what DMBS you're using.) | You shouldn't have a full address column (which is a duplicate of other columns) stored in your database unless you have a good reason. The correct way would be to construct the full address string in your queries. By creating the field dynamically you reduce redundancy in the table and you have one less column to maintain (which would need to be updated anytime any other column changes).
In your query you would do something like
```
SELECT CONCAT(ISNULL(address,''), ISNULL(address2,''), ISNULL(city,''), ISNULL(state,''), ISNULL(zip,'')) AS fulladdress FROM Locations;
```
The `CONCAT()` function performs concatenation and the `ISNULL()` gives you your string if it's not null or the second param (which was passed as '') if it is null |
18,979 | Can any chess engine tell you why a move is bad or good? For example, say a chess engine says the score against my opponent is currently +2 in my favor. I then make a move and my score drops to say 1.4. Can any engine tell me what I did wrong such that my score dropped from 2 to 1.4 (assuming I didn't hang a piece or pawn etc.)
It seems to me that having chess programmers make their programs even stronger is now pointless and it would be much more beneficial to the average chess player if they could have their programs instruct us why a move is bad (or good), assuming they currently cannot do this. | 2017/10/29 | [
"https://chess.stackexchange.com/questions/18979",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/443/"
] | **Sort of (but not really) - and it's actually getting *harder* for engines to do this for you.** To understand why, you have to understand how the evaluation goes. Engines typically can make snap evaluations on a given position, giving it a raw point value. Then, whatever the position is, they play forward, trying to find the line forward that optimizes that score for both sides.
It's important to understand, that '2.0' or '1.4' score *aren't* the evaluation/score for the current position. Instead, it's the evaluation N moves down the line, with each side playing the best move the engine found. This is why the "Current evaluation score" jumps around while the computer is thinking. It's not that the 'score' for a position changed - it's just that it found a different line moving forward that ended up in a different position (which had a different score.)
In the past, engines sucked. Not just because of sub-optimal algorithms, but because of very slow hardware - if you think compounding interest is powerful, it's nothing compared to [Moore's Law](https://en.wikipedia.org/wiki/Moore%27s_law). So computers back then were just looking a few moves into the future. Which made it relatively easy for a human to follow the logic - your score went down because you're losing your knight the next turn.
But now? If your score went from '2.0' to '-0.3', it's possible it's because, due to some unavoidable tactics over the next 7 moves, that you'll have to give up the exchange in order to avoid losing your queen or getting checkmated. But it's hard to show the leap from "Here's the position now" and "Well, I evaluated 20 billion positions going forward, and trust me when I say that you sacrificing the rook for their bishop was the best you could hope for."
Occasionally a move from a grandmaster winning game is said to be "invisible" to a chess engine. Only after the move is made, the engine recognizes the high value of the move. This weakness in the engine could easily be remedied by more exhaustive checking of possible moves. | The engine evaluation ("2"/"1.4") is in fact very similar to how a human would evaluate a position. It is basically a sum of various factors such as *material*, *king safety*, *piece activity*, etc. evaluated not for the current position but for the position some 20 moves ahead or so; assuming perfect play from both sides.
In principle one could try to monitor the change in all those factors separately (instead of only their sum as engines do). For instance if a move leads to a lower value for "king safety" later on compared to the best move, one might be tempted to tell the learner something like: *Your last move made your king more vulnerable*
However I doubt that this would work in actual games, because:
* the learner's move might in fact have other issues: for instance it might neglect development and only because of this the player might have to make concessions later on regarding his king's protection (assuming best play).
* many factors might change at the same time, some going up some going down for instance. Trying to express this in words might be cumbersome, e.g.: *Your last move neglected king safety, but improved your piece's activity and you lost a pawn but occupied an open file* Would this information be helpful to a learner?
Because of this, I doubt that computer's will be able to teach you positional or intuitive play (based on principles) at least with current technology. Better to use classical methods such as other humans, reading/watching/listening annotated games, etc |
18,979 | Can any chess engine tell you why a move is bad or good? For example, say a chess engine says the score against my opponent is currently +2 in my favor. I then make a move and my score drops to say 1.4. Can any engine tell me what I did wrong such that my score dropped from 2 to 1.4 (assuming I didn't hang a piece or pawn etc.)
It seems to me that having chess programmers make their programs even stronger is now pointless and it would be much more beneficial to the average chess player if they could have their programs instruct us why a move is bad (or good), assuming they currently cannot do this. | 2017/10/29 | [
"https://chess.stackexchange.com/questions/18979",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/443/"
] | @D\_M mentioned about Chessmaster, but it only reports very simple static features such as:
* Your queen is being attacked
* You lose a pawn in the computer line
* You win an exchange in the computer line
Do you know why Chessmaster did that? That's because the implementation was easy.
>
> Can any engine tell me what I did wrong such that my score dropped from 2 to 1.4 (assuming I didn't hang a piece or pawn etc.)
>
>
>
**NO**. Chesmaster can't do that. No software can do that. We don't have the technology to do that. Traditional engine programming techniques can't do that.
To do what your describe, we need advanced mathematics/machine learning models. I'm not aware of anything like that. | The engine evaluation ("2"/"1.4") is in fact very similar to how a human would evaluate a position. It is basically a sum of various factors such as *material*, *king safety*, *piece activity*, etc. evaluated not for the current position but for the position some 20 moves ahead or so; assuming perfect play from both sides.
In principle one could try to monitor the change in all those factors separately (instead of only their sum as engines do). For instance if a move leads to a lower value for "king safety" later on compared to the best move, one might be tempted to tell the learner something like: *Your last move made your king more vulnerable*
However I doubt that this would work in actual games, because:
* the learner's move might in fact have other issues: for instance it might neglect development and only because of this the player might have to make concessions later on regarding his king's protection (assuming best play).
* many factors might change at the same time, some going up some going down for instance. Trying to express this in words might be cumbersome, e.g.: *Your last move neglected king safety, but improved your piece's activity and you lost a pawn but occupied an open file* Would this information be helpful to a learner?
Because of this, I doubt that computer's will be able to teach you positional or intuitive play (based on principles) at least with current technology. Better to use classical methods such as other humans, reading/watching/listening annotated games, etc |
18,979 | Can any chess engine tell you why a move is bad or good? For example, say a chess engine says the score against my opponent is currently +2 in my favor. I then make a move and my score drops to say 1.4. Can any engine tell me what I did wrong such that my score dropped from 2 to 1.4 (assuming I didn't hang a piece or pawn etc.)
It seems to me that having chess programmers make their programs even stronger is now pointless and it would be much more beneficial to the average chess player if they could have their programs instruct us why a move is bad (or good), assuming they currently cannot do this. | 2017/10/29 | [
"https://chess.stackexchange.com/questions/18979",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/443/"
] | **Sort of (but not really) - and it's actually getting *harder* for engines to do this for you.** To understand why, you have to understand how the evaluation goes. Engines typically can make snap evaluations on a given position, giving it a raw point value. Then, whatever the position is, they play forward, trying to find the line forward that optimizes that score for both sides.
It's important to understand, that '2.0' or '1.4' score *aren't* the evaluation/score for the current position. Instead, it's the evaluation N moves down the line, with each side playing the best move the engine found. This is why the "Current evaluation score" jumps around while the computer is thinking. It's not that the 'score' for a position changed - it's just that it found a different line moving forward that ended up in a different position (which had a different score.)
In the past, engines sucked. Not just because of sub-optimal algorithms, but because of very slow hardware - if you think compounding interest is powerful, it's nothing compared to [Moore's Law](https://en.wikipedia.org/wiki/Moore%27s_law). So computers back then were just looking a few moves into the future. Which made it relatively easy for a human to follow the logic - your score went down because you're losing your knight the next turn.
But now? If your score went from '2.0' to '-0.3', it's possible it's because, due to some unavoidable tactics over the next 7 moves, that you'll have to give up the exchange in order to avoid losing your queen or getting checkmated. But it's hard to show the leap from "Here's the position now" and "Well, I evaluated 20 billion positions going forward, and trust me when I say that you sacrificing the rook for their bishop was the best you could hope for."
Occasionally a move from a grandmaster winning game is said to be "invisible" to a chess engine. Only after the move is made, the engine recognizes the high value of the move. This weakness in the engine could easily be remedied by more exhaustive checking of possible moves. | There've been attempts to make engines explain why moves are good or bad. Here's an [example](https://app.decodechess.com/) I am aware of.
You could try clicking through the example to see how helpful it is. |
18,979 | Can any chess engine tell you why a move is bad or good? For example, say a chess engine says the score against my opponent is currently +2 in my favor. I then make a move and my score drops to say 1.4. Can any engine tell me what I did wrong such that my score dropped from 2 to 1.4 (assuming I didn't hang a piece or pawn etc.)
It seems to me that having chess programmers make their programs even stronger is now pointless and it would be much more beneficial to the average chess player if they could have their programs instruct us why a move is bad (or good), assuming they currently cannot do this. | 2017/10/29 | [
"https://chess.stackexchange.com/questions/18979",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/443/"
] | I think the chess engine can "tell" you, but in an indirect way.
What I would do is to play several different moves from the same position. The chess engine will (presumably) give you a different score for each one.
This will allow you to "rank" the various moves. Perhaps a pattern will emerge. If not, you might want to get a (stronger) human player to explain the chess engine's rankings to you. | No.
Although Chessmaster as mentioned by everyone can tell you some basic things like if the following line will result in an exchange sacrifice or you may lose a pawn and so so.
But you can also analyse this yourself by playing down the lines. There are no chess engines nor I see any in the near future that can explain why the move is good/bad unless it will cost you material difference. As a engine may have played a move to improve his position in the future say like after 50 moves. There is no way it can explain to you why this move will result in a better position after 50 moves.
Also major chess engines in the market like Stockfish etc. do not even bother to include such features as the level chess engines play at are completely different and very hard to analyse even if we are provided with explanation of every move. |
18,979 | Can any chess engine tell you why a move is bad or good? For example, say a chess engine says the score against my opponent is currently +2 in my favor. I then make a move and my score drops to say 1.4. Can any engine tell me what I did wrong such that my score dropped from 2 to 1.4 (assuming I didn't hang a piece or pawn etc.)
It seems to me that having chess programmers make their programs even stronger is now pointless and it would be much more beneficial to the average chess player if they could have their programs instruct us why a move is bad (or good), assuming they currently cannot do this. | 2017/10/29 | [
"https://chess.stackexchange.com/questions/18979",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/443/"
] | **Sort of (but not really) - and it's actually getting *harder* for engines to do this for you.** To understand why, you have to understand how the evaluation goes. Engines typically can make snap evaluations on a given position, giving it a raw point value. Then, whatever the position is, they play forward, trying to find the line forward that optimizes that score for both sides.
It's important to understand, that '2.0' or '1.4' score *aren't* the evaluation/score for the current position. Instead, it's the evaluation N moves down the line, with each side playing the best move the engine found. This is why the "Current evaluation score" jumps around while the computer is thinking. It's not that the 'score' for a position changed - it's just that it found a different line moving forward that ended up in a different position (which had a different score.)
In the past, engines sucked. Not just because of sub-optimal algorithms, but because of very slow hardware - if you think compounding interest is powerful, it's nothing compared to [Moore's Law](https://en.wikipedia.org/wiki/Moore%27s_law). So computers back then were just looking a few moves into the future. Which made it relatively easy for a human to follow the logic - your score went down because you're losing your knight the next turn.
But now? If your score went from '2.0' to '-0.3', it's possible it's because, due to some unavoidable tactics over the next 7 moves, that you'll have to give up the exchange in order to avoid losing your queen or getting checkmated. But it's hard to show the leap from "Here's the position now" and "Well, I evaluated 20 billion positions going forward, and trust me when I say that you sacrificing the rook for their bishop was the best you could hope for."
Occasionally a move from a grandmaster winning game is said to be "invisible" to a chess engine. Only after the move is made, the engine recognizes the high value of the move. This weakness in the engine could easily be remedied by more exhaustive checking of possible moves. | Yes, I have seen programs that attempt to explain why a move is good or bad in language. Chessmaster 9000 would do this.
Many engines will show you the best line for each move. So it can tell you that if you play g6, it expects the game to go f5 gxf5 Nxf5, whereas if you play b6 it expects the game to go a5 bxa5 Bxa5. Often from there you can see why the move was good or bad. But sometimes it's still very subtle.
There is a tool [here](https://hxim.github.io/Stockfish-Evaluation-Guide/) where you can input a position and it will tell you exactly why Stockfish evaluates the position the way it does. It only works for a static position (it doesn't look ahead at all), but it's still interesting. |
18,979 | Can any chess engine tell you why a move is bad or good? For example, say a chess engine says the score against my opponent is currently +2 in my favor. I then make a move and my score drops to say 1.4. Can any engine tell me what I did wrong such that my score dropped from 2 to 1.4 (assuming I didn't hang a piece or pawn etc.)
It seems to me that having chess programmers make their programs even stronger is now pointless and it would be much more beneficial to the average chess player if they could have their programs instruct us why a move is bad (or good), assuming they currently cannot do this. | 2017/10/29 | [
"https://chess.stackexchange.com/questions/18979",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/443/"
] | **Sort of (but not really) - and it's actually getting *harder* for engines to do this for you.** To understand why, you have to understand how the evaluation goes. Engines typically can make snap evaluations on a given position, giving it a raw point value. Then, whatever the position is, they play forward, trying to find the line forward that optimizes that score for both sides.
It's important to understand, that '2.0' or '1.4' score *aren't* the evaluation/score for the current position. Instead, it's the evaluation N moves down the line, with each side playing the best move the engine found. This is why the "Current evaluation score" jumps around while the computer is thinking. It's not that the 'score' for a position changed - it's just that it found a different line moving forward that ended up in a different position (which had a different score.)
In the past, engines sucked. Not just because of sub-optimal algorithms, but because of very slow hardware - if you think compounding interest is powerful, it's nothing compared to [Moore's Law](https://en.wikipedia.org/wiki/Moore%27s_law). So computers back then were just looking a few moves into the future. Which made it relatively easy for a human to follow the logic - your score went down because you're losing your knight the next turn.
But now? If your score went from '2.0' to '-0.3', it's possible it's because, due to some unavoidable tactics over the next 7 moves, that you'll have to give up the exchange in order to avoid losing your queen or getting checkmated. But it's hard to show the leap from "Here's the position now" and "Well, I evaluated 20 billion positions going forward, and trust me when I say that you sacrificing the rook for their bishop was the best you could hope for."
Occasionally a move from a grandmaster winning game is said to be "invisible" to a chess engine. Only after the move is made, the engine recognizes the high value of the move. This weakness in the engine could easily be remedied by more exhaustive checking of possible moves. | In addition to other answers, engines don't assess positions like humans, so they can't provide a good explanation why *they think* your move is inferior (emphasis on they think, not necessarily).
But you can follow sidelines using engine suggestions and understand why it was inferior. At least this is what I do.
Could there be an engine which can do this? I guess yes, but from business point of view, probably, an infeasibly huge effort is necessary. |
18,979 | Can any chess engine tell you why a move is bad or good? For example, say a chess engine says the score against my opponent is currently +2 in my favor. I then make a move and my score drops to say 1.4. Can any engine tell me what I did wrong such that my score dropped from 2 to 1.4 (assuming I didn't hang a piece or pawn etc.)
It seems to me that having chess programmers make their programs even stronger is now pointless and it would be much more beneficial to the average chess player if they could have their programs instruct us why a move is bad (or good), assuming they currently cannot do this. | 2017/10/29 | [
"https://chess.stackexchange.com/questions/18979",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/443/"
] | Yes, I have seen programs that attempt to explain why a move is good or bad in language. Chessmaster 9000 would do this.
Many engines will show you the best line for each move. So it can tell you that if you play g6, it expects the game to go f5 gxf5 Nxf5, whereas if you play b6 it expects the game to go a5 bxa5 Bxa5. Often from there you can see why the move was good or bad. But sometimes it's still very subtle.
There is a tool [here](https://hxim.github.io/Stockfish-Evaluation-Guide/) where you can input a position and it will tell you exactly why Stockfish evaluates the position the way it does. It only works for a static position (it doesn't look ahead at all), but it's still interesting. | The engine evaluation ("2"/"1.4") is in fact very similar to how a human would evaluate a position. It is basically a sum of various factors such as *material*, *king safety*, *piece activity*, etc. evaluated not for the current position but for the position some 20 moves ahead or so; assuming perfect play from both sides.
In principle one could try to monitor the change in all those factors separately (instead of only their sum as engines do). For instance if a move leads to a lower value for "king safety" later on compared to the best move, one might be tempted to tell the learner something like: *Your last move made your king more vulnerable*
However I doubt that this would work in actual games, because:
* the learner's move might in fact have other issues: for instance it might neglect development and only because of this the player might have to make concessions later on regarding his king's protection (assuming best play).
* many factors might change at the same time, some going up some going down for instance. Trying to express this in words might be cumbersome, e.g.: *Your last move neglected king safety, but improved your piece's activity and you lost a pawn but occupied an open file* Would this information be helpful to a learner?
Because of this, I doubt that computer's will be able to teach you positional or intuitive play (based on principles) at least with current technology. Better to use classical methods such as other humans, reading/watching/listening annotated games, etc |
18,979 | Can any chess engine tell you why a move is bad or good? For example, say a chess engine says the score against my opponent is currently +2 in my favor. I then make a move and my score drops to say 1.4. Can any engine tell me what I did wrong such that my score dropped from 2 to 1.4 (assuming I didn't hang a piece or pawn etc.)
It seems to me that having chess programmers make their programs even stronger is now pointless and it would be much more beneficial to the average chess player if they could have their programs instruct us why a move is bad (or good), assuming they currently cannot do this. | 2017/10/29 | [
"https://chess.stackexchange.com/questions/18979",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/443/"
] | Yes, I have seen programs that attempt to explain why a move is good or bad in language. Chessmaster 9000 would do this.
Many engines will show you the best line for each move. So it can tell you that if you play g6, it expects the game to go f5 gxf5 Nxf5, whereas if you play b6 it expects the game to go a5 bxa5 Bxa5. Often from there you can see why the move was good or bad. But sometimes it's still very subtle.
There is a tool [here](https://hxim.github.io/Stockfish-Evaluation-Guide/) where you can input a position and it will tell you exactly why Stockfish evaluates the position the way it does. It only works for a static position (it doesn't look ahead at all), but it's still interesting. | No.
Although Chessmaster as mentioned by everyone can tell you some basic things like if the following line will result in an exchange sacrifice or you may lose a pawn and so so.
But you can also analyse this yourself by playing down the lines. There are no chess engines nor I see any in the near future that can explain why the move is good/bad unless it will cost you material difference. As a engine may have played a move to improve his position in the future say like after 50 moves. There is no way it can explain to you why this move will result in a better position after 50 moves.
Also major chess engines in the market like Stockfish etc. do not even bother to include such features as the level chess engines play at are completely different and very hard to analyse even if we are provided with explanation of every move. |
18,979 | Can any chess engine tell you why a move is bad or good? For example, say a chess engine says the score against my opponent is currently +2 in my favor. I then make a move and my score drops to say 1.4. Can any engine tell me what I did wrong such that my score dropped from 2 to 1.4 (assuming I didn't hang a piece or pawn etc.)
It seems to me that having chess programmers make their programs even stronger is now pointless and it would be much more beneficial to the average chess player if they could have their programs instruct us why a move is bad (or good), assuming they currently cannot do this. | 2017/10/29 | [
"https://chess.stackexchange.com/questions/18979",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/443/"
] | I think the chess engine can "tell" you, but in an indirect way.
What I would do is to play several different moves from the same position. The chess engine will (presumably) give you a different score for each one.
This will allow you to "rank" the various moves. Perhaps a pattern will emerge. If not, you might want to get a (stronger) human player to explain the chess engine's rankings to you. | The engine evaluation ("2"/"1.4") is in fact very similar to how a human would evaluate a position. It is basically a sum of various factors such as *material*, *king safety*, *piece activity*, etc. evaluated not for the current position but for the position some 20 moves ahead or so; assuming perfect play from both sides.
In principle one could try to monitor the change in all those factors separately (instead of only their sum as engines do). For instance if a move leads to a lower value for "king safety" later on compared to the best move, one might be tempted to tell the learner something like: *Your last move made your king more vulnerable*
However I doubt that this would work in actual games, because:
* the learner's move might in fact have other issues: for instance it might neglect development and only because of this the player might have to make concessions later on regarding his king's protection (assuming best play).
* many factors might change at the same time, some going up some going down for instance. Trying to express this in words might be cumbersome, e.g.: *Your last move neglected king safety, but improved your piece's activity and you lost a pawn but occupied an open file* Would this information be helpful to a learner?
Because of this, I doubt that computer's will be able to teach you positional or intuitive play (based on principles) at least with current technology. Better to use classical methods such as other humans, reading/watching/listening annotated games, etc |
18,979 | Can any chess engine tell you why a move is bad or good? For example, say a chess engine says the score against my opponent is currently +2 in my favor. I then make a move and my score drops to say 1.4. Can any engine tell me what I did wrong such that my score dropped from 2 to 1.4 (assuming I didn't hang a piece or pawn etc.)
It seems to me that having chess programmers make their programs even stronger is now pointless and it would be much more beneficial to the average chess player if they could have their programs instruct us why a move is bad (or good), assuming they currently cannot do this. | 2017/10/29 | [
"https://chess.stackexchange.com/questions/18979",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/443/"
] | **Sort of (but not really) - and it's actually getting *harder* for engines to do this for you.** To understand why, you have to understand how the evaluation goes. Engines typically can make snap evaluations on a given position, giving it a raw point value. Then, whatever the position is, they play forward, trying to find the line forward that optimizes that score for both sides.
It's important to understand, that '2.0' or '1.4' score *aren't* the evaluation/score for the current position. Instead, it's the evaluation N moves down the line, with each side playing the best move the engine found. This is why the "Current evaluation score" jumps around while the computer is thinking. It's not that the 'score' for a position changed - it's just that it found a different line moving forward that ended up in a different position (which had a different score.)
In the past, engines sucked. Not just because of sub-optimal algorithms, but because of very slow hardware - if you think compounding interest is powerful, it's nothing compared to [Moore's Law](https://en.wikipedia.org/wiki/Moore%27s_law). So computers back then were just looking a few moves into the future. Which made it relatively easy for a human to follow the logic - your score went down because you're losing your knight the next turn.
But now? If your score went from '2.0' to '-0.3', it's possible it's because, due to some unavoidable tactics over the next 7 moves, that you'll have to give up the exchange in order to avoid losing your queen or getting checkmated. But it's hard to show the leap from "Here's the position now" and "Well, I evaluated 20 billion positions going forward, and trust me when I say that you sacrificing the rook for their bishop was the best you could hope for."
Occasionally a move from a grandmaster winning game is said to be "invisible" to a chess engine. Only after the move is made, the engine recognizes the high value of the move. This weakness in the engine could easily be remedied by more exhaustive checking of possible moves. | I think the chess engine can "tell" you, but in an indirect way.
What I would do is to play several different moves from the same position. The chess engine will (presumably) give you a different score for each one.
This will allow you to "rank" the various moves. Perhaps a pattern will emerge. If not, you might want to get a (stronger) human player to explain the chess engine's rankings to you. |
51,019,433 | I'm trying to develop a plugin, and I'm not the best at developing plugins. I do ofc know php, and oop, but the wp functions is pretty difficult to understand, and also the codex.
I'm trying to make an "ORDERS" page, where you can click on a button, to go to `view_order.php` where it will fetch all the data from the specific ID.
I got it all to work, to fetch out of the right table etc, but the problem is, that i have a `<a href` like this:
```
<a href="view_order.php?id=<?php echo $row->id; ?> ">
```
(It finds the id, so no problems there) but when i click on it, it will go to
>
> <http://localhost/wp-admin/view_order.php?id=3>
>
>
>
and ofc say that it can't find the page. I'm a bit confused here. What can i do? | 2018/06/25 | [
"https://Stackoverflow.com/questions/51019433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8533033/"
] | use this as a reference
```
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
``` | I just tested on my phone and the navbar seems to be fixed no problem. Maybe adding this meta tag will help you
`<meta name="viewport" content="width=device-width, initial-scale=1">` |
31,409,502 | I have a `table` that I want to select the very first `TH` only if it contains a `caption`. I thought it might be something like this:
```css
.myTable caption + tr th:first-child
{
/* stuff */
}
```
It's instead selecting nothing. Is this a bug in CSS or just my logic?
See my JSFiddle: <https://jsfiddle.net/ukb13pdp/1/>
```css
.objectTable th:first-child
{
background-color: blue;
color: white;
}
.objectTable caption + tr th:first-child
{
background-color: red;
}
```
```html
<table class='objectTable'>
<caption>Caption Table</caption>
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
<br/><br/>
<span>No Caption Table</span>
<table class='objectTable'>
<tr>
<th>C</th>
<th>D</th>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>
``` | 2015/07/14 | [
"https://Stackoverflow.com/questions/31409502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096126/"
] | The cause here is exactly the same as the one described in [this related question](https://stackoverflow.com/questions/5568859/why-doesnt-table-tr-td-work-when-using-the-child-selector) about the use of child selectors with `tr`. The problem is that `tr` elements are made children of an implicit `tbody` element, so what ends up being the sibling of the `caption` is that `tbody` and not the `tr`:
```
.myTable caption + tbody th:first-child
```
As an aside, if your `th` elements reside in a header row they should ideally be contained in a `thead` element and the data rows contained in explicit `tbody` element(s):
```
<table class=myTable>
<caption>Table with header group</caption>
<thead>
<tr><th>Header<th>Header
<tbody>
<tr><td>Row 1<td>Row 1
<tr><td>Row 2<td>Row 2
</table>
```
And selected using
```
.myTable caption + thead th:first-child
``` | You're forgetting about the `<tbody>` element which wraps the `<tr>` element. Even though not specified in your (otherwise invalid) HTML, the `<tbody>` element is automatically implemented by the browser as a way of validating this, so instead of:
```
<caption>
<tr>
```
You end up with:
```
<caption>
<tbody>
<tr>
```
As seen in this element inspector capture below:

To select the very first `<tr>` element after a `<caption>` element, you can instead use:
```css
caption + tbody tr:first-child {
...
}
```
[**JSFiddle demo**](https://jsfiddle.net/ukb13pdp/3/). |
120,326 | I am a beginning graduate student in Mathematics. I have a professor who always brings up the fact that my GPA is not great in my undergraduate degree even though my performance is above the norm in the institution I am enrolled at the moment, so far I got straight A's in the graduate courses that I have completed. He always tries to point out at my flaws in my undergraduate years to humiliate me in front of other professors and my colleagues. What would be a wise reply/reaction to such abuse?
I feel bad about it cause I feel like I am harassed and I don't reply.
I am also currently taking a course with that professor. | 2018/11/19 | [
"https://academia.stackexchange.com/questions/120326",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/99012/"
] | There are several possibilities. Some may be appropriate. Some may work. Or not.
**Avoidance**. If possible, just avoid this person. Don't have anything to do with him. Difficult, I know. There are probably limited options to do that.
**Ignore his taunts**. My guess is that he disgraces himself when he does this. If he does this publicly, other students probably see it for what it is. But a public, angry, response from you would probably do yourself more harm than it is worth.
**Formal Complaint**. This will have consequences all 'round, but might be effective. His department chair might be interested to hear what you have to say, especially if the professor is un-tenured. But a complaint from a group of students would be more effective than one from a single student. And make the complaint in person or using a formal mail. Email is too easy to ignore, for this.
Try not to feel bad. The actions of the prof are inexcusable and aren't due to anything in you or that you can actually correct. Know it for what it is: unprofessional behavior. | It would appear that he is trying to shame you to make himself feel better. This is not unusual behaviour, though you would hope for better from a senior academic. One solution is to call him on it enough to stop it but not enough to make an enemy of him:
"Yes, my GPA was indeed 3.0. That seems to have really caught your attention because you've mentioned it the last 9 times we've met."
I would not try to emphasis that you are getting great grades now. The important bit is to call him on his GPA-focus, particularly if there are other people around. Do it in a manner which suggests that you are genuinely curious about why he is mentioning it, rather than letting him know that it irks you. |
120,326 | I am a beginning graduate student in Mathematics. I have a professor who always brings up the fact that my GPA is not great in my undergraduate degree even though my performance is above the norm in the institution I am enrolled at the moment, so far I got straight A's in the graduate courses that I have completed. He always tries to point out at my flaws in my undergraduate years to humiliate me in front of other professors and my colleagues. What would be a wise reply/reaction to such abuse?
I feel bad about it cause I feel like I am harassed and I don't reply.
I am also currently taking a course with that professor. | 2018/11/19 | [
"https://academia.stackexchange.com/questions/120326",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/99012/"
] | As I understand you, you are being *publicly* shamed (in front of fellow grad students) by this professor by dint of your undergrad record.
If you are in the US, this is violating FERPA by revealing your academic record. Other countries have similar privacy laws. File a FERPA complaint and wipe that smug smile off his face.
I'm no expert and I suspect each school is different. But this is a federal law and I think most schools would take such a blatant violation seriously. I'm pretty sure this prof would get his leash yanked pretty hard.
Note that it could backfire. You could an enemy who will make your graduate experience miserable. But I'm betting against it. There have been a number of times when I just let a jerk be a jerk because I thought my life would go more smoothly, but found out later that if I had stood up for myself, I would have gotten a standing ovation from 99% of the people around me. This prof is a jerk and his colleagues will likely appreciate him being called out.
Also, in the case of harassment and rights violations, the perpetrator is warned against retaliation in any form. And someone will be watching for it. Someone behind those closed doors will tattle. I think you are perfectly safe.
### My experience
When I taught small classes, I would write all the test scores on the board, so that students could see where they ranked. One young lady thought I was violating FERPA with this tattled on me. I got hauled into the chairs office where he was accompanied with one of those university JD types (the law students who never pass the bar, but get jobs at universities being annoying.) and the dean. They were ready to have a field day with me. They had already talked to other students and had corroboration that I had, in fact, written all the scores on the board. The JD was salivating.
We talked at cross purposes for a while, then they figured out that I was writing numbers only. No names. No personal information was being displayed. They were so disappointed. An administrator gets to be administrative so rarely and here they had an open-and-shut case go up in smoke.
So the point here is that at this school at this time, FERPA violations were a big deal. I suspect that in the current safe-room environment, they might be a bigger deal. Telling the class that that guy right there has a low GPA could traumatize him for life, eh? | It would appear that he is trying to shame you to make himself feel better. This is not unusual behaviour, though you would hope for better from a senior academic. One solution is to call him on it enough to stop it but not enough to make an enemy of him:
"Yes, my GPA was indeed 3.0. That seems to have really caught your attention because you've mentioned it the last 9 times we've met."
I would not try to emphasis that you are getting great grades now. The important bit is to call him on his GPA-focus, particularly if there are other people around. Do it in a manner which suggests that you are genuinely curious about why he is mentioning it, rather than letting him know that it irks you. |
120,326 | I am a beginning graduate student in Mathematics. I have a professor who always brings up the fact that my GPA is not great in my undergraduate degree even though my performance is above the norm in the institution I am enrolled at the moment, so far I got straight A's in the graduate courses that I have completed. He always tries to point out at my flaws in my undergraduate years to humiliate me in front of other professors and my colleagues. What would be a wise reply/reaction to such abuse?
I feel bad about it cause I feel like I am harassed and I don't reply.
I am also currently taking a course with that professor. | 2018/11/19 | [
"https://academia.stackexchange.com/questions/120326",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/99012/"
] | I've gone through this nonsense before. Here is an interaction I had with one of my professors regarding an assignment I had in college, around 20 years ago:
>
> Me: Sir, I know what pride is but what is prejudice?
>
> Him: Prejudice means, "what I have against you"
>
>
>
Best part is, I still did not understand.
That professor is looking for a reaction from you. Detach from the negative experience, don't react negatively and you will stop the very thing that feeds their ego.
You have to attack the core of his belief system. | It would appear that he is trying to shame you to make himself feel better. This is not unusual behaviour, though you would hope for better from a senior academic. One solution is to call him on it enough to stop it but not enough to make an enemy of him:
"Yes, my GPA was indeed 3.0. That seems to have really caught your attention because you've mentioned it the last 9 times we've met."
I would not try to emphasis that you are getting great grades now. The important bit is to call him on his GPA-focus, particularly if there are other people around. Do it in a manner which suggests that you are genuinely curious about why he is mentioning it, rather than letting him know that it irks you. |
120,326 | I am a beginning graduate student in Mathematics. I have a professor who always brings up the fact that my GPA is not great in my undergraduate degree even though my performance is above the norm in the institution I am enrolled at the moment, so far I got straight A's in the graduate courses that I have completed. He always tries to point out at my flaws in my undergraduate years to humiliate me in front of other professors and my colleagues. What would be a wise reply/reaction to such abuse?
I feel bad about it cause I feel like I am harassed and I don't reply.
I am also currently taking a course with that professor. | 2018/11/19 | [
"https://academia.stackexchange.com/questions/120326",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/99012/"
] | Seek advice from a trusted mentor.
If you have another professor or advisor who you believe you can speak to about this, I would encourage you to explore that option. Not only is it important to have a positive influence to counteract the negative impact of this professor in your personal development, but quality mentorship is also a component in your future career success.
A mentor who has already passed these trials and tribulations in their career may have very well witnessed and experienced these same behaviors. They can offer a more informed plan for how to treat this with your best interests in mind. What your mentor advises may boil down to the same options @Buffy has laid-out. In the case that you should choose formal action, a mentor supporting you in this could be very influential in how it concludes.
One of the unfortunate realities of academia currently is that institutional mechanisms to discourage and rectify this type of behavior are (in my opinion) rare and frequently ineffective. For better or worse, your professors often have an inordinate amount of influence on your career once you are at the graduate level. For this reason, it's really difficult for a student to utilize formal recourse options. Some schools do have specific [anti-bullying resources](https://graduateschool.vt.edu/student-life/we-hear-your-voice/disrupting_academic_bullying.html), and you should investigate if these exist at your institution. | I feel you have to be careful not to go nuclear, because if he is your professor you have to be careful not to move from "annoyance" to "threat" in his eyes, given he presumably grades your work. However, it seems like he's already put himself in a bad position since you said he "tries ... to humiliate me in front of other professors", not just in class.
I believe to reduce risk of this going nuclear, you have to present as though you're concerned and not accusing.
So go to his boss. Say you're trying to look out for the organisation as a whole. Point out he's breaching privacy laws by repeatedly bringing this up in front of other professors, and if anyone makes an official complaint for any reason then things aren't going to end well for anyone. Ask his boss if they can have a quiet word to "nip this in the bud" and mitigate reputational risk to the organisation, and by implication also to this guy's boss.
Play up your concern for the organisation and try not to get personal. Mention some of the other staff members he's done this in front of. Stress that you believe it's better for all concerned if this just quietly stops happening.
Afterwards, write down what you believe was discussed in the meeting as clearly and succinctly as you can. Send an email to the person you've just met with, thanking them for their time and including your notes on the "informal meeting" (that is, you're explicitly not making a formal complaint right now) "just for their reference" and to "clear things up if I misinterpreted or misunderstood anything".
Assuming this person's boss doesn't argue your email, you've now established yourself on record as trying to deal with it quietly without reputational risk to the organisation. If it escalates or you need to file a formal complaint later, you've established the moral high ground. |
120,326 | I am a beginning graduate student in Mathematics. I have a professor who always brings up the fact that my GPA is not great in my undergraduate degree even though my performance is above the norm in the institution I am enrolled at the moment, so far I got straight A's in the graduate courses that I have completed. He always tries to point out at my flaws in my undergraduate years to humiliate me in front of other professors and my colleagues. What would be a wise reply/reaction to such abuse?
I feel bad about it cause I feel like I am harassed and I don't reply.
I am also currently taking a course with that professor. | 2018/11/19 | [
"https://academia.stackexchange.com/questions/120326",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/99012/"
] | As I understand you, you are being *publicly* shamed (in front of fellow grad students) by this professor by dint of your undergrad record.
If you are in the US, this is violating FERPA by revealing your academic record. Other countries have similar privacy laws. File a FERPA complaint and wipe that smug smile off his face.
I'm no expert and I suspect each school is different. But this is a federal law and I think most schools would take such a blatant violation seriously. I'm pretty sure this prof would get his leash yanked pretty hard.
Note that it could backfire. You could an enemy who will make your graduate experience miserable. But I'm betting against it. There have been a number of times when I just let a jerk be a jerk because I thought my life would go more smoothly, but found out later that if I had stood up for myself, I would have gotten a standing ovation from 99% of the people around me. This prof is a jerk and his colleagues will likely appreciate him being called out.
Also, in the case of harassment and rights violations, the perpetrator is warned against retaliation in any form. And someone will be watching for it. Someone behind those closed doors will tattle. I think you are perfectly safe.
### My experience
When I taught small classes, I would write all the test scores on the board, so that students could see where they ranked. One young lady thought I was violating FERPA with this tattled on me. I got hauled into the chairs office where he was accompanied with one of those university JD types (the law students who never pass the bar, but get jobs at universities being annoying.) and the dean. They were ready to have a field day with me. They had already talked to other students and had corroboration that I had, in fact, written all the scores on the board. The JD was salivating.
We talked at cross purposes for a while, then they figured out that I was writing numbers only. No names. No personal information was being displayed. They were so disappointed. An administrator gets to be administrative so rarely and here they had an open-and-shut case go up in smoke.
So the point here is that at this school at this time, FERPA violations were a big deal. I suspect that in the current safe-room environment, they might be a bigger deal. Telling the class that that guy right there has a low GPA could traumatize him for life, eh? | Seek advice from a trusted mentor.
If you have another professor or advisor who you believe you can speak to about this, I would encourage you to explore that option. Not only is it important to have a positive influence to counteract the negative impact of this professor in your personal development, but quality mentorship is also a component in your future career success.
A mentor who has already passed these trials and tribulations in their career may have very well witnessed and experienced these same behaviors. They can offer a more informed plan for how to treat this with your best interests in mind. What your mentor advises may boil down to the same options @Buffy has laid-out. In the case that you should choose formal action, a mentor supporting you in this could be very influential in how it concludes.
One of the unfortunate realities of academia currently is that institutional mechanisms to discourage and rectify this type of behavior are (in my opinion) rare and frequently ineffective. For better or worse, your professors often have an inordinate amount of influence on your career once you are at the graduate level. For this reason, it's really difficult for a student to utilize formal recourse options. Some schools do have specific [anti-bullying resources](https://graduateschool.vt.edu/student-life/we-hear-your-voice/disrupting_academic_bullying.html), and you should investigate if these exist at your institution. |
120,326 | I am a beginning graduate student in Mathematics. I have a professor who always brings up the fact that my GPA is not great in my undergraduate degree even though my performance is above the norm in the institution I am enrolled at the moment, so far I got straight A's in the graduate courses that I have completed. He always tries to point out at my flaws in my undergraduate years to humiliate me in front of other professors and my colleagues. What would be a wise reply/reaction to such abuse?
I feel bad about it cause I feel like I am harassed and I don't reply.
I am also currently taking a course with that professor. | 2018/11/19 | [
"https://academia.stackexchange.com/questions/120326",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/99012/"
] | Seek advice from a trusted mentor.
If you have another professor or advisor who you believe you can speak to about this, I would encourage you to explore that option. Not only is it important to have a positive influence to counteract the negative impact of this professor in your personal development, but quality mentorship is also a component in your future career success.
A mentor who has already passed these trials and tribulations in their career may have very well witnessed and experienced these same behaviors. They can offer a more informed plan for how to treat this with your best interests in mind. What your mentor advises may boil down to the same options @Buffy has laid-out. In the case that you should choose formal action, a mentor supporting you in this could be very influential in how it concludes.
One of the unfortunate realities of academia currently is that institutional mechanisms to discourage and rectify this type of behavior are (in my opinion) rare and frequently ineffective. For better or worse, your professors often have an inordinate amount of influence on your career once you are at the graduate level. For this reason, it's really difficult for a student to utilize formal recourse options. Some schools do have specific [anti-bullying resources](https://graduateschool.vt.edu/student-life/we-hear-your-voice/disrupting_academic_bullying.html), and you should investigate if these exist at your institution. | It would appear that he is trying to shame you to make himself feel better. This is not unusual behaviour, though you would hope for better from a senior academic. One solution is to call him on it enough to stop it but not enough to make an enemy of him:
"Yes, my GPA was indeed 3.0. That seems to have really caught your attention because you've mentioned it the last 9 times we've met."
I would not try to emphasis that you are getting great grades now. The important bit is to call him on his GPA-focus, particularly if there are other people around. Do it in a manner which suggests that you are genuinely curious about why he is mentioning it, rather than letting him know that it irks you. |
120,326 | I am a beginning graduate student in Mathematics. I have a professor who always brings up the fact that my GPA is not great in my undergraduate degree even though my performance is above the norm in the institution I am enrolled at the moment, so far I got straight A's in the graduate courses that I have completed. He always tries to point out at my flaws in my undergraduate years to humiliate me in front of other professors and my colleagues. What would be a wise reply/reaction to such abuse?
I feel bad about it cause I feel like I am harassed and I don't reply.
I am also currently taking a course with that professor. | 2018/11/19 | [
"https://academia.stackexchange.com/questions/120326",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/99012/"
] | Seek advice from a trusted mentor.
If you have another professor or advisor who you believe you can speak to about this, I would encourage you to explore that option. Not only is it important to have a positive influence to counteract the negative impact of this professor in your personal development, but quality mentorship is also a component in your future career success.
A mentor who has already passed these trials and tribulations in their career may have very well witnessed and experienced these same behaviors. They can offer a more informed plan for how to treat this with your best interests in mind. What your mentor advises may boil down to the same options @Buffy has laid-out. In the case that you should choose formal action, a mentor supporting you in this could be very influential in how it concludes.
One of the unfortunate realities of academia currently is that institutional mechanisms to discourage and rectify this type of behavior are (in my opinion) rare and frequently ineffective. For better or worse, your professors often have an inordinate amount of influence on your career once you are at the graduate level. For this reason, it's really difficult for a student to utilize formal recourse options. Some schools do have specific [anti-bullying resources](https://graduateschool.vt.edu/student-life/we-hear-your-voice/disrupting_academic_bullying.html), and you should investigate if these exist at your institution. | I will copy on [B.Goddard's answer](https://academia.stackexchange.com/a/120346/9200) - wipe the arrogant smile off their face.
On the other hand, this will backfire to you in a matter of seconds, maybe sooner. So be ready for that.
* File as many instances as you can of when you were mocked by that professor.
* Look for a different advisor, discuss your issue with them honestly. (Do not mention the mocker's name until directly asked for it)
* Look for a different university to minimise the mocker's/bully's options to interfere with your career.
With the backup plan go for the complaint and leave. Take your lesson and forget about this professor.
It is highly probable that you were not the only one to be bullied by this professor so there is a chance you will start an avalanche of complaints against them. This might lead not only to wipe the smile off their face but to wipe them off their position as well. |
120,326 | I am a beginning graduate student in Mathematics. I have a professor who always brings up the fact that my GPA is not great in my undergraduate degree even though my performance is above the norm in the institution I am enrolled at the moment, so far I got straight A's in the graduate courses that I have completed. He always tries to point out at my flaws in my undergraduate years to humiliate me in front of other professors and my colleagues. What would be a wise reply/reaction to such abuse?
I feel bad about it cause I feel like I am harassed and I don't reply.
I am also currently taking a course with that professor. | 2018/11/19 | [
"https://academia.stackexchange.com/questions/120326",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/99012/"
] | There are several possibilities. Some may be appropriate. Some may work. Or not.
**Avoidance**. If possible, just avoid this person. Don't have anything to do with him. Difficult, I know. There are probably limited options to do that.
**Ignore his taunts**. My guess is that he disgraces himself when he does this. If he does this publicly, other students probably see it for what it is. But a public, angry, response from you would probably do yourself more harm than it is worth.
**Formal Complaint**. This will have consequences all 'round, but might be effective. His department chair might be interested to hear what you have to say, especially if the professor is un-tenured. But a complaint from a group of students would be more effective than one from a single student. And make the complaint in person or using a formal mail. Email is too easy to ignore, for this.
Try not to feel bad. The actions of the prof are inexcusable and aren't due to anything in you or that you can actually correct. Know it for what it is: unprofessional behavior. | I feel you have to be careful not to go nuclear, because if he is your professor you have to be careful not to move from "annoyance" to "threat" in his eyes, given he presumably grades your work. However, it seems like he's already put himself in a bad position since you said he "tries ... to humiliate me in front of other professors", not just in class.
I believe to reduce risk of this going nuclear, you have to present as though you're concerned and not accusing.
So go to his boss. Say you're trying to look out for the organisation as a whole. Point out he's breaching privacy laws by repeatedly bringing this up in front of other professors, and if anyone makes an official complaint for any reason then things aren't going to end well for anyone. Ask his boss if they can have a quiet word to "nip this in the bud" and mitigate reputational risk to the organisation, and by implication also to this guy's boss.
Play up your concern for the organisation and try not to get personal. Mention some of the other staff members he's done this in front of. Stress that you believe it's better for all concerned if this just quietly stops happening.
Afterwards, write down what you believe was discussed in the meeting as clearly and succinctly as you can. Send an email to the person you've just met with, thanking them for their time and including your notes on the "informal meeting" (that is, you're explicitly not making a formal complaint right now) "just for their reference" and to "clear things up if I misinterpreted or misunderstood anything".
Assuming this person's boss doesn't argue your email, you've now established yourself on record as trying to deal with it quietly without reputational risk to the organisation. If it escalates or you need to file a formal complaint later, you've established the moral high ground. |
120,326 | I am a beginning graduate student in Mathematics. I have a professor who always brings up the fact that my GPA is not great in my undergraduate degree even though my performance is above the norm in the institution I am enrolled at the moment, so far I got straight A's in the graduate courses that I have completed. He always tries to point out at my flaws in my undergraduate years to humiliate me in front of other professors and my colleagues. What would be a wise reply/reaction to such abuse?
I feel bad about it cause I feel like I am harassed and I don't reply.
I am also currently taking a course with that professor. | 2018/11/19 | [
"https://academia.stackexchange.com/questions/120326",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/99012/"
] | As I understand you, you are being *publicly* shamed (in front of fellow grad students) by this professor by dint of your undergrad record.
If you are in the US, this is violating FERPA by revealing your academic record. Other countries have similar privacy laws. File a FERPA complaint and wipe that smug smile off his face.
I'm no expert and I suspect each school is different. But this is a federal law and I think most schools would take such a blatant violation seriously. I'm pretty sure this prof would get his leash yanked pretty hard.
Note that it could backfire. You could an enemy who will make your graduate experience miserable. But I'm betting against it. There have been a number of times when I just let a jerk be a jerk because I thought my life would go more smoothly, but found out later that if I had stood up for myself, I would have gotten a standing ovation from 99% of the people around me. This prof is a jerk and his colleagues will likely appreciate him being called out.
Also, in the case of harassment and rights violations, the perpetrator is warned against retaliation in any form. And someone will be watching for it. Someone behind those closed doors will tattle. I think you are perfectly safe.
### My experience
When I taught small classes, I would write all the test scores on the board, so that students could see where they ranked. One young lady thought I was violating FERPA with this tattled on me. I got hauled into the chairs office where he was accompanied with one of those university JD types (the law students who never pass the bar, but get jobs at universities being annoying.) and the dean. They were ready to have a field day with me. They had already talked to other students and had corroboration that I had, in fact, written all the scores on the board. The JD was salivating.
We talked at cross purposes for a while, then they figured out that I was writing numbers only. No names. No personal information was being displayed. They were so disappointed. An administrator gets to be administrative so rarely and here they had an open-and-shut case go up in smoke.
So the point here is that at this school at this time, FERPA violations were a big deal. I suspect that in the current safe-room environment, they might be a bigger deal. Telling the class that that guy right there has a low GPA could traumatize him for life, eh? | I feel you have to be careful not to go nuclear, because if he is your professor you have to be careful not to move from "annoyance" to "threat" in his eyes, given he presumably grades your work. However, it seems like he's already put himself in a bad position since you said he "tries ... to humiliate me in front of other professors", not just in class.
I believe to reduce risk of this going nuclear, you have to present as though you're concerned and not accusing.
So go to his boss. Say you're trying to look out for the organisation as a whole. Point out he's breaching privacy laws by repeatedly bringing this up in front of other professors, and if anyone makes an official complaint for any reason then things aren't going to end well for anyone. Ask his boss if they can have a quiet word to "nip this in the bud" and mitigate reputational risk to the organisation, and by implication also to this guy's boss.
Play up your concern for the organisation and try not to get personal. Mention some of the other staff members he's done this in front of. Stress that you believe it's better for all concerned if this just quietly stops happening.
Afterwards, write down what you believe was discussed in the meeting as clearly and succinctly as you can. Send an email to the person you've just met with, thanking them for their time and including your notes on the "informal meeting" (that is, you're explicitly not making a formal complaint right now) "just for their reference" and to "clear things up if I misinterpreted or misunderstood anything".
Assuming this person's boss doesn't argue your email, you've now established yourself on record as trying to deal with it quietly without reputational risk to the organisation. If it escalates or you need to file a formal complaint later, you've established the moral high ground. |
120,326 | I am a beginning graduate student in Mathematics. I have a professor who always brings up the fact that my GPA is not great in my undergraduate degree even though my performance is above the norm in the institution I am enrolled at the moment, so far I got straight A's in the graduate courses that I have completed. He always tries to point out at my flaws in my undergraduate years to humiliate me in front of other professors and my colleagues. What would be a wise reply/reaction to such abuse?
I feel bad about it cause I feel like I am harassed and I don't reply.
I am also currently taking a course with that professor. | 2018/11/19 | [
"https://academia.stackexchange.com/questions/120326",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/99012/"
] | Maybe you could be interested in Non Violent Communication.
From wikipedia:
<https://en.wikipedia.org/wiki/Nonviolent_Communication>
>
> It is based on the idea that all human beings have the capacity for compassion and only resort to violence or behavior that harms themselves and others when they do not recognize more effective strategies for meeting needs.
> Habits of thinking and speaking that lead to the use of violence (social, psychological and physical) are learned through culture. NVC theory supposes all human behavior stems from attempts to meet universal human needs and that these needs are never in conflict. Rather, conflict arises when strategies for meeting needs clash. NVC proposes that people identify shared needs, revealed by the thoughts and feelings that surround these needs, and collaborate to develop strategies that meet them. This creates both harmony and learning for future cooperation.
>
>
>
The idea behind this is that the behavior of the professor is, in some kind of way, the expression of an unmet need. This perception can help you to externalize the problem from yourself and to get out of the mental game.
<https://www.youtube.com/watch?v=4LuPCAh9FCc> | It would appear that he is trying to shame you to make himself feel better. This is not unusual behaviour, though you would hope for better from a senior academic. One solution is to call him on it enough to stop it but not enough to make an enemy of him:
"Yes, my GPA was indeed 3.0. That seems to have really caught your attention because you've mentioned it the last 9 times we've met."
I would not try to emphasis that you are getting great grades now. The important bit is to call him on his GPA-focus, particularly if there are other people around. Do it in a manner which suggests that you are genuinely curious about why he is mentioning it, rather than letting him know that it irks you. |
37,383,507 | Friends, I would like a permanent solution to a script to change password without email access cpanel.
I tried the cpanel api but I could not ...
Could you help me?
I need a page where the User enter the email address and new password, after which the password is changed ...
Please help me ... | 2016/05/23 | [
"https://Stackoverflow.com/questions/37383507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6249483/"
] | ```
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if (![mediaType isEqualToString:(NSString *)kUTTypeMovie])
return;
mediaURl = [info objectForKey:UIImagePickerControllerMediaURL];
//NSLog(@"mediaURL %@",mediaURl);
moviePath = mediaURl.absoluteString;
// NSLog(@"moviePath %@",moviePath);
tempFilePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
NSLog(@"filepath %@",tempFilePath);
//if you want only file name
NSArray *ar = [tempFilePath componentsSeparatedByString:@"/"];
NSString *filename = [[ar lastObject] uppercaseString];
NSLog(@"filename %@",filename);
}
```
Let me know if you have any issues | Swift 4 or later
Working on My Side for the captured image
Use :
```
imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
let fileName = FileInfo.getMediaName(info: info)
}
```
class : pleas put the method **info[:]**
```
class FileInfo {
// Return Media name
static func getMediaName(info:[String : Any]) -> String {
if let asset = info[UIImagePickerControllerPHAsset] as? PHAsset {
let assetResources = PHAssetResource.assetResources(for: asset)
let firstObj = assetResources.first?.originalFilename as! NSString
print(firstObj)
return firstObj
}
}
}
```
// IMG\_02256.jpeg |
37,383,507 | Friends, I would like a permanent solution to a script to change password without email access cpanel.
I tried the cpanel api but I could not ...
Could you help me?
I need a page where the User enter the email address and new password, after which the password is changed ...
Please help me ... | 2016/05/23 | [
"https://Stackoverflow.com/questions/37383507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6249483/"
] | I know this thread is super old but i thought if someone finds it, here is a working answer in swift:
```
func fileName(for infoDict: [String : Any]) -> String? {
guard let referenceURL = infoDict[UIImagePickerControllerReferenceURL] as? URL else { return nil }
let result = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil)
guard let asset = result.firstObject else { return nil }
let firstResource = PHAssetResource.assetResources(for: asset).first
return firstResource?.originalFilename ?? asset.value(forKey: "filename") as? String
}
``` | Swift 4 or later
Working on My Side for the captured image
Use :
```
imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
let fileName = FileInfo.getMediaName(info: info)
}
```
class : pleas put the method **info[:]**
```
class FileInfo {
// Return Media name
static func getMediaName(info:[String : Any]) -> String {
if let asset = info[UIImagePickerControllerPHAsset] as? PHAsset {
let assetResources = PHAssetResource.assetResources(for: asset)
let firstObj = assetResources.first?.originalFilename as! NSString
print(firstObj)
return firstObj
}
}
}
```
// IMG\_02256.jpeg |
35,122,934 | I have my config/mail 'driver' set to mandrill, host, port, etc. including in services.php mandrill secret set.
Sending Mail works fine locally, but on the live server I get:
>
> Class 'GuzzleHttp\Client' not found
>
>
>
I have tried "guzzlehttp/guzzle": "~5.3|~6.0", and then back to "guzzlehttp/guzzle": "~4.0", no luck. I have done composer update, and dump-autoload still no luck on my live server. Been through every other associated Stackoverflow question and still can't resolve. | 2016/02/01 | [
"https://Stackoverflow.com/questions/35122934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3820348/"
] | Please follow these simple steps:
**First:** Place this on top of your class
```
use Guzzlehttp\Client;
```
**Second:** Inside your function, instead of using
```
$client = new Client();
```
use
```
$client = new \GuzzleHttp\Client();
```
**reference:**
<http://docs.guzzlephp.org/en/latest/quickstart.html> | try composer require guzzlehttp/guzzle without specifying the version. Worked for me |
35,122,934 | I have my config/mail 'driver' set to mandrill, host, port, etc. including in services.php mandrill secret set.
Sending Mail works fine locally, but on the live server I get:
>
> Class 'GuzzleHttp\Client' not found
>
>
>
I have tried "guzzlehttp/guzzle": "~5.3|~6.0", and then back to "guzzlehttp/guzzle": "~4.0", no luck. I have done composer update, and dump-autoload still no luck on my live server. Been through every other associated Stackoverflow question and still can't resolve. | 2016/02/01 | [
"https://Stackoverflow.com/questions/35122934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3820348/"
] | Please follow these simple steps:
**First:** Place this on top of your class
```
use Guzzlehttp\Client;
```
**Second:** Inside your function, instead of using
```
$client = new Client();
```
use
```
$client = new \GuzzleHttp\Client();
```
**reference:**
<http://docs.guzzlephp.org/en/latest/quickstart.html> | **Error ?** the library GuzzleHttp (which is a Simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data ) is either missing or mis-configured.
**Solution :** run the following command on your terminal(root folder):
```
composer require guzzlehttp/guzzle:^6.5
``` |
70,638 | I have an ASCII-art box and I need a program to open it.
Examples
--------
Input:
```
-------
| |
|_____|
```
Output:
```
/
/
/
/
/
/
/
| |
|_____|
```
Specification
=============
* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
+ All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length
Opening the box:
* Each `-` should be replaced by a `/` in ascending lines and position. | 2016/01/31 | [
"https://codegolf.stackexchange.com/questions/70638",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/40695/"
] | JavaScript ES6, 57 bytes
------------------------
```
s=>s[r="replace"](/-+/,s=>s[r](/-/g,`
$'/`))[r](/-/g,' ')
```
Outputs a leading newline. Works by taking the row of `-`s and converting them into a triangle, then replacing the `-`s with spaces.
Edit: Saved 5 bytes thanks to @edc65. | Python, 125 bytes (110 without box)
===================================
```
i="\n---\n| |\n|_|"
l,b,r=i.count("-"),i.split('\n'),range
for x in r(1,l):print" "*(l-x)+"/"
for x in r(2,len(b)):print b[x]
```
If anyone has any idea how to shorten it, please let me know! |
70,638 | I have an ASCII-art box and I need a program to open it.
Examples
--------
Input:
```
-------
| |
|_____|
```
Output:
```
/
/
/
/
/
/
/
| |
|_____|
```
Specification
=============
* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
+ All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length
Opening the box:
* Each `-` should be replaced by a `/` in ascending lines and position. | 2016/01/31 | [
"https://codegolf.stackexchange.com/questions/70638",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/40695/"
] | **Perl, 61 54 33 + 3 = 36 characters**
--------------------------------------
```
s^-^" "x(length$')."/\n"^ge&chomp
```
Run it as
```
perl -ple 's^-^" "x(length${chr 39})."/\n"^ge&chomp' closed_box_file
```
Each `-` in first line is replaced by a string that is a result of concatenation of some number of , `/` and `\n`. `${chr 39}` evaluates to perl's (in)famous `$'` aka `$POSTMATCH` special variable. Lastly, chomp gets rid of the trailing newline character that was added for the last `-` character.
Thanks to @manatwork for saving 7 + more characters.
**Bonus** - `s^-^" "x$i++."\\\n"^ge&&chop` opens the box from the right edge in 29 + 3 characters :). Run it as:
```
gowtham@ubuntu:~$ cat a
----
| |
|__|
gowtham@ubuntu:~$ perl -plE 's^-^" "x$i++."\\\n"^ge&&chop' closed_box_file
\
\
\
\
| |
|__|
``` | [Vyxal](https://github.com/Lyxal/Vyxal), 16 bytes
=================================================
```
L:£(&‹¥\/꘍,)□Ḣ⁋,
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=L%3A%C2%A3%28%26%E2%80%B9%C2%A5%5C%2F%EA%98%8D%2C%29%E2%96%A1%E1%B8%A2%E2%81%8B%2C&inputs=----%0A%7C%20%20%7C%0A%7C__%7C&header=&footer=) |
70,638 | I have an ASCII-art box and I need a program to open it.
Examples
--------
Input:
```
-------
| |
|_____|
```
Output:
```
/
/
/
/
/
/
/
| |
|_____|
```
Specification
=============
* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
+ All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length
Opening the box:
* Each `-` should be replaced by a `/` in ascending lines and position. | 2016/01/31 | [
"https://codegolf.stackexchange.com/questions/70638",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/40695/"
] | [JavaScript (Node.js)](https://nodejs.org), 56 bytes
====================================================
```javascript
a=>a[b="replace"](/-+/,c=>c[b](d=/-/g,`
$'/`))[b](d,' ')
```
[Try it online!](https://tio.run/##JctBCoMwEEDRfU4RpJCEJs4JxouINOMYpSUYiaWr3D1qfcsP/0M/2jm/t69b0xTqjJWwo37EJoctEodm0OCeYBk77sdBTwgOFuvFQ4E35p@skspUTuueYmhjWvSsvbuJIi9FlNelnE89AA "JavaScript (Node.js) – Try It Online")
Should be written as a comment of **@Neil**'s [answer](https://codegolf.stackexchange.com/a/70655/82328) but I can't create comments yet | [K (ngn/k)](https://github.com/ngn/k), 18 bytes
===============================================
```
{(" /"@|=#*x),1_x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlpDSUFfyaHGVlmrQlPHML6i9n@ahpIuBChxKSgo1SiAQA2EHQ8CNUqa/wE "K (ngn/k) – Try It Online") |
70,638 | I have an ASCII-art box and I need a program to open it.
Examples
--------
Input:
```
-------
| |
|_____|
```
Output:
```
/
/
/
/
/
/
/
| |
|_____|
```
Specification
=============
* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
+ All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length
Opening the box:
* Each `-` should be replaced by a `/` in ascending lines and position. | 2016/01/31 | [
"https://codegolf.stackexchange.com/questions/70638",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/40695/"
] | [Charcoal](https://github.com/somebody1234/Charcoal/wiki), 14 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page)
==============================================================================================================================
```
↙L§⪪θ¶⁰M→✂⪪θ¶¹
```
[Try it online (verbose)](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJb88zyc1rUTHJzUvvSRDw7HEMy8ltUIjuCAns0SjUEcpJk9JU8dAU1OTyze/LFXDKigzPaNEkys4JzM5FU2Voeb//9FKSkq6EMBVowACNVw18SBQA5SJ/a9blgMA) or [try it online (pure)](https://tio.run/##S85ILErOT8z5//9R28z3e9YcWv5o1apzOw5te9S44f2etY/aJj2a0wQVOrTz//9oJSUlXQjgqlEAgRqumngQqAHKxAIA).
**Explanation:**
Split the input by newlines, take the length of the first line, and print a line of that length from the Top-Right to Down-Left:
```
Print(:DownLeft,Length(AtIndex(Split(q,"\n"),0)))
↙L§⪪θ¶⁰
```
Move once to the right:
```
Move(:Right)
M→
```
Split the input by newlines again, and remove the first item, and print what's left implicitly:
```
Slice(Split(q,"\n"),1)
✂⪪θ¶¹
```
(NOTE: Putting the input split by newlines in a variable (since I do it twice above) is ~~1 byte longer~~ also 14 bytes by using a slightly different method (thanks to *@Neil*):
`≔⮌⪪θ¶θ↙L⊟θM→⮌θ` [Try it online (verbose)](https://tio.run/##Pcy9CsMgGIXh3asQp08wN5BMhY4phHRsQwnhqwqi8Qe7eO/GUNpnPS9nU2vY3GpqvcSopYUZM4aIcN@NTuAFZU/LOBfU84FMQdsE/dV97IjvJOiIViYFk9vBc96Km8sI/aylSv/@d9mKodYHY6z7IoWeCimvU2nLUrtsDg) or [try it online (pure)](https://tio.run/##S85ILErOT8z5//9R55RH63oerVp1bsehbed2PGqb@X7Pmkdd88/teL9n7aO2SUDJczv@/49WUlLShQCuGgUQqOGqiQeBGqBMLAA)). | Ruby, 59 characters
===================
(57 characters code + 2 characters command line options.)
```ruby
s=""
$_=$_.chars.map{(s<<" ")[1..-1]+?/}.reverse*$/if$.<2
```
Sample run:
```
bash-4.3$ ruby -ple 's="";$_=$_.chars.map{(s<<" ")[1..-1]+?/}.reverse*$/if$.<2' <<< $'-------\n| |\n|_____|'
/
/
/
/
/
/
/
| |
|_____|
``` |
70,638 | I have an ASCII-art box and I need a program to open it.
Examples
--------
Input:
```
-------
| |
|_____|
```
Output:
```
/
/
/
/
/
/
/
| |
|_____|
```
Specification
=============
* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
+ All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length
Opening the box:
* Each `-` should be replaced by a `/` in ascending lines and position. | 2016/01/31 | [
"https://codegolf.stackexchange.com/questions/70638",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/40695/"
] | [JavaScript (Node.js)](https://nodejs.org), 56 bytes
====================================================
```javascript
a=>a[b="replace"](/-+/,c=>c[b](d=/-/g,`
$'/`))[b](d,' ')
```
[Try it online!](https://tio.run/##JctBCoMwEEDRfU4RpJCEJs4JxouINOMYpSUYiaWr3D1qfcsP/0M/2jm/t69b0xTqjJWwo37EJoctEodm0OCeYBk77sdBTwgOFuvFQ4E35p@skspUTuueYmhjWvSsvbuJIi9FlNelnE89AA "JavaScript (Node.js) – Try It Online")
Should be written as a comment of **@Neil**'s [answer](https://codegolf.stackexchange.com/a/70655/82328) but I can't create comments yet | Python, 125 bytes (110 without box)
===================================
```
i="\n---\n| |\n|_|"
l,b,r=i.count("-"),i.split('\n'),range
for x in r(1,l):print" "*(l-x)+"/"
for x in r(2,len(b)):print b[x]
```
If anyone has any idea how to shorten it, please let me know! |
70,638 | I have an ASCII-art box and I need a program to open it.
Examples
--------
Input:
```
-------
| |
|_____|
```
Output:
```
/
/
/
/
/
/
/
| |
|_____|
```
Specification
=============
* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
+ All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length
Opening the box:
* Each `-` should be replaced by a `/` in ascending lines and position. | 2016/01/31 | [
"https://codegolf.stackexchange.com/questions/70638",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/40695/"
] | **Perl, 61 54 33 + 3 = 36 characters**
--------------------------------------
```
s^-^" "x(length$')."/\n"^ge&chomp
```
Run it as
```
perl -ple 's^-^" "x(length${chr 39})."/\n"^ge&chomp' closed_box_file
```
Each `-` in first line is replaced by a string that is a result of concatenation of some number of , `/` and `\n`. `${chr 39}` evaluates to perl's (in)famous `$'` aka `$POSTMATCH` special variable. Lastly, chomp gets rid of the trailing newline character that was added for the last `-` character.
Thanks to @manatwork for saving 7 + more characters.
**Bonus** - `s^-^" "x$i++."\\\n"^ge&&chop` opens the box from the right edge in 29 + 3 characters :). Run it as:
```
gowtham@ubuntu:~$ cat a
----
| |
|__|
gowtham@ubuntu:~$ perl -plE 's^-^" "x$i++."\\\n"^ge&&chop' closed_box_file
\
\
\
\
| |
|__|
``` | [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 9 bytes
==============================================================================================================
```
g'/1.Λ|»»
```
[Try it online! (legacy-only)](https://tio.run/##MzBNTDJM/f8/XV3fUO/c7JpDuw/t/v9fFwK4ahRAoIarJh4EagA "05AB1E (legacy) – Try It Online")
### How it works
```
g'/1.Λ|»» – Full program. Takes input from STDIN.
g - Length. Only takes the first line into account.
'/ – Push a slash character, "/".
1.Λ – And diagonally up-right, draw a line of slashes of the given length.
|» – Push the remaining inputs (all other lines) joined on newlines.
» – Then join the stack on newlines.
``` |
70,638 | I have an ASCII-art box and I need a program to open it.
Examples
--------
Input:
```
-------
| |
|_____|
```
Output:
```
/
/
/
/
/
/
/
| |
|_____|
```
Specification
=============
* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
+ All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length
Opening the box:
* Each `-` should be replaced by a `/` in ascending lines and position. | 2016/01/31 | [
"https://codegolf.stackexchange.com/questions/70638",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/40695/"
] | Pyth, ~~16~~ 14 bytes
=====================
```
j+_m+*;d\/Uz.z
```
Explanation
```
m Uz - [V for d in range(len(input()))]
+*;d\/ - " "*d + "/"
_ - ^[::-1]
j+ .z - "\n".join(^+rest_of_input())
```
Thanks [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for new algorithm!
[Try it here.](http://pyth.herokuapp.com/?code=j%2B_m%2B*%3Bd%5C%2FUz.z&input=-------%0A|+++++|%0A|_____|&debug=0) | JavaScript ES6, 106 bytes
=========================
```
q=>(q=q.split`
`,n=q[0].length,eval('for(i=0,r="";i<n;i++)r+=" ".repeat(n-i-1)+"/\\n"'),r+q.slice(1).join`
`)
```
Simple enough: getting the length of the first line, creating a spaced-triangle with trailing `/`, and adding that to the original, sliced and joined.
Test it out! (ES6 only `:(`)
----------------------------
```js
F=q=>(q=q.split`
`,n=q[0].length,eval('for(i=0,r="";i<n;i++)r+=" ".repeat(n-i-1)+"/\\n"'),r+q.slice(1).join`
`)
function n(){q.innerHTML=F(o.value)}
o.onkeydown=o.onkeyup=o.onchange=o.onkeypress=n;
n();
```
```css
*{font-family:Consolas,monospace;}textarea{width:100%;height:50%;}#q{white-space:pre;}
```
```html
<textarea id=o>----
| |
|__|</textarea><div id=q>
``` |
70,638 | I have an ASCII-art box and I need a program to open it.
Examples
--------
Input:
```
-------
| |
|_____|
```
Output:
```
/
/
/
/
/
/
/
| |
|_____|
```
Specification
=============
* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
+ All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length
Opening the box:
* Each `-` should be replaced by a `/` in ascending lines and position. | 2016/01/31 | [
"https://codegolf.stackexchange.com/questions/70638",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/40695/"
] | CJam, 14 bytes
==============
```
l,{N'/@S*}%W%q
```
[Try it online!](http://cjam.tryitonline.net/#code=bCx7TicvQFMqfSVXJXE&input=LS0tLS0tLQp8ICAgICB8CnxfX19fX3w)
### How it works
```
l Read the first line from STDIN.
, Compute the line's length. Result: L
{ }% Map; for each I in [0 ... L-1]:
(implicit) Push I.
N Push a linefeed.
'/ Push a slash.
@ Rotate I on top of the stack.
S* Turn I into a string of I spaces.
W% Reverse the resulting array of strings and characters.
q Read the remaining input from STDIN.
``` | Python 2, 100 bytes
===================
```
def o(b):
m=b.split('\n')[1:]
print"\n".join(["/".rjust(i)for i in range(len(m[0]),0,-1)]+m)
```
Defines a function `o` that takes a string as its input. (Full program wasn't specified in the question). |
70,638 | I have an ASCII-art box and I need a program to open it.
Examples
--------
Input:
```
-------
| |
|_____|
```
Output:
```
/
/
/
/
/
/
/
| |
|_____|
```
Specification
=============
* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
+ All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length
Opening the box:
* Each `-` should be replaced by a `/` in ascending lines and position. | 2016/01/31 | [
"https://codegolf.stackexchange.com/questions/70638",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/40695/"
] | Java 8, ~~158~~ 118 bytes
=========================
This is just a start, but hey, FGITWFTW.
```
n->{String o="";int z=n.lastIndexOf("-"),i=z;for(;i-->0;o+="/\n")for(int y=i;y-->0;o+=" ");return o+n.substring(z+2);}
```
Expects input as a string, returns the box. | PowerShell, 55 bytes
--------------------
```
$d,$b=$args-split"`n";($d.length-1)..0|%{" "*$_+"/"};$b
```
Takes input `$args` as a string, `-split`s on newlines ``n` ([reference link](https://technet.microsoft.com/en-us/library/hh847835.aspx)), stores the first line into `$d` (as a string) and the remaining into `$b` (as an array of strings). We then loop from the `length` of the first line (minus 1) to `0` and each iteration output that number of spaces plus a `/`. Finally, output `$b` (the rest of the input string) which by default will output one per line.
### Example Run
```
PS C:\Tools\Scripts\golfing> .\help-me-open-the-box.ps1 "----`n| |`n|__|"
/
/
/
/
| |
|__|
``` |
70,638 | I have an ASCII-art box and I need a program to open it.
Examples
--------
Input:
```
-------
| |
|_____|
```
Output:
```
/
/
/
/
/
/
/
| |
|_____|
```
Specification
=============
* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
+ All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length
Opening the box:
* Each `-` should be replaced by a `/` in ascending lines and position. | 2016/01/31 | [
"https://codegolf.stackexchange.com/questions/70638",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/40695/"
] | Retina, ~~34~~ 20 bytes
=======================
```
-(?=(-*))¶?
$1/¶
-
```
In the first step every `-` is substituted with the `-`'s following it, a `/` and a newline. The newline at the end of the original first line is deleted. In the second step we change the new `-`'s to spaces which results in the desired output.
[Try it online here.](http://retina.tryitonline.net/#code=LSg_PSgtKikpwrY_CiQxL8K2Ci0KIA&input=LS0tLS0tLQp8ICAgICB8CnxfX19fX3w) | PowerShell, 55 bytes
--------------------
```
$d,$b=$args-split"`n";($d.length-1)..0|%{" "*$_+"/"};$b
```
Takes input `$args` as a string, `-split`s on newlines ``n` ([reference link](https://technet.microsoft.com/en-us/library/hh847835.aspx)), stores the first line into `$d` (as a string) and the remaining into `$b` (as an array of strings). We then loop from the `length` of the first line (minus 1) to `0` and each iteration output that number of spaces plus a `/`. Finally, output `$b` (the rest of the input string) which by default will output one per line.
### Example Run
```
PS C:\Tools\Scripts\golfing> .\help-me-open-the-box.ps1 "----`n| |`n|__|"
/
/
/
/
| |
|__|
``` |
70,631,273 | I'm very enthausiast about vuejs but the composition API made me get lost slightly on reactivity:
In a .vue child component a prop is passed (by another parent component), movies:
```
export default {
props:{
movies: Array
},
setup(props){}
```
.
Placing in the **setup** function body of this child component:
```
A) console.log("props: ",props) // Proxy {}
```
[above EXPECTED] above tells me that the props object is a reactive proxy object.
```
B) console.log("props.movies: ",props.movies); // Proxy {}
```
[above UNEXPECTED] above tells me that the props key 'movies' is a reactive proxy object as well, why? (thus why is not only the main props object reactive? Maybe I should just take this for granted *(and e.g. think of it as the result of a props = reactive(props) call)*
--> ANSWER: props is a \*\*deep \*\* reactive object (thanks Michal Levý!)
```
C) let moviesLocal = props.movies ; // ERROR-> getting value from props in root scope of setup will cause the value to loose reactivity
```
[above UNEXPECTED] As props.movies is a reactive object, I'd assume that I can assign this to a local variable, and this local variable then also would become reactive. Why is this not the case (I get the error shown above)
```
D) let moviesLocal = ref(props.movies);
moviesLocal.value[0].Title="CHANGED in child component";
```
[above UNEXPECTED]
I made a local copy in the child component (moviesLocal). This variable I made reactive (ref). Changing the value of the reactive moviesLocal also causes the 'movies' reactive object in the parent object to change, why is that ? *This even holds if I change D: let moviesLocal = ref(props.movies); to let moviesLocal = ref({...props.movies});*
Thanks a lot! Looking forward to understand this behaviour | 2022/01/08 | [
"https://Stackoverflow.com/questions/70631273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1345112/"
] | Use `toRef` to maintain reactivity.
```
const moviesLocalRef = toRef(props, 'movies')
```
See <https://v3.vuejs.org/api/refs-api.html#toref>
The rule is that a `reactive` object child property must always be accessed from the root of the object. `a.b.c.d`. You cannot just `break off a piece and modify it`, because the act of resolving from the root is what allows Vue to track changes.
In your case, the internal property is the same, but Vue has lost the ability to track changes.
As a side note, you can also create a computed reference.
```
const moviesLocalRef = computed(()=>props.movies)
```
Whether you use a `computed ref` or `toRef`, you will need to access your property using `theRef.value` outside of templates. As I state in conclusion, this is what allows Vue to maintain the reactivity.
Conclusion
==========
Here is how I have chosen to think about Vue3 reactivity.
The act of `dereferencing a property` from an object is what triggers the magic.
For a `reactive object`, you need to start with the `reactive object` and then `drill down` to your property of interest. For a `ref`, you need to unbox the `value` from the `ref`. Either way, there is always a `get` operation that triggers the internal mechanism and notifies Vue who is watching what.
This `drilling down` happens automatically in templates and watchers that are aware they received a reference, but not anywhere else.
See <https://v3.vuejs.org/guide/reactivity.html#how-vue-tracks-these-changes> | Important part of understanding Vue reactivity is understanding JavaScript - specifically difference between [Value and Reference](https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0). If you are not sure what I'm talking about, read the article carefully...
In following examples I will be using `props` object as it was created following way (in reality it is not created *exactly* like this but runtime behavior is very similar):
```js
const props = reactive({ movies: [], price: 100 })
```
```
B) console.log("props.movies: ",props.movies); // Proxy {}
```
>
> above tells me that the props key 'movies' is a reactive proxy object as well, why?
>
>
>
Because when Vue creates new reactive object (by wrapping existing object into a Proxy), that conversion is [**deep**](https://v3.vuejs.org/api/basic-reactivity.html#reactive) - it affects all nested properties (this behavior can be changed by using for example `markRaw` or `shallowRef`)
In terms of Value vs Reference the `props` is a variable holding a reference to a reactive proxy object. That object has a property `movies` which holds the reference to a reactive proxy of array (arrays are also technically Objects)
```
C) let moviesLocal = props.movies ;
// ERROR-> getting value from props in root scope of setup will cause the value to loose reactivity
```
>
> As props.movies is a reactive object, I'd assume that I can assign this to a local variable, and this local variable then also would become reactive. Why is this not the case
>
>
>
Variables are not reactive. Only Objects can be reactive. In this case `moviesLocal` variable is assigned with reference to same reactive object as `props.movies` (`moviesLocal === props.movies` returns `true`). This object is **still reactive**.
Let's use our `moviesLocal` variable in the template to render some kind of list...
If for example parent mutates the array referenced by `props.movies` (adding new item with `push()`, assigning different value to `props.movies[0]` etc.) child will be notified about the change and its template will re-render.
So why the error? Where is the "loose reactivity" ? Problem is what happens when parent replaces the value of `props.movies` with different\new array. Our `moviesLocal` variable will still hold the reference to previous reactive array. Our **child component will still be reactive to changes (mutations) of that original array but lost the ability to react to changes of `props.movies` property.**
This is demonstrated in [this demo](https://sfc.vuejs.org/#eyJBcHAudnVlIjoiPHNjcmlwdCBzZXR1cD5cbiAgaW1wb3J0IHsgcmVmIH0gZnJvbSBcInZ1ZVwiXG4gaW1wb3J0IGNvbXAgZnJvbSAnLi9Db21wLnZ1ZSdcblxuIGNvbnN0IG1vdmllcyA9IHJlZihbXCJNYXRyaXhcIiwgXCJJUCBNYW5cIl0pXG4gXG4gY29uc3QgY291bnRlciA9IHJlZigxKVxuIGNvbnN0IG11dGF0ZSA9ICgpID0+IHsgbW92aWVzLnZhbHVlLnB1c2goYFN0YXIgV2FycyAke2NvdW50ZXIudmFsdWUrK31gKSB9XG4gY29uc3QgcmVwbGFjZSA9ICgpID0+IG1vdmllcy52YWx1ZSA9IFtcIk1hdHJpeFwiLCBcIklQIE1hblwiXVxuPC9zY3JpcHQ+XG5cbjx0ZW1wbGF0ZT5cbiAgPGgzPlxuICAgIENoaWxkIGNvbXBvbmVudCBpcyByZWFjdGluZyB0byBhcnJheSBtdXRhdGlvbi4gSXQgd2lsbCBzdG9wIHJlYWN0aW5nIGFzIHNvb24gYXMgeW91IHVzZSBSZXBsYWNlIDFzdCB0aW1lXG4gIDwvaDM+XG4gIDxidXR0b24gQGNsaWNrPVwibXV0YXRlXCI+XG4gICAgTXV0YXRlIChwdXNoKVxuICA8L2J1dHRvbj5cbiAgPGJ1dHRvbiBAY2xpY2s9XCJyZXBsYWNlXCI+XG4gICAgUmVwbGFjZVxuICA8L2J1dHRvbj5cbiAgPGNvbXAgOm1vdmllcz1cIm1vdmllc1wiPjwvY29tcD5cbiAgPHByZT57eyBtb3ZpZXMgfX08L3ByZT5cbjwvdGVtcGxhdGU+IiwiaW1wb3J0LW1hcC5qc29uIjoie1xuICBcImltcG9ydHNcIjoge1xuICAgIFwidnVlXCI6IFwiaHR0cHM6Ly9zZmMudnVlanMub3JnL3Z1ZS5ydW50aW1lLmVzbS1icm93c2VyLmpzXCJcbiAgfVxufSIsIkNvbXAudnVlIjoiPHNjcmlwdCBzZXR1cD5cbiAgaW1wb3J0IHsgd2F0Y2gsIGlzUmVmIH0gZnJvbSBcInZ1ZVwiXG4gIGNvbnN0IHByb3BzID0gZGVmaW5lUHJvcHMoe1xuICAgIG1vdmllczoge1xuICAgICAgdHlwZTogQXJyYXlcbiAgICB9XG4gIH0pXG4gIFxuICBjb25zdCBsb2NhbE1vdmllcyA9IHByb3BzLm1vdmllc1xuICB3YXRjaChsb2NhbE1vdmllcywgKHZhbCkgPT4gY29uc29sZS5sb2coSlNPTi5zdHJpbmdpZnkodmFsKSkpICBcbjwvc2NyaXB0PlxuPHRlbXBsYXRlPlxuICAgPGRpdiB2LWZvcj1cIm0gaW4gbG9jYWxNb3ZpZXNcIj5cbiAgICAge3sgbSB9fVxuICA8L2Rpdj5cbjwvdGVtcGxhdGU+In0=)
The funny thing is that in the core, this behavior has nothing to do with Vue reactivity. It is just plain JS. Check this:
```js
const obj = {
movies: ['Matrix']
}
const local = obj.movies
obj.movies = ['Avatar']
```
What is the value of `local` at this point ? Of course it is `['Matrix']`! `const local = obj.movies` is just value assignment. It does not somehow magically "link" the `local` variable with the value of `obj.movies` object property.
```
D) let moviesLocal = ref(props.movies);
moviesLocal.value[0].Title="CHANGED in child component";
```
>
> I made a local copy in the child component (moviesLocal). This variable I made reactive (ref).
>
>
>
Again, variables **are not reactive**. Objects they point to (reference) can be reactive. Array referenced by `props.movies` was already reactive proxy. You just created a `ref` which holds that same object
>
> Changing the value of the reactive moviesLocal also causes the 'movies' reactive object in the parent object to change, why is that ?
>
>
>
Because both point to (reference) same array (wrapped by Vue proxy) in the memory. Assign a new array to one of them and the this "link" will break... |
72,091 | In Michael Ende's novel *The Neverending Story*, the character Yikka, a talking mule, keeps saying that her intuition comes from being "half an ass (donkey)." "When one is only half an ass, and not a whole one, one knows things." I don't have a German translation of the book to get the original phrase, but... is there something in German language or culture that explains this line? She uses it as an explanation of how she was able to sense the identity of a stranger, and how she sometimes knows what her human rider is thinking. ??? | 2022/11/03 | [
"https://german.stackexchange.com/questions/72091",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/54378/"
] | In German it is
>
> Wenn man bloß ein halber Esel ist wie ich und kein ganzer, dann fühlt man so was.
>
>
>
This is a somewhat mysterious statement and there is nothing in German language or culture that explains it. I think one can only make conjectures about its meaning.
1. Naive explanation.
The word "Esel" (donkey) is often used as synonym for a fool. Perhaps this is the reason why the translator used the word "ass" instead of "donkey". This could mean that Yikka wants to say that she is not foolish enough to ignore the truth.
2. Psychological explanation. See Gronemann, Helmut: Phantásien – Das Reich des Unbewussten. „Die unendliche Geschichte“ von Michael Ende aus der Sicht der Tiefenpsychologie. Zürich: Schweizer Spiegel Verlag 1985. Also see [here](https://phaidra.univie.ac.at/open/o:1262377) p. 79.
*Nach Ansicht Helmut Gronemanns versinnbildlicht der Esel das Unbewusste, das Pferd dagegen verkörpert das Bewusstsein. Das Gespür des Maultieres besteht demnach in der Fähigkeit, beide psychischen Komponenten zu vereinigen. Das höhere Wissen des Tieres versinnbildlicht so die Geschlossenheit, die Bastian erst erreichen muss.*
Translation via DeepL:
*According to Helmut Gronemann, the donkey symbolizes the unconscious, while the horse embodies the conscious. The sense of the mule thus consists in the ability to unite both psychic components. The higher knowledge of the animal thus symbolizes the unity that Bastian must first achieve.*
By the way, here is the [German text](http://maxima-library.org/knigi/knigi/b/25523?format=read). | To be honest, this question is subject to interpretation...
But I'll give it a try. Since Yakka is a mule, she is *technically* half an ass and not a full one. I think Ende plays with different attributes, the word "Esel" (ass) and the animal have in German language and culture:
* The word "Esel" is often used to describe a human being as very stupid. Therefore, the "whole ass" would not be able to feel the things Yakka feels
* On the other hand, donkeys are often considered wiser then humans in Germany (and maybe in other countries) when it comes to feel danger, finding the right way and so on. The fact that donkeys sometimes refuse to follow orders from given by humans is often explained by saying that they are able to see/feel something humans cannot see/feel
So I think, Ende wants to say that Yakka has the wisdom of a donky without being "a whole ass". |
36,354,704 | My iOS app has a pretty common setup: it makes HTTP queries to an API server that responds with JSON objects. These JSON objects are then parsed to appropriate Swift objects.
Initially I divided properties into required properties and optional properties, mostly based on my API server's database requirements. For example, `id`, `email`, and `name` are require fields so they use non-optional types. Others can be `NULL` in database, so they are optional types.
```
class User {
let id: Int
let email: String
let profile: String?
let name: String
let motive: String?
let address: String?
let profilePhotoUrl: String?
}
```
Recently, I started wondering whether this was a good setup at all. I found out that although some properties might be always in the database, that does not mean that those properties will always be included in the JSON response.
For example, in the User profile page, all these fields are needed to properly display the view. Therefore, JSON response will include all these fields. For a view that lists users' names, however, I would not need `email` or `id`, and JSON response should probably not include those properties either. Unfortunately, this will cause error and crash the app when parsing JSON response into Swift object since the app expects `id`, `email`, `name` to be always not-nil.
I'm thinking of changing all properties of Swift objects into optionals, but it feels like throwing away all the benefits of this language-specific feature. Moreover, I will have to write many more lines of code to unwrap all these optionals somewhere else in the app anyway.
On the other hand, JSON objects are by their nature not very interoperable with strict static typing and nil-checking of Swift so it might be better to simply accept that annoyance.
Should I transition to models with every property as optionals? Or is there a better way? I'd appreciate any comment here. | 2016/04/01 | [
"https://Stackoverflow.com/questions/36354704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264622/"
] | There are three ways you can go with this:
1. Always send all the JSON data, and leave your properties non-optional.
2. Make all the properties optional.
3. Make all the properties non-optional, and write your own `init(from:)` method to assign default values to missing values, as described in [this answer](https://stackoverflow.com/a/44575580/7258538).
All of these should work; which one is "best" is opinion-based, and thus out of the scope of a Stack Overflow answer. Choose whichever one is most convenient for your particular need. | I typically make all non-critical properties optional, and then have a failable initializer. This allows me to better handle any changes in the JSON format or broken API contracts.
For example:
```
class User {
let id: Int
let email: String
var profile: String?
var name: String?
var motive: String?
var address: String?
var profilePhotoUrl: String?
}
```
This means that I will never have a user object without an id or email (let's assume those are the two that always need to be associated with a user). If I get a JSON payload without an id or email, the Initializer in the User class will fail and won't create the user object. I then have error handling for failed initializers.
I'd much rather have a swift class with optional properties than a bunch of properties with an empty string value. |
36,354,704 | My iOS app has a pretty common setup: it makes HTTP queries to an API server that responds with JSON objects. These JSON objects are then parsed to appropriate Swift objects.
Initially I divided properties into required properties and optional properties, mostly based on my API server's database requirements. For example, `id`, `email`, and `name` are require fields so they use non-optional types. Others can be `NULL` in database, so they are optional types.
```
class User {
let id: Int
let email: String
let profile: String?
let name: String
let motive: String?
let address: String?
let profilePhotoUrl: String?
}
```
Recently, I started wondering whether this was a good setup at all. I found out that although some properties might be always in the database, that does not mean that those properties will always be included in the JSON response.
For example, in the User profile page, all these fields are needed to properly display the view. Therefore, JSON response will include all these fields. For a view that lists users' names, however, I would not need `email` or `id`, and JSON response should probably not include those properties either. Unfortunately, this will cause error and crash the app when parsing JSON response into Swift object since the app expects `id`, `email`, `name` to be always not-nil.
I'm thinking of changing all properties of Swift objects into optionals, but it feels like throwing away all the benefits of this language-specific feature. Moreover, I will have to write many more lines of code to unwrap all these optionals somewhere else in the app anyway.
On the other hand, JSON objects are by their nature not very interoperable with strict static typing and nil-checking of Swift so it might be better to simply accept that annoyance.
Should I transition to models with every property as optionals? Or is there a better way? I'd appreciate any comment here. | 2016/04/01 | [
"https://Stackoverflow.com/questions/36354704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264622/"
] | There are three ways you can go with this:
1. Always send all the JSON data, and leave your properties non-optional.
2. Make all the properties optional.
3. Make all the properties non-optional, and write your own `init(from:)` method to assign default values to missing values, as described in [this answer](https://stackoverflow.com/a/44575580/7258538).
All of these should work; which one is "best" is opinion-based, and thus out of the scope of a Stack Overflow answer. Choose whichever one is most convenient for your particular need. | I would prefer using failable Initializer its neat compared to other options.
So keep the required properties as non-optionals and create object only if they are present in the response (you can use if-let or gaurd-let to check this in response), else fail the creation of the object.
Using this approach we avoid making non-optionals as optionals and having a pain to handle them throughout the program.
Also optionals are not meant for defensive programming so don't abuse optionals by making "non-optional" properties as optionals. |
36,354,704 | My iOS app has a pretty common setup: it makes HTTP queries to an API server that responds with JSON objects. These JSON objects are then parsed to appropriate Swift objects.
Initially I divided properties into required properties and optional properties, mostly based on my API server's database requirements. For example, `id`, `email`, and `name` are require fields so they use non-optional types. Others can be `NULL` in database, so they are optional types.
```
class User {
let id: Int
let email: String
let profile: String?
let name: String
let motive: String?
let address: String?
let profilePhotoUrl: String?
}
```
Recently, I started wondering whether this was a good setup at all. I found out that although some properties might be always in the database, that does not mean that those properties will always be included in the JSON response.
For example, in the User profile page, all these fields are needed to properly display the view. Therefore, JSON response will include all these fields. For a view that lists users' names, however, I would not need `email` or `id`, and JSON response should probably not include those properties either. Unfortunately, this will cause error and crash the app when parsing JSON response into Swift object since the app expects `id`, `email`, `name` to be always not-nil.
I'm thinking of changing all properties of Swift objects into optionals, but it feels like throwing away all the benefits of this language-specific feature. Moreover, I will have to write many more lines of code to unwrap all these optionals somewhere else in the app anyway.
On the other hand, JSON objects are by their nature not very interoperable with strict static typing and nil-checking of Swift so it might be better to simply accept that annoyance.
Should I transition to models with every property as optionals? Or is there a better way? I'd appreciate any comment here. | 2016/04/01 | [
"https://Stackoverflow.com/questions/36354704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264622/"
] | The first thing to do is ask: Does an element of the “view that lists users' names” need to be the same kind of object as the model object behind a “User profile page”? Perhaps not. Maybe you should create a model specifically for the user list:
```
struct UserList: Decodable {
struct Item: Decodable {
var id: Int
var name: String
}
var items: [Item]
}
```
(Although the question said the JSON response might not include `id`, it doesn't seem like a user list without ids with be particularly useful, so I made it required here.)
If you really want them to be the same kind of object, then maybe you want to model a user as having core properties that the server always sends, and a “details” field that might be nil:
```
class User: Decodable {
let id: Int
let name: String
let details: Details?
struct Details: Decodable {
var email: String
var profile: String?
var motive: String?
var address: String?
var profilePhotoUrl: String?
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
details = container.contains(.email) ? try Details(from: decoder) : nil
}
enum CodingKeys: String, CodingKey {
case id
case name
case email // Used to detect presence of Details
}
}
```
Note that I create the `Details`, if it's present, using `Details(from: decoder)`, instead of the usual `container.decode(Details.self, forKey: .details)`. I do it using `Details(from: decoder)` so that the properties of the `Details` come out of the same JSON object as the properties of the `User`, instead of requiring a nested object. | I would prefer using failable Initializer its neat compared to other options.
So keep the required properties as non-optionals and create object only if they are present in the response (you can use if-let or gaurd-let to check this in response), else fail the creation of the object.
Using this approach we avoid making non-optionals as optionals and having a pain to handle them throughout the program.
Also optionals are not meant for defensive programming so don't abuse optionals by making "non-optional" properties as optionals. |
36,354,704 | My iOS app has a pretty common setup: it makes HTTP queries to an API server that responds with JSON objects. These JSON objects are then parsed to appropriate Swift objects.
Initially I divided properties into required properties and optional properties, mostly based on my API server's database requirements. For example, `id`, `email`, and `name` are require fields so they use non-optional types. Others can be `NULL` in database, so they are optional types.
```
class User {
let id: Int
let email: String
let profile: String?
let name: String
let motive: String?
let address: String?
let profilePhotoUrl: String?
}
```
Recently, I started wondering whether this was a good setup at all. I found out that although some properties might be always in the database, that does not mean that those properties will always be included in the JSON response.
For example, in the User profile page, all these fields are needed to properly display the view. Therefore, JSON response will include all these fields. For a view that lists users' names, however, I would not need `email` or `id`, and JSON response should probably not include those properties either. Unfortunately, this will cause error and crash the app when parsing JSON response into Swift object since the app expects `id`, `email`, `name` to be always not-nil.
I'm thinking of changing all properties of Swift objects into optionals, but it feels like throwing away all the benefits of this language-specific feature. Moreover, I will have to write many more lines of code to unwrap all these optionals somewhere else in the app anyway.
On the other hand, JSON objects are by their nature not very interoperable with strict static typing and nil-checking of Swift so it might be better to simply accept that annoyance.
Should I transition to models with every property as optionals? Or is there a better way? I'd appreciate any comment here. | 2016/04/01 | [
"https://Stackoverflow.com/questions/36354704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264622/"
] | Yes, you should use optional if the property is not necessary in API and if you want some value in the mandatory property then assign blank value:
```
class User {
let id: Int?
let email: String? = ""
let profile: String?
let name: String? = ""
let motive: String?
let address: String?
let profilePhotoUrl: String?
}
``` | I would prefer optional properties because you can not promise JSON values to be there all the time and any change on response property name would crash your app.
If you do not use optional values, you have to control parameters while parsing and add a default value if you want a crash free app. And you wouldn't know if it was nil or empty string from server.
Optional values is your best friends.
[object mapper](https://github.com/Hearst-DD/ObjectMapper#immutablemappable-protocol) for mutable and non-mutable properties.
[realm-swift](https://realm.io/docs/swift/latest/#property-cheatsheet) for default non-optional values. |
36,354,704 | My iOS app has a pretty common setup: it makes HTTP queries to an API server that responds with JSON objects. These JSON objects are then parsed to appropriate Swift objects.
Initially I divided properties into required properties and optional properties, mostly based on my API server's database requirements. For example, `id`, `email`, and `name` are require fields so they use non-optional types. Others can be `NULL` in database, so they are optional types.
```
class User {
let id: Int
let email: String
let profile: String?
let name: String
let motive: String?
let address: String?
let profilePhotoUrl: String?
}
```
Recently, I started wondering whether this was a good setup at all. I found out that although some properties might be always in the database, that does not mean that those properties will always be included in the JSON response.
For example, in the User profile page, all these fields are needed to properly display the view. Therefore, JSON response will include all these fields. For a view that lists users' names, however, I would not need `email` or `id`, and JSON response should probably not include those properties either. Unfortunately, this will cause error and crash the app when parsing JSON response into Swift object since the app expects `id`, `email`, `name` to be always not-nil.
I'm thinking of changing all properties of Swift objects into optionals, but it feels like throwing away all the benefits of this language-specific feature. Moreover, I will have to write many more lines of code to unwrap all these optionals somewhere else in the app anyway.
On the other hand, JSON objects are by their nature not very interoperable with strict static typing and nil-checking of Swift so it might be better to simply accept that annoyance.
Should I transition to models with every property as optionals? Or is there a better way? I'd appreciate any comment here. | 2016/04/01 | [
"https://Stackoverflow.com/questions/36354704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264622/"
] | I typically make all non-critical properties optional, and then have a failable initializer. This allows me to better handle any changes in the JSON format or broken API contracts.
For example:
```
class User {
let id: Int
let email: String
var profile: String?
var name: String?
var motive: String?
var address: String?
var profilePhotoUrl: String?
}
```
This means that I will never have a user object without an id or email (let's assume those are the two that always need to be associated with a user). If I get a JSON payload without an id or email, the Initializer in the User class will fail and won't create the user object. I then have error handling for failed initializers.
I'd much rather have a swift class with optional properties than a bunch of properties with an empty string value. | I would prefer using failable Initializer its neat compared to other options.
So keep the required properties as non-optionals and create object only if they are present in the response (you can use if-let or gaurd-let to check this in response), else fail the creation of the object.
Using this approach we avoid making non-optionals as optionals and having a pain to handle them throughout the program.
Also optionals are not meant for defensive programming so don't abuse optionals by making "non-optional" properties as optionals. |
36,354,704 | My iOS app has a pretty common setup: it makes HTTP queries to an API server that responds with JSON objects. These JSON objects are then parsed to appropriate Swift objects.
Initially I divided properties into required properties and optional properties, mostly based on my API server's database requirements. For example, `id`, `email`, and `name` are require fields so they use non-optional types. Others can be `NULL` in database, so they are optional types.
```
class User {
let id: Int
let email: String
let profile: String?
let name: String
let motive: String?
let address: String?
let profilePhotoUrl: String?
}
```
Recently, I started wondering whether this was a good setup at all. I found out that although some properties might be always in the database, that does not mean that those properties will always be included in the JSON response.
For example, in the User profile page, all these fields are needed to properly display the view. Therefore, JSON response will include all these fields. For a view that lists users' names, however, I would not need `email` or `id`, and JSON response should probably not include those properties either. Unfortunately, this will cause error and crash the app when parsing JSON response into Swift object since the app expects `id`, `email`, `name` to be always not-nil.
I'm thinking of changing all properties of Swift objects into optionals, but it feels like throwing away all the benefits of this language-specific feature. Moreover, I will have to write many more lines of code to unwrap all these optionals somewhere else in the app anyway.
On the other hand, JSON objects are by their nature not very interoperable with strict static typing and nil-checking of Swift so it might be better to simply accept that annoyance.
Should I transition to models with every property as optionals? Or is there a better way? I'd appreciate any comment here. | 2016/04/01 | [
"https://Stackoverflow.com/questions/36354704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264622/"
] | The premise:
>
> Partial representing is a common pattern in REST. Does that mean all
> properties in Swift need to be optionals? For example, the client
> might just need a list of user ids for a view. Does that mean that all
> the other properties (name, email, etc) need to be marked as optional?
> Is this good practice in Swift?
>
>
>
Marking properties optional in a model only indicates that the key may or may not come. It allows the reader to know certain things about the model in the first look itself.
If you maintain only one common model for different API response structures and make all the properties optional, whether that's good practice or not is very debatable.
I have done this and it bites. Sometimes it's fine, sometimes it's just not clear enough.
Keeping one model for multiple APIs is like designing one `ViewController` with many UI elements and depending on particular cases, determining what UI element should be shown or not.
This increases the learning curve for new developers as there's more understanding-the-system involved.
---
### My 2 cents on this:
Assuming we are going ahead with Swift's `Codable` for encoding/decoding models, I would break it up into separate models rather than maintaining a common model with all optionals &/or default values.
Reasons for my decision are:
1. **Clarity of Separation**
* Each model for a specific purpose
* Scope of cleaner custom decoders
+ Useful when the json structure needs a little pre-processing
2. **Consideration of API specific additional keys** that might come later on.
* What if this User list API is the only one requiring more keys like, say, number of friends or some other statistic?
+ Should I continue to load a single model to support different cases with additional keys that come in only one API response but not another?
+ What if a 3rd API is designed to get user information but this time with a slightly different purpose? Should I over-load the same model with yet more keys?
* With a single model, as the project continues to progress, things could get messy as key availability in now very API-case-based. With all being optionals we will have alot of optional bindings & maybe some shortcut nil coalescings here and there which we could have avoided with dedicated models in the first place.
3. **Writing up a model is cheap but maintaining cases is not.**
---
However, if I was lazy and I have a strong feeling crazy changes aren't coming up ahead, I would just go ahead making all the keys optionals and bear the associated costs. | This really depends on the way you are handling your data. If you are handling your data through a "Codable" class, then you have to write a custom decoder to throw an exception when you don't get certain expected values. Like so:
```
class User: Codable {
let id: Int
let email: String
let profile: String?
let name: String
let motive: String?
let address: String?
let profilePhotoUrl: String?
//other methods (such as init, encoder, and decoder) need to be added below.
}
```
Because I know that I'm going to need to return an error if I don't get the minimum required parameters, you would need something like an Error enum:
```
enum UserCodableError: Error {
case missingNeededParameters
//and so on with more cases
}
```
You should be using coding keys to keep things consistent from the server. A way to do that inside of the User Object would be like so:
```
fileprivate enum CodingKeys: String, CodingKey {
case id = "YOUR JSON SERVER KEYS GO HERE"
case email
case profile
case name
case motive
case address
case profilePhotoUrl
}
```
Then, you need to write your Decoder. A way to do that would be like so:
```
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
guard let id = try? values.decode(Int.self, forKey: .id), let email = try? values.decode(String.self, forKey: .email), let name = try? values.decode(String.self, forKey: .name) else {
throw UserCodableError.missingNeededParameters
}
self.id = id
self.email = email
self.name = name
//now simply try to decode the optionals
self.profile = try? values.decode(String.self, forKey: .profile)
self.motive = try? values.decode(String.self, forKey: .motive)
self.address = try? values.decode(String.self, forKey: .address)
self.profilePhotoUrl = try? values.decode(String.self, forKey: .profilePhotoUrl)
}
```
SOMETHING TO NOTE: You should write your own encoder as well to stay consistent.
All of that can go, simply to a nice calling statement like this:
```
if let user = try? JSONDecoder().decode(User.self, from: jsonData) {
//do stuff with user
}
```
This is probably the safest, swift-ist, and most object oriented way to handle this type of issue. |
36,354,704 | My iOS app has a pretty common setup: it makes HTTP queries to an API server that responds with JSON objects. These JSON objects are then parsed to appropriate Swift objects.
Initially I divided properties into required properties and optional properties, mostly based on my API server's database requirements. For example, `id`, `email`, and `name` are require fields so they use non-optional types. Others can be `NULL` in database, so they are optional types.
```
class User {
let id: Int
let email: String
let profile: String?
let name: String
let motive: String?
let address: String?
let profilePhotoUrl: String?
}
```
Recently, I started wondering whether this was a good setup at all. I found out that although some properties might be always in the database, that does not mean that those properties will always be included in the JSON response.
For example, in the User profile page, all these fields are needed to properly display the view. Therefore, JSON response will include all these fields. For a view that lists users' names, however, I would not need `email` or `id`, and JSON response should probably not include those properties either. Unfortunately, this will cause error and crash the app when parsing JSON response into Swift object since the app expects `id`, `email`, `name` to be always not-nil.
I'm thinking of changing all properties of Swift objects into optionals, but it feels like throwing away all the benefits of this language-specific feature. Moreover, I will have to write many more lines of code to unwrap all these optionals somewhere else in the app anyway.
On the other hand, JSON objects are by their nature not very interoperable with strict static typing and nil-checking of Swift so it might be better to simply accept that annoyance.
Should I transition to models with every property as optionals? Or is there a better way? I'd appreciate any comment here. | 2016/04/01 | [
"https://Stackoverflow.com/questions/36354704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264622/"
] | There are three ways you can go with this:
1. Always send all the JSON data, and leave your properties non-optional.
2. Make all the properties optional.
3. Make all the properties non-optional, and write your own `init(from:)` method to assign default values to missing values, as described in [this answer](https://stackoverflow.com/a/44575580/7258538).
All of these should work; which one is "best" is opinion-based, and thus out of the scope of a Stack Overflow answer. Choose whichever one is most convenient for your particular need. | I would prefer optional properties because you can not promise JSON values to be there all the time and any change on response property name would crash your app.
If you do not use optional values, you have to control parameters while parsing and add a default value if you want a crash free app. And you wouldn't know if it was nil or empty string from server.
Optional values is your best friends.
[object mapper](https://github.com/Hearst-DD/ObjectMapper#immutablemappable-protocol) for mutable and non-mutable properties.
[realm-swift](https://realm.io/docs/swift/latest/#property-cheatsheet) for default non-optional values. |
36,354,704 | My iOS app has a pretty common setup: it makes HTTP queries to an API server that responds with JSON objects. These JSON objects are then parsed to appropriate Swift objects.
Initially I divided properties into required properties and optional properties, mostly based on my API server's database requirements. For example, `id`, `email`, and `name` are require fields so they use non-optional types. Others can be `NULL` in database, so they are optional types.
```
class User {
let id: Int
let email: String
let profile: String?
let name: String
let motive: String?
let address: String?
let profilePhotoUrl: String?
}
```
Recently, I started wondering whether this was a good setup at all. I found out that although some properties might be always in the database, that does not mean that those properties will always be included in the JSON response.
For example, in the User profile page, all these fields are needed to properly display the view. Therefore, JSON response will include all these fields. For a view that lists users' names, however, I would not need `email` or `id`, and JSON response should probably not include those properties either. Unfortunately, this will cause error and crash the app when parsing JSON response into Swift object since the app expects `id`, `email`, `name` to be always not-nil.
I'm thinking of changing all properties of Swift objects into optionals, but it feels like throwing away all the benefits of this language-specific feature. Moreover, I will have to write many more lines of code to unwrap all these optionals somewhere else in the app anyway.
On the other hand, JSON objects are by their nature not very interoperable with strict static typing and nil-checking of Swift so it might be better to simply accept that annoyance.
Should I transition to models with every property as optionals? Or is there a better way? I'd appreciate any comment here. | 2016/04/01 | [
"https://Stackoverflow.com/questions/36354704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264622/"
] | In my opinion, I will choose 1 of 2 solutions:
1. Edit my `init func` from `JSON` to `object`, init with default object values for all props (`id = -1, email = ''`), then read JSON with optional checking.
2. Create a new `class/struct` for that specific case. | I would prefer optional properties because you can not promise JSON values to be there all the time and any change on response property name would crash your app.
If you do not use optional values, you have to control parameters while parsing and add a default value if you want a crash free app. And you wouldn't know if it was nil or empty string from server.
Optional values is your best friends.
[object mapper](https://github.com/Hearst-DD/ObjectMapper#immutablemappable-protocol) for mutable and non-mutable properties.
[realm-swift](https://realm.io/docs/swift/latest/#property-cheatsheet) for default non-optional values. |
36,354,704 | My iOS app has a pretty common setup: it makes HTTP queries to an API server that responds with JSON objects. These JSON objects are then parsed to appropriate Swift objects.
Initially I divided properties into required properties and optional properties, mostly based on my API server's database requirements. For example, `id`, `email`, and `name` are require fields so they use non-optional types. Others can be `NULL` in database, so they are optional types.
```
class User {
let id: Int
let email: String
let profile: String?
let name: String
let motive: String?
let address: String?
let profilePhotoUrl: String?
}
```
Recently, I started wondering whether this was a good setup at all. I found out that although some properties might be always in the database, that does not mean that those properties will always be included in the JSON response.
For example, in the User profile page, all these fields are needed to properly display the view. Therefore, JSON response will include all these fields. For a view that lists users' names, however, I would not need `email` or `id`, and JSON response should probably not include those properties either. Unfortunately, this will cause error and crash the app when parsing JSON response into Swift object since the app expects `id`, `email`, `name` to be always not-nil.
I'm thinking of changing all properties of Swift objects into optionals, but it feels like throwing away all the benefits of this language-specific feature. Moreover, I will have to write many more lines of code to unwrap all these optionals somewhere else in the app anyway.
On the other hand, JSON objects are by their nature not very interoperable with strict static typing and nil-checking of Swift so it might be better to simply accept that annoyance.
Should I transition to models with every property as optionals? Or is there a better way? I'd appreciate any comment here. | 2016/04/01 | [
"https://Stackoverflow.com/questions/36354704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264622/"
] | There are three ways you can go with this:
1. Always send all the JSON data, and leave your properties non-optional.
2. Make all the properties optional.
3. Make all the properties non-optional, and write your own `init(from:)` method to assign default values to missing values, as described in [this answer](https://stackoverflow.com/a/44575580/7258538).
All of these should work; which one is "best" is opinion-based, and thus out of the scope of a Stack Overflow answer. Choose whichever one is most convenient for your particular need. | The first thing to do is ask: Does an element of the “view that lists users' names” need to be the same kind of object as the model object behind a “User profile page”? Perhaps not. Maybe you should create a model specifically for the user list:
```
struct UserList: Decodable {
struct Item: Decodable {
var id: Int
var name: String
}
var items: [Item]
}
```
(Although the question said the JSON response might not include `id`, it doesn't seem like a user list without ids with be particularly useful, so I made it required here.)
If you really want them to be the same kind of object, then maybe you want to model a user as having core properties that the server always sends, and a “details” field that might be nil:
```
class User: Decodable {
let id: Int
let name: String
let details: Details?
struct Details: Decodable {
var email: String
var profile: String?
var motive: String?
var address: String?
var profilePhotoUrl: String?
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
details = container.contains(.email) ? try Details(from: decoder) : nil
}
enum CodingKeys: String, CodingKey {
case id
case name
case email // Used to detect presence of Details
}
}
```
Note that I create the `Details`, if it's present, using `Details(from: decoder)`, instead of the usual `container.decode(Details.self, forKey: .details)`. I do it using `Details(from: decoder)` so that the properties of the `Details` come out of the same JSON object as the properties of the `User`, instead of requiring a nested object. |
36,354,704 | My iOS app has a pretty common setup: it makes HTTP queries to an API server that responds with JSON objects. These JSON objects are then parsed to appropriate Swift objects.
Initially I divided properties into required properties and optional properties, mostly based on my API server's database requirements. For example, `id`, `email`, and `name` are require fields so they use non-optional types. Others can be `NULL` in database, so they are optional types.
```
class User {
let id: Int
let email: String
let profile: String?
let name: String
let motive: String?
let address: String?
let profilePhotoUrl: String?
}
```
Recently, I started wondering whether this was a good setup at all. I found out that although some properties might be always in the database, that does not mean that those properties will always be included in the JSON response.
For example, in the User profile page, all these fields are needed to properly display the view. Therefore, JSON response will include all these fields. For a view that lists users' names, however, I would not need `email` or `id`, and JSON response should probably not include those properties either. Unfortunately, this will cause error and crash the app when parsing JSON response into Swift object since the app expects `id`, `email`, `name` to be always not-nil.
I'm thinking of changing all properties of Swift objects into optionals, but it feels like throwing away all the benefits of this language-specific feature. Moreover, I will have to write many more lines of code to unwrap all these optionals somewhere else in the app anyway.
On the other hand, JSON objects are by their nature not very interoperable with strict static typing and nil-checking of Swift so it might be better to simply accept that annoyance.
Should I transition to models with every property as optionals? Or is there a better way? I'd appreciate any comment here. | 2016/04/01 | [
"https://Stackoverflow.com/questions/36354704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264622/"
] | The first thing to do is ask: Does an element of the “view that lists users' names” need to be the same kind of object as the model object behind a “User profile page”? Perhaps not. Maybe you should create a model specifically for the user list:
```
struct UserList: Decodable {
struct Item: Decodable {
var id: Int
var name: String
}
var items: [Item]
}
```
(Although the question said the JSON response might not include `id`, it doesn't seem like a user list without ids with be particularly useful, so I made it required here.)
If you really want them to be the same kind of object, then maybe you want to model a user as having core properties that the server always sends, and a “details” field that might be nil:
```
class User: Decodable {
let id: Int
let name: String
let details: Details?
struct Details: Decodable {
var email: String
var profile: String?
var motive: String?
var address: String?
var profilePhotoUrl: String?
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
details = container.contains(.email) ? try Details(from: decoder) : nil
}
enum CodingKeys: String, CodingKey {
case id
case name
case email // Used to detect presence of Details
}
}
```
Note that I create the `Details`, if it's present, using `Details(from: decoder)`, instead of the usual `container.decode(Details.self, forKey: .details)`. I do it using `Details(from: decoder)` so that the properties of the `Details` come out of the same JSON object as the properties of the `User`, instead of requiring a nested object. | I typically make all non-critical properties optional, and then have a failable initializer. This allows me to better handle any changes in the JSON format or broken API contracts.
For example:
```
class User {
let id: Int
let email: String
var profile: String?
var name: String?
var motive: String?
var address: String?
var profilePhotoUrl: String?
}
```
This means that I will never have a user object without an id or email (let's assume those are the two that always need to be associated with a user). If I get a JSON payload without an id or email, the Initializer in the User class will fail and won't create the user object. I then have error handling for failed initializers.
I'd much rather have a swift class with optional properties than a bunch of properties with an empty string value. |
8,401,785 | Debugging a package procedure and am getting a no data found when there is in fact data.
Testing just the SELECT
```
SELECT trim(trailing '/' from GL_SECURITY) as DUMMY
FROM b2k_user@b2k
WHERE sms_username = 'FUCHSB';
```
This happily returns my value : '23706\*706'
As soon as i try to have this selected INTO i get a NO\_DATA \_FOUND error
(commented out the error handling i put in)
```
set serveroutput on
DECLARE
p_BAS_user_name varchar2(20);
v_gl_inclusion varchar2(1000);
v_gl_exclusions varchar2(1000);
BEGIN
--inputs
p_BAS_user_name := 'FUCHSB';
dbms_output.put_line(p_BAS_user_name);
----- GOOD -----
--BEGIN
SELECT trim(trailing '/' from GL_SECURITY) as DUMMY
INTO v_gl_inclusion
FROM b2k_user@b2k
WHERE sms_username = p_BAS_user_name;
--EXCEPTION
-- WHEN NO_DATA_FOUND THEN
-- v_gl_inclusion := 'SUPER EFFING STUPID';
--END;
dbms_output.put_line(v_gl_inclusion);
END;
Error report:
ORA-01403: no data found
ORA-06512: at line 12
01403. 00000 - "no data found"
*Cause:
*Action:
FUCHSB
```
I can catch the error just fine except for the fact that based on the 1st query i know 100% there is a value for FUCHSB in the database.
Any ideas.. I'm really starting to despise Oracle. Yes this query is being run over a datalink as seen in the 1st query the data is there.
Thanks
---
SOLVED strange behavior in SQL developer caused me to overlook potential whitespace:
It looks as though SQL Developer when running the standalone select applies its own trimming comparator when doing the 'WHERE sms\_username = p\_BAS\_user\_name;' portion.. turns out when sitting in the package it does not.. bunch of white space was causing the issue.. still strange that it returns on the normal select. Thanks though! | 2011/12/06 | [
"https://Stackoverflow.com/questions/8401785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1083699/"
] | I'm pretty sure I found the cause of this behaviour: I'm guessing that the column is actually of type CHAR and not VARCHAR2.
Consider the following:
```
SQL> CREATE TABLE t (a CHAR(10));
Table created.
SQL> INSERT INTO t VALUES ('FUCHSB');
1 row created.
SQL> SELECT * FROM t WHERE a = 'FUCHSB';
A
----------
FUCHSB
SQL> DECLARE
2 l VARCHAR2(20) := 'FUCHSB';
3 BEGIN
4 SELECT a INTO l FROM t WHERE a = l;
5 END;
6 /
DECLARE
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4
```
Conclusion:
* When working with the CHAR datatype, declare your PL/SQL variables as CHAR.
* When possible, prefer the VARCHAR2 datatype for table column definition. The CHAR datatype is just a bloated VARCHAR2 datatype and doesn't add any feature over the VARCHAR2 datatype (consuming more space/memory is not a feature). | I noticed another issue for the same error.
ERROR at line xx:
ORA-01403: no data found
ORA-06512: at line xx
```
select abc into var from table
```
If the query return no data, above error will throw. |
3,888,867 | Currently I am studying Standard Template Library (STL).
In this program I am storing some long values in Associative Container and then sorting them according to unit's place (according to the number in unit's place).
**Code :**
```
#include <iostream>
#include <set>
#include <functional>
using namespace std;
class UnitLess
{
public:
bool operator()(long first, long second)
{
long fu = first % 10;
long su = second % 10;
return fu < su;
}
};
typedef set<long, UnitLess> Ctnr;
int main(void)
{
Ctnr store;
store.insert(3124);
store.insert(5236);
store.insert(2347);
store.insert(6415);
store.insert(4548);
store.insert(6415);
for(Ctnr::iterator i = store.begin(); i != store.end(); ++i)
{
cout << *i << endl;
}
}
```
But I don't understand why our Professor has overloaded () operator ?
Thanks. | 2010/10/08 | [
"https://Stackoverflow.com/questions/3888867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92487/"
] | The class's purpose is to implement a function that sorts the elements in the set in a given way. This is known as a predicate.
It is implemented as a functor, i.e. by allowing the function operator to be used on an object (this is what std::set does beneath the hood). Doing so is the common way for STL and similar code to call custom objects. (A function pointer is more limited than a function object (a.k.a. functor)
So it's used like this:
```
Unitless functor;
functor(123, 124); // returns true or false
```
std::set is a sorted binary tree, so it calls the Unitless's ()-operator several times on each insert to determine where each long value should go.
Try compiling and putting some printf/std::cout in there and see what happens.
Also, be aware that callbacks like this (i.e. when you can't see the call to your code) are scary and confusing in the beginning of your learning curve.
* Then you get used to it and use them all over, because they are neat.
* Then your code gets scary and confusing again and you avoid them like the plague.
* Then you become a duct-tape programmer and use them only where appropriate, but never elsewhere.
;) | `UnitLess` is a [binary predicate](http://www.sgi.com/tech/stl/BinaryPredicate.html), that is required to be a callable with two parameters in STL.
By overloading the function-call operator in `UnitLess` instances of that type can be used like a function that takes two `longs` and returns a `bool`.
```
UnitLess f;
f(5, 10);
```
is equivalent to
```
bool f(long first, long second)
{
long fu = first % 10;
long su = second % 10;
return fu < su;
}
f(5, 10);
``` |
3,888,867 | Currently I am studying Standard Template Library (STL).
In this program I am storing some long values in Associative Container and then sorting them according to unit's place (according to the number in unit's place).
**Code :**
```
#include <iostream>
#include <set>
#include <functional>
using namespace std;
class UnitLess
{
public:
bool operator()(long first, long second)
{
long fu = first % 10;
long su = second % 10;
return fu < su;
}
};
typedef set<long, UnitLess> Ctnr;
int main(void)
{
Ctnr store;
store.insert(3124);
store.insert(5236);
store.insert(2347);
store.insert(6415);
store.insert(4548);
store.insert(6415);
for(Ctnr::iterator i = store.begin(); i != store.end(); ++i)
{
cout << *i << endl;
}
}
```
But I don't understand why our Professor has overloaded () operator ?
Thanks. | 2010/10/08 | [
"https://Stackoverflow.com/questions/3888867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92487/"
] | `UnitLess` is a [binary predicate](http://www.sgi.com/tech/stl/BinaryPredicate.html), that is required to be a callable with two parameters in STL.
By overloading the function-call operator in `UnitLess` instances of that type can be used like a function that takes two `longs` and returns a `bool`.
```
UnitLess f;
f(5, 10);
```
is equivalent to
```
bool f(long first, long second)
{
long fu = first % 10;
long su = second % 10;
return fu < su;
}
f(5, 10);
``` | He has implemented a custom comparison used for std::set that only compares the units i.e. the amount modulo 10. Because std::set is a template, it just tries to call something that looks like a function, whether or not it is one or not. By overloading operator() you make it act like a function.
Doing this can actually in some circumstances be extremely powerful because a struct / class can store state as well as extra parameters. The whole of boost::function / boost::bind is based on doing this (and you don't need to create a class each time).
In the actual example coded there is perhaps a slight flaw as the exercise was simply to sort them by units but it could well eliminate numbers that have the same units but are not actually duplicates. In your sample code there are no such examples (you have a duplicate but that is a duplicate of the whole value). If you had 3478 in addition to 4548, the Set comparator would consider them the same and would not permit the duplicate.
By the way, I am not sure set is what I would call an "associative" container, which refers to key-value pairs. There are no associated values in set, just keys.
One more point: operator() should be const. |
3,888,867 | Currently I am studying Standard Template Library (STL).
In this program I am storing some long values in Associative Container and then sorting them according to unit's place (according to the number in unit's place).
**Code :**
```
#include <iostream>
#include <set>
#include <functional>
using namespace std;
class UnitLess
{
public:
bool operator()(long first, long second)
{
long fu = first % 10;
long su = second % 10;
return fu < su;
}
};
typedef set<long, UnitLess> Ctnr;
int main(void)
{
Ctnr store;
store.insert(3124);
store.insert(5236);
store.insert(2347);
store.insert(6415);
store.insert(4548);
store.insert(6415);
for(Ctnr::iterator i = store.begin(); i != store.end(); ++i)
{
cout << *i << endl;
}
}
```
But I don't understand why our Professor has overloaded () operator ?
Thanks. | 2010/10/08 | [
"https://Stackoverflow.com/questions/3888867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92487/"
] | The class's purpose is to implement a function that sorts the elements in the set in a given way. This is known as a predicate.
It is implemented as a functor, i.e. by allowing the function operator to be used on an object (this is what std::set does beneath the hood). Doing so is the common way for STL and similar code to call custom objects. (A function pointer is more limited than a function object (a.k.a. functor)
So it's used like this:
```
Unitless functor;
functor(123, 124); // returns true or false
```
std::set is a sorted binary tree, so it calls the Unitless's ()-operator several times on each insert to determine where each long value should go.
Try compiling and putting some printf/std::cout in there and see what happens.
Also, be aware that callbacks like this (i.e. when you can't see the call to your code) are scary and confusing in the beginning of your learning curve.
* Then you get used to it and use them all over, because they are neat.
* Then your code gets scary and confusing again and you avoid them like the plague.
* Then you become a duct-tape programmer and use them only where appropriate, but never elsewhere.
;) | He has implemented a custom comparison used for std::set that only compares the units i.e. the amount modulo 10. Because std::set is a template, it just tries to call something that looks like a function, whether or not it is one or not. By overloading operator() you make it act like a function.
Doing this can actually in some circumstances be extremely powerful because a struct / class can store state as well as extra parameters. The whole of boost::function / boost::bind is based on doing this (and you don't need to create a class each time).
In the actual example coded there is perhaps a slight flaw as the exercise was simply to sort them by units but it could well eliminate numbers that have the same units but are not actually duplicates. In your sample code there are no such examples (you have a duplicate but that is a duplicate of the whole value). If you had 3478 in addition to 4548, the Set comparator would consider them the same and would not permit the duplicate.
By the way, I am not sure set is what I would call an "associative" container, which refers to key-value pairs. There are no associated values in set, just keys.
One more point: operator() should be const. |
810 | I've had a suspicion for a while that there are simply not enough active users (or users with enough rep) on Fitness.SE to pass a community close vote.
It looks like I might be correct. [Shog9](https://fitness.meta.stackexchange.com/questions/809/2019-a-year-in-moderation)'s previous post shows the statistic:
```
Action Moderators Community¹
---------------------------------------- ---------- ----------
Questions closed 261 5
```
Obviously we can't compare Fitness.SE to Stack Overflow but the percentage is quite different:
```
Action Moderators Community¹
----------------------------------------- ---------- ----------
Questions closed 33,862 306,210
```
Personally, I have voted to close questions before. Questions that were so blatantly off-topic that I didn't have to think twice. They've hung up around 3 or 4 close votes before a mod either gives the 5th vote or closes it at 4.
Would it be worthwhile to reduce the required number of close votes on Fitness? | 2020/01/08 | [
"https://fitness.meta.stackexchange.com/questions/810",
"https://fitness.meta.stackexchange.com",
"https://fitness.meta.stackexchange.com/users/31284/"
] | Change to 3
===========
Yes, I think the threshold should be lowered to 3 votes to close. | No Change
=========
Keep the close threshold at 5 votes. |
810 | I've had a suspicion for a while that there are simply not enough active users (or users with enough rep) on Fitness.SE to pass a community close vote.
It looks like I might be correct. [Shog9](https://fitness.meta.stackexchange.com/questions/809/2019-a-year-in-moderation)'s previous post shows the statistic:
```
Action Moderators Community¹
---------------------------------------- ---------- ----------
Questions closed 261 5
```
Obviously we can't compare Fitness.SE to Stack Overflow but the percentage is quite different:
```
Action Moderators Community¹
----------------------------------------- ---------- ----------
Questions closed 33,862 306,210
```
Personally, I have voted to close questions before. Questions that were so blatantly off-topic that I didn't have to think twice. They've hung up around 3 or 4 close votes before a mod either gives the 5th vote or closes it at 4.
Would it be worthwhile to reduce the required number of close votes on Fitness? | 2020/01/08 | [
"https://fitness.meta.stackexchange.com/questions/810",
"https://fitness.meta.stackexchange.com",
"https://fitness.meta.stackexchange.com/users/31284/"
] | This is now live!
Thanks so much for your patience here while we got things worked out on our end. I've reviewed your history with closure on two points and find that it does look like this would be a good change to make here.
The first thing I look at is the percentage of questions that get a first close flag or vote that get handled. Here, that's not bad -
[](https://i.stack.imgur.com/5tIgd.png)
So, this looks generally good. While there's definitely some months where things are a bit more rough, in general, we're looking at decent percentages - not perfect, of course, but not bad... so now we turn to the second graph - how many questions per month were handled by moderators versus community members, both closes and reopens.
[](https://i.stack.imgur.com/ePU33.png)
When I see this, the high percentage kinda makes sense - if you're not clear on what this shows, it's indicating that the mods are doing the bulk of the closures here. The purple line is the questions closed per month and the yellow line just below it (and sometimes obscured by it) is the ones that the moderators did the closure for, in the end. It doesn't mean community members weren't participating at all, just that a mod had to cast a vote to close.
While we definitely don't want mods doing all the work as it creates a potentially asymmetric close/reopen process where it's much easier to close than reopen - unless mods are also watching reopens - we also understand that, on smaller sites, this may not be particularly taxing. While the mods are doing a lot of the lifting, the questions closed per month is generally less than one per day, meaning that it's not onerous.
That being said, the community should still be able to handle this without moderator involvement. One of my hopes when I make these changes is that community members will feel more empowered to participate. When five votes were needed, it can feel impossible that you'll ever get enough votes without a mod stepping in. When only three or needed, hopefully that's less of a concern.
Because we ran the big test on many sites that JNat linked to in the comments, we feel pretty secure that this is a safe change to make, so I won't be monitoring it closely. If you have any concerns down the line, please let me know but, for the most part, y'all can consider this change permanent. I'll likely check the numbers in a few months to ensure nothing looks problematic but I won't post an update unless there's something particularly worth mentioning.
If you have any questions, please let me know! | No Change
=========
Keep the close threshold at 5 votes. |
810 | I've had a suspicion for a while that there are simply not enough active users (or users with enough rep) on Fitness.SE to pass a community close vote.
It looks like I might be correct. [Shog9](https://fitness.meta.stackexchange.com/questions/809/2019-a-year-in-moderation)'s previous post shows the statistic:
```
Action Moderators Community¹
---------------------------------------- ---------- ----------
Questions closed 261 5
```
Obviously we can't compare Fitness.SE to Stack Overflow but the percentage is quite different:
```
Action Moderators Community¹
----------------------------------------- ---------- ----------
Questions closed 33,862 306,210
```
Personally, I have voted to close questions before. Questions that were so blatantly off-topic that I didn't have to think twice. They've hung up around 3 or 4 close votes before a mod either gives the 5th vote or closes it at 4.
Would it be worthwhile to reduce the required number of close votes on Fitness? | 2020/01/08 | [
"https://fitness.meta.stackexchange.com/questions/810",
"https://fitness.meta.stackexchange.com",
"https://fitness.meta.stackexchange.com/users/31284/"
] | This is now live!
Thanks so much for your patience here while we got things worked out on our end. I've reviewed your history with closure on two points and find that it does look like this would be a good change to make here.
The first thing I look at is the percentage of questions that get a first close flag or vote that get handled. Here, that's not bad -
[](https://i.stack.imgur.com/5tIgd.png)
So, this looks generally good. While there's definitely some months where things are a bit more rough, in general, we're looking at decent percentages - not perfect, of course, but not bad... so now we turn to the second graph - how many questions per month were handled by moderators versus community members, both closes and reopens.
[](https://i.stack.imgur.com/ePU33.png)
When I see this, the high percentage kinda makes sense - if you're not clear on what this shows, it's indicating that the mods are doing the bulk of the closures here. The purple line is the questions closed per month and the yellow line just below it (and sometimes obscured by it) is the ones that the moderators did the closure for, in the end. It doesn't mean community members weren't participating at all, just that a mod had to cast a vote to close.
While we definitely don't want mods doing all the work as it creates a potentially asymmetric close/reopen process where it's much easier to close than reopen - unless mods are also watching reopens - we also understand that, on smaller sites, this may not be particularly taxing. While the mods are doing a lot of the lifting, the questions closed per month is generally less than one per day, meaning that it's not onerous.
That being said, the community should still be able to handle this without moderator involvement. One of my hopes when I make these changes is that community members will feel more empowered to participate. When five votes were needed, it can feel impossible that you'll ever get enough votes without a mod stepping in. When only three or needed, hopefully that's less of a concern.
Because we ran the big test on many sites that JNat linked to in the comments, we feel pretty secure that this is a safe change to make, so I won't be monitoring it closely. If you have any concerns down the line, please let me know but, for the most part, y'all can consider this change permanent. I'll likely check the numbers in a few months to ensure nothing looks problematic but I won't post an update unless there's something particularly worth mentioning.
If you have any questions, please let me know! | Change to 3
===========
Yes, I think the threshold should be lowered to 3 votes to close. |
230 | It's time to propose the topics for our Challenge Week!
Some notes:
1. Propose one topic per answer (make it CW by checking the checkbox under your answer);
Write them like
`## Topic <br><br>
"description"`.
2. No maximum of proposals, but don't just propose tons of stuff. Propose things that could stimulate questions and answers.
3. Vote other proposals **up** if you like them, and **down** if you don't.
4. Include a short description or notes, otherwise the system won't let you post your answer.
For each Challenge Week, we'll take the most voted proposal (excluding the already asked ones), so keep proposing! Don't wait for others to propose!
Any questions? Use the comments below. :) | 2012/01/24 | [
"https://linguistics.meta.stackexchange.com/questions/230",
"https://linguistics.meta.stackexchange.com",
"https://linguistics.meta.stackexchange.com/users/111/"
] | Syntax
------
The rules and the study of rules that study the construction of sentences in a given language. | Phonology
---------
The branch of linguistics which investigates the ways in which sounds are used systematically in different languages to form words and utterances. |
230 | It's time to propose the topics for our Challenge Week!
Some notes:
1. Propose one topic per answer (make it CW by checking the checkbox under your answer);
Write them like
`## Topic <br><br>
"description"`.
2. No maximum of proposals, but don't just propose tons of stuff. Propose things that could stimulate questions and answers.
3. Vote other proposals **up** if you like them, and **down** if you don't.
4. Include a short description or notes, otherwise the system won't let you post your answer.
For each Challenge Week, we'll take the most voted proposal (excluding the already asked ones), so keep proposing! Don't wait for others to propose!
Any questions? Use the comments below. :) | 2012/01/24 | [
"https://linguistics.meta.stackexchange.com/questions/230",
"https://linguistics.meta.stackexchange.com",
"https://linguistics.meta.stackexchange.com/users/111/"
] | Syntax
------
The rules and the study of rules that study the construction of sentences in a given language. | Pragmatics
----------
A branch of linguistics which studies the ways in which context contributes to meaning. |
230 | It's time to propose the topics for our Challenge Week!
Some notes:
1. Propose one topic per answer (make it CW by checking the checkbox under your answer);
Write them like
`## Topic <br><br>
"description"`.
2. No maximum of proposals, but don't just propose tons of stuff. Propose things that could stimulate questions and answers.
3. Vote other proposals **up** if you like them, and **down** if you don't.
4. Include a short description or notes, otherwise the system won't let you post your answer.
For each Challenge Week, we'll take the most voted proposal (excluding the already asked ones), so keep proposing! Don't wait for others to propose!
Any questions? Use the comments below. :) | 2012/01/24 | [
"https://linguistics.meta.stackexchange.com/questions/230",
"https://linguistics.meta.stackexchange.com",
"https://linguistics.meta.stackexchange.com/users/111/"
] | Second language(s) acquisition
------------------------------
Questions regarding the mechanisms for the acquisition of second languages. | Phonology
---------
The branch of linguistics which investigates the ways in which sounds are used systematically in different languages to form words and utterances. |
230 | It's time to propose the topics for our Challenge Week!
Some notes:
1. Propose one topic per answer (make it CW by checking the checkbox under your answer);
Write them like
`## Topic <br><br>
"description"`.
2. No maximum of proposals, but don't just propose tons of stuff. Propose things that could stimulate questions and answers.
3. Vote other proposals **up** if you like them, and **down** if you don't.
4. Include a short description or notes, otherwise the system won't let you post your answer.
For each Challenge Week, we'll take the most voted proposal (excluding the already asked ones), so keep proposing! Don't wait for others to propose!
Any questions? Use the comments below. :) | 2012/01/24 | [
"https://linguistics.meta.stackexchange.com/questions/230",
"https://linguistics.meta.stackexchange.com",
"https://linguistics.meta.stackexchange.com/users/111/"
] | Second language(s) acquisition
------------------------------
Questions regarding the mechanisms for the acquisition of second languages. | Pragmatics
----------
A branch of linguistics which studies the ways in which context contributes to meaning. |
230 | It's time to propose the topics for our Challenge Week!
Some notes:
1. Propose one topic per answer (make it CW by checking the checkbox under your answer);
Write them like
`## Topic <br><br>
"description"`.
2. No maximum of proposals, but don't just propose tons of stuff. Propose things that could stimulate questions and answers.
3. Vote other proposals **up** if you like them, and **down** if you don't.
4. Include a short description or notes, otherwise the system won't let you post your answer.
For each Challenge Week, we'll take the most voted proposal (excluding the already asked ones), so keep proposing! Don't wait for others to propose!
Any questions? Use the comments below. :) | 2012/01/24 | [
"https://linguistics.meta.stackexchange.com/questions/230",
"https://linguistics.meta.stackexchange.com",
"https://linguistics.meta.stackexchange.com/users/111/"
] | Historical linguistics
----------------------
The study of how languages evolve over the centuries usually interests not only professional linguists, but also classicists, literary critics, as well as other users just interested in languages in general. Historical linguistics will probably make for a great challenge! | Phonology
---------
The branch of linguistics which investigates the ways in which sounds are used systematically in different languages to form words and utterances. |
230 | It's time to propose the topics for our Challenge Week!
Some notes:
1. Propose one topic per answer (make it CW by checking the checkbox under your answer);
Write them like
`## Topic <br><br>
"description"`.
2. No maximum of proposals, but don't just propose tons of stuff. Propose things that could stimulate questions and answers.
3. Vote other proposals **up** if you like them, and **down** if you don't.
4. Include a short description or notes, otherwise the system won't let you post your answer.
For each Challenge Week, we'll take the most voted proposal (excluding the already asked ones), so keep proposing! Don't wait for others to propose!
Any questions? Use the comments below. :) | 2012/01/24 | [
"https://linguistics.meta.stackexchange.com/questions/230",
"https://linguistics.meta.stackexchange.com",
"https://linguistics.meta.stackexchange.com/users/111/"
] | Historical linguistics
----------------------
The study of how languages evolve over the centuries usually interests not only professional linguists, but also classicists, literary critics, as well as other users just interested in languages in general. Historical linguistics will probably make for a great challenge! | Pragmatics
----------
A branch of linguistics which studies the ways in which context contributes to meaning. |
230 | It's time to propose the topics for our Challenge Week!
Some notes:
1. Propose one topic per answer (make it CW by checking the checkbox under your answer);
Write them like
`## Topic <br><br>
"description"`.
2. No maximum of proposals, but don't just propose tons of stuff. Propose things that could stimulate questions and answers.
3. Vote other proposals **up** if you like them, and **down** if you don't.
4. Include a short description or notes, otherwise the system won't let you post your answer.
For each Challenge Week, we'll take the most voted proposal (excluding the already asked ones), so keep proposing! Don't wait for others to propose!
Any questions? Use the comments below. :) | 2012/01/24 | [
"https://linguistics.meta.stackexchange.com/questions/230",
"https://linguistics.meta.stackexchange.com",
"https://linguistics.meta.stackexchange.com/users/111/"
] | Computational Linguistics
-------------------------
An interdisciplinary field dealing with the statistical or rule-based modeling of natural language from a computational perspective. | Phonology
---------
The branch of linguistics which investigates the ways in which sounds are used systematically in different languages to form words and utterances. |
230 | It's time to propose the topics for our Challenge Week!
Some notes:
1. Propose one topic per answer (make it CW by checking the checkbox under your answer);
Write them like
`## Topic <br><br>
"description"`.
2. No maximum of proposals, but don't just propose tons of stuff. Propose things that could stimulate questions and answers.
3. Vote other proposals **up** if you like them, and **down** if you don't.
4. Include a short description or notes, otherwise the system won't let you post your answer.
For each Challenge Week, we'll take the most voted proposal (excluding the already asked ones), so keep proposing! Don't wait for others to propose!
Any questions? Use the comments below. :) | 2012/01/24 | [
"https://linguistics.meta.stackexchange.com/questions/230",
"https://linguistics.meta.stackexchange.com",
"https://linguistics.meta.stackexchange.com/users/111/"
] | Computational Linguistics
-------------------------
An interdisciplinary field dealing with the statistical or rule-based modeling of natural language from a computational perspective. | Pragmatics
----------
A branch of linguistics which studies the ways in which context contributes to meaning. |
230 | It's time to propose the topics for our Challenge Week!
Some notes:
1. Propose one topic per answer (make it CW by checking the checkbox under your answer);
Write them like
`## Topic <br><br>
"description"`.
2. No maximum of proposals, but don't just propose tons of stuff. Propose things that could stimulate questions and answers.
3. Vote other proposals **up** if you like them, and **down** if you don't.
4. Include a short description or notes, otherwise the system won't let you post your answer.
For each Challenge Week, we'll take the most voted proposal (excluding the already asked ones), so keep proposing! Don't wait for others to propose!
Any questions? Use the comments below. :) | 2012/01/24 | [
"https://linguistics.meta.stackexchange.com/questions/230",
"https://linguistics.meta.stackexchange.com",
"https://linguistics.meta.stackexchange.com/users/111/"
] | Methodology
-----------
Topics concerning how linguistic arguments are made, and what is permitted as evidence in supporting a linguistic argument. Questions ideally highlight debates in methodology and different methodological frameworks in different subfields. | Phonology
---------
The branch of linguistics which investigates the ways in which sounds are used systematically in different languages to form words and utterances. |
230 | It's time to propose the topics for our Challenge Week!
Some notes:
1. Propose one topic per answer (make it CW by checking the checkbox under your answer);
Write them like
`## Topic <br><br>
"description"`.
2. No maximum of proposals, but don't just propose tons of stuff. Propose things that could stimulate questions and answers.
3. Vote other proposals **up** if you like them, and **down** if you don't.
4. Include a short description or notes, otherwise the system won't let you post your answer.
For each Challenge Week, we'll take the most voted proposal (excluding the already asked ones), so keep proposing! Don't wait for others to propose!
Any questions? Use the comments below. :) | 2012/01/24 | [
"https://linguistics.meta.stackexchange.com/questions/230",
"https://linguistics.meta.stackexchange.com",
"https://linguistics.meta.stackexchange.com/users/111/"
] | Methodology
-----------
Topics concerning how linguistic arguments are made, and what is permitted as evidence in supporting a linguistic argument. Questions ideally highlight debates in methodology and different methodological frameworks in different subfields. | Pragmatics
----------
A branch of linguistics which studies the ways in which context contributes to meaning. |
21,604,866 | This is the code that I'm using. I can hear that the notification is working, but no text.
```
@Override
public void onReceive(Context context, Intent arg1) {
showNotification(context);
}
private void showNotification(Context context) {
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MyActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setContentTitle("My notification")
.setContentText("Hello World!");
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
``` | 2014/02/06 | [
"https://Stackoverflow.com/questions/21604866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450116/"
] | if you are using support-v4 library the use this code
```
private void showNotification(Context context) {
PendingIntent pIntent = PendingIntent.getActivity(context, 0,
new Intent(context, DashBoard.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
mBuilder.setContentIntent(pIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(0, mBuilder.getNotification());
}
``` | ```
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
``` |
21,604,866 | This is the code that I'm using. I can hear that the notification is working, but no text.
```
@Override
public void onReceive(Context context, Intent arg1) {
showNotification(context);
}
private void showNotification(Context context) {
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MyActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setContentTitle("My notification")
.setContentText("Hello World!");
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
``` | 2014/02/06 | [
"https://Stackoverflow.com/questions/21604866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450116/"
] | You need to add an icon `new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher);` | ```
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
``` |
27,332,170 | Everything seemed to be running okay (for several days), but I ran into an issue only once and having a really hard time to reproduce the problem.
"Comparison method violates its general contract!" was thrown and completely caught me off guard. I have the following:
```
public class CustomComparator implements Comparator<Chromosome> {
public int compare(Chromosome c1, Chromosome c2){
return c1.compareTo(c2);
}
}
```
My Chromosome class:
```
public class Chromosome implements Comparable<Chromosome>{
private double rank;
//bunch of methods...
@Override public int compareTo(Chromosome c){
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this.getRank() == c.getRank()) //getRank() simply returns a double value 'rank'
return EQUAL;
else if (this.getRank() < c.getRank())
return BEFORE;
else //i.e. (this.getRank() > c.getRank())
return AFTER;
}
```
I have an ArrayList and I used both Collections.sort(MyList) and Collections.sort(MyList, Collections.reverseOrder()). They're still working fine up till now. I just ran into that error only once out of 100's of run. Is there something wrong with this implementation? | 2014/12/06 | [
"https://Stackoverflow.com/questions/27332170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4222618/"
] | Java 7 has changed the behavior of their sorting algorithms a bit. They now throw an Exception if a violation of the general contract for the `compareTo` method is detected. You can read about that contract's properties for example [here](https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html).
In general it could be violated for example in case that it would resolve to a < b and b < a. If this was detected before Java 7, it was just silently ignored. Now an Exception will be thrown.
If you want to use the old behaviour, you may use the following:
`System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");`
But I don't encourage you to do this. You should just change your implementation to the standard implementation of double comparison via [`Double.compare(a, b)`](http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#compare%28double,%20double%29). This implementation correctly deals with infinity and NaN values for doubles.
Furthermore if your `Comparator` just delegates to the `compareTo` method, it can be discarded in general. | Possibly that one of your parameter might be due to positive or negative infinity i.e. dividing by zero. Also don't rely upon == on double values. You should just use:
```
return Double.compare(this.getRank(), c.getRank());
``` |
4,161,943 | I am a beginner in js, and am puzzled by the following code:
```
Foo = function(arg) {
this.arg = arg;
};
Foo.prototype = {
init: function () {
var f = function () {
alert("current arg: " + this.arg); // am expecting "bar", got undefined
}
f();
}
};
var yo = Foo("bar");
yo.init();
```
I was expected to get "current arg: bar", but got "current arg: undefined". I noticed that by copying this.arg into a "normal" variable first, and refering this variable in the closure works:
```
Foo.prototype = {
init: function () {
var yo = this.arg;
var f = function () {
alert("current arg: " + yo); }
f();
}
};
```
Am I doing something wrong, got wrong expectations, or does it fall into one of the js WTF ? | 2010/11/12 | [
"https://Stackoverflow.com/questions/4161943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11465/"
] | It depends on how the function was invoked.
If invoked with keyword `new` then `this` refers to the object being constructed (which will be implicitly returned at the end of the function).
If invoked as a normal function, `this` refers to the global `window` object.
Example:
```
// Constructor for Foo,
// (invoke with keyword new!)
function Foo()
{
this.name = "Foo" ;
}
myFoo = new Foo() ;
alert( 'myFoo ' + myFoo.name + '\n' + 'window: ' + window.name ) ; // window.name will be empty
// now if we invoke Foo() WITHOUT keyword NEW
// then all references to `this` inside the
// function Foo will be to the
// __global window object__, i.e. the global window
// object will get clobbered with new properties it shouldn't
// have! (.name!)
Foo() ; // incorrect invokation style!
alert( 'myFoo ' + myFoo.name + '\n' + 'window: ' + window.name ) ;
```
JavaScript doesn't have "constructors" per se, the only way JavaScript knows that your `function` is actually a "constructor" is invokation style (namely you using keyword `new` whenever you invoke it) | Vanilla functions will be run with `this` referring to `window`. Your second piece of code is a perfect example of how to work around this problem using closures.
(You can also use `call` and `apply` to call a function with a particular context.) |
615,875 | Good afternoon,
I would like to know how to colour the nodes A and Y in another colour (grey for example) without changing the colour of the other two nodes.
Best regards.
```
\begin{figure}[h]
\centering
\begin{tikzpicture}[
node distance=1cm and 1cm,
mynode/.style={draw,circle,text width=0.5cm,align=center}
]
\node[mynode] (z) {A};
\node[mynode,right=of z] (x) {Y};
\node[mynode,left=of z] (y) {$U_A$};
\node[mynode,right=of x] (w) {$U_Y$};
\path (x) edge[latex-] (z);
\path (y) edge[latex-] (z);
\path (x) edge[latex-] (w);
\end{tikzpicture}
\caption{Graph.}
\end{figure}
``` | 2021/09/18 | [
"https://tex.stackexchange.com/questions/615875",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/252116/"
] | Replace `\pgfcalendarweekdayshortname` by `\myweekday` and define the latter in the preamble as
```
\newcommand\myweekday[1]{\ifcase#1M\or T\or W\or T\or F\or S\or S\fi}
```
[](https://i.stack.imgur.com/Uh52X.png)
```
\documentclass[12pt]{article}
\usepackage{tikz}
\usetikzlibrary{calendar}
\newcommand\myweekday[1]{\ifcase#1M\or T\or W\or T\or F\or S\or S\fi}
\begin{document}
\begin{tikzpicture}
\calendar[dates=2021-01-01 to 2021-01-last,
day list downward,
day code={
\node[anchor = east]{\tikzdaytext};
\draw node[anchor = west, gray]{\myweekday{\pgfcalendarcurrentweekday}};
},
execute after day scope={
\ifdate{Sunday}{\pgftransformyshift{1em}}{}},
]
if(weekend) [shape=coordinate]; % (1)
\end{tikzpicture}
\end{document}
``` | Using `\StrLeft` from the `xstring` package:
```
\documentclass[12pt]{article}
\usepackage{tikz}
\usetikzlibrary{calendar}
\usepackage{xstring}
\begin{document}
\begin{tikzpicture}
\calendar[dates=2021-01-01 to 2021-01-last,
day list downward,
day code={
\node[anchor = east]{\tikzdaytext};
\draw node[anchor = west, gray]{\StrLeft{\pgfcalendarweekdayshortname{\pgfcalendarcurrentweekday}}{1}};
},
execute after day scope={
\ifdate{Sunday}{\pgftransformyshift{1em}}{}},
]
if(weekend) [shape=coordinate]; % (1)
\end{tikzpicture}
\end{document}
```
[](https://i.stack.imgur.com/v1aNP.png) |
40,886,904 | I've tried to build <https://github.com/DEVSENSE/Phalanger>, but after the build process it shows build errors. I tried VS 2015, maybe there it just a question of a wrong version?
[](https://i.stack.imgur.com/Q6qXv.png) | 2016/11/30 | [
"https://Stackoverflow.com/questions/40886904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3941733/"
] | No. They are completely different.
`test in [1,2,3]` checks if there is a property **named** `2` in the object. There is, it has the value `3`.
`[1,2,3].indexOf(test)` gets the first property with the **value** `2` (which is in the property named `1`)
>
> suggest that you can't do in on an array, only on an object
>
>
>
Arrays are objects. (A subclass if we want to use classical OO terminally, which doesn't really fit for a prototypal language like JS, but it gets the point across).
The array `[1, 2, 3]` is *like* an object `{ "0": 1, "1": 2, "2": 3 }` (but inherits a bunch of other properties from the Array constructor). | The first checks for an index, or if property of an object exists,
```
console.log(test in [1,2,3]);
```
and not for a value in the array, as the second is doing.
```
console.log([1,2,3].indexOf(test) != -1);
``` |
40,886,904 | I've tried to build <https://github.com/DEVSENSE/Phalanger>, but after the build process it shows build errors. I tried VS 2015, maybe there it just a question of a wrong version?
[](https://i.stack.imgur.com/Q6qXv.png) | 2016/11/30 | [
"https://Stackoverflow.com/questions/40886904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3941733/"
] | The first checks for an index, or if property of an object exists,
```
console.log(test in [1,2,3]);
```
and not for a value in the array, as the second is doing.
```
console.log([1,2,3].indexOf(test) != -1);
``` | Try this
```
var test = 2;
var arrval= [1, 5, 2, 4];
var a = arrval.indexOf(test);
if(a>-1) console.log("Having");
else console.log("Not Having");
``` |
40,886,904 | I've tried to build <https://github.com/DEVSENSE/Phalanger>, but after the build process it shows build errors. I tried VS 2015, maybe there it just a question of a wrong version?
[](https://i.stack.imgur.com/Q6qXv.png) | 2016/11/30 | [
"https://Stackoverflow.com/questions/40886904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3941733/"
] | No. They are completely different.
`test in [1,2,3]` checks if there is a property **named** `2` in the object. There is, it has the value `3`.
`[1,2,3].indexOf(test)` gets the first property with the **value** `2` (which is in the property named `1`)
>
> suggest that you can't do in on an array, only on an object
>
>
>
Arrays are objects. (A subclass if we want to use classical OO terminally, which doesn't really fit for a prototypal language like JS, but it gets the point across).
The array `[1, 2, 3]` is *like* an object `{ "0": 1, "1": 2, "2": 3 }` (but inherits a bunch of other properties from the Array constructor). | As per [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in),
>
> The in operator returns true if the specified property is in the specified object.
>
>
>
`in` will check for keys. Its similar to `Object.keys(array).indexOf(test)`
```js
var a1 = [1,2,3];
var a2 = ['a', 'b', 'c']
var test = 2;
console.log(test in a1)
console.log(test in a2)
// Ideal way
//ES5
console.log(a1.indexOf(test)>-1)
console.log(a2.indexOf(test)>-1)
//ES6
console.log(a1.includes(test))
console.log(a2.includes(test))
``` |
40,886,904 | I've tried to build <https://github.com/DEVSENSE/Phalanger>, but after the build process it shows build errors. I tried VS 2015, maybe there it just a question of a wrong version?
[](https://i.stack.imgur.com/Q6qXv.png) | 2016/11/30 | [
"https://Stackoverflow.com/questions/40886904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3941733/"
] | No. They are completely different.
`test in [1,2,3]` checks if there is a property **named** `2` in the object. There is, it has the value `3`.
`[1,2,3].indexOf(test)` gets the first property with the **value** `2` (which is in the property named `1`)
>
> suggest that you can't do in on an array, only on an object
>
>
>
Arrays are objects. (A subclass if we want to use classical OO terminally, which doesn't really fit for a prototypal language like JS, but it gets the point across).
The array `[1, 2, 3]` is *like* an object `{ "0": 1, "1": 2, "2": 3 }` (but inherits a bunch of other properties from the Array constructor). | Try this
```
var test = 2;
var arrval= [1, 5, 2, 4];
var a = arrval.indexOf(test);
if(a>-1) console.log("Having");
else console.log("Not Having");
``` |
40,886,904 | I've tried to build <https://github.com/DEVSENSE/Phalanger>, but after the build process it shows build errors. I tried VS 2015, maybe there it just a question of a wrong version?
[](https://i.stack.imgur.com/Q6qXv.png) | 2016/11/30 | [
"https://Stackoverflow.com/questions/40886904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3941733/"
] | No. They are completely different.
`test in [1,2,3]` checks if there is a property **named** `2` in the object. There is, it has the value `3`.
`[1,2,3].indexOf(test)` gets the first property with the **value** `2` (which is in the property named `1`)
>
> suggest that you can't do in on an array, only on an object
>
>
>
Arrays are objects. (A subclass if we want to use classical OO terminally, which doesn't really fit for a prototypal language like JS, but it gets the point across).
The array `[1, 2, 3]` is *like* an object `{ "0": 1, "1": 2, "2": 3 }` (but inherits a bunch of other properties from the Array constructor). | >
> The [**in operator**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in) returns true if the specified property is in the
> specified object.
>
>
>
Using `in` operator for an array checks of the `indices` and the `length` property - because those are the properties for an array:
```js
console.log(Object.getOwnPropertyNames([1, 2, 3]));
console.log(Object.keys([1, 2, 3]));
console.log('length' in [1, 2, 3]);
```
`Object.keys` : return all enumerable properties
`Object.getOwnPropertyNames` : return all properties |
40,886,904 | I've tried to build <https://github.com/DEVSENSE/Phalanger>, but after the build process it shows build errors. I tried VS 2015, maybe there it just a question of a wrong version?
[](https://i.stack.imgur.com/Q6qXv.png) | 2016/11/30 | [
"https://Stackoverflow.com/questions/40886904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3941733/"
] | As per [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in),
>
> The in operator returns true if the specified property is in the specified object.
>
>
>
`in` will check for keys. Its similar to `Object.keys(array).indexOf(test)`
```js
var a1 = [1,2,3];
var a2 = ['a', 'b', 'c']
var test = 2;
console.log(test in a1)
console.log(test in a2)
// Ideal way
//ES5
console.log(a1.indexOf(test)>-1)
console.log(a2.indexOf(test)>-1)
//ES6
console.log(a1.includes(test))
console.log(a2.includes(test))
``` | Try this
```
var test = 2;
var arrval= [1, 5, 2, 4];
var a = arrval.indexOf(test);
if(a>-1) console.log("Having");
else console.log("Not Having");
``` |
40,886,904 | I've tried to build <https://github.com/DEVSENSE/Phalanger>, but after the build process it shows build errors. I tried VS 2015, maybe there it just a question of a wrong version?
[](https://i.stack.imgur.com/Q6qXv.png) | 2016/11/30 | [
"https://Stackoverflow.com/questions/40886904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3941733/"
] | >
> The [**in operator**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in) returns true if the specified property is in the
> specified object.
>
>
>
Using `in` operator for an array checks of the `indices` and the `length` property - because those are the properties for an array:
```js
console.log(Object.getOwnPropertyNames([1, 2, 3]));
console.log(Object.keys([1, 2, 3]));
console.log('length' in [1, 2, 3]);
```
`Object.keys` : return all enumerable properties
`Object.getOwnPropertyNames` : return all properties | Try this
```
var test = 2;
var arrval= [1, 5, 2, 4];
var a = arrval.indexOf(test);
if(a>-1) console.log("Having");
else console.log("Not Having");
``` |
35,254,997 | How to implement a button above the keyboard? (For example: "Notes" app, or
[like this](http://i.stack.imgur.com/hrLlq.gif) | 2016/02/07 | [
"https://Stackoverflow.com/questions/35254997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4478196/"
] | MKaro's solution works! I'll attach the Swift 3 version for faster copy-paste.
**Swift 3:**
```
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
keyboardToolbar.isTranslucent = false
keyboardToolbar.barTintColor = UIColor.white
let addButton = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(someFunction)
)
addButton.tintColor = UIColor.black
keyboardToolbar.items = [addButton]
textView.inputAccessoryView = keyboardToolbar
``` | Its simple, all you need is to use UIToolBar and UIBarButtonItem.
Here is a simple example, that make "Special Keyboard" for specific TextField:
This code create the toolbar:
```
UIToolbar *keyboardToolbar = [[UIToolbar alloc] init];
[keyboardToolbar sizeToFit];
keyboardToolbar.translucent=NO; //if you want it.
keyboardToolbar.barTintColor = Some Color; //the color of the toolbar
```
this code create the button that you want
```
UIBarButtonItem *doneBarButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self.view action:@selector(set your own function here:)];
[doneBarButton setImage:CHOOSE YOUR IMAGE];
keyboardToolbar.items = @[doneBarButton];//you can add couple of buttons if you want to.
yourtextfield.inputAccessoryView = keyboardToolbar;
``` |
72,144,828 | ```
class Dashboard extends Component {
constructor(props) {
super(props)
this.state = {
assetList: [],
assetList1: [];
}
}
componentDidMount = async () => {
const web3 = window.web3
const LandData=Land.networks[networkId]
if (LandData) {
const landList = new web3.eth.Contract(Land.abi, LandData.address)
this.setState({ landList })
}
}
...
}
```
In this code the state for `landlist` is not defines in `constructor` but `setState` is used. If I have to convert the code to a function component, what will be the equivalent code? | 2022/05/06 | [
"https://Stackoverflow.com/questions/72144828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19055006/"
] | In React class components, there existed a single `state` object and you could update it with any properties you needed. State in React function components functions a little differently.
React function components use the `useState` hook to explicitly declare a state variable and updater function.
You can use a single state, and in this case the functionality would be pretty similar, keeping in mind though that unlike the `this.setState` of class components, the `useState`
Example:
```
const Dashboard = () => {
const [state, setState] = React.useState({
assetList: [],
assetList1: []
});
useEffect(() => {
const web3 = window.web3;
const LandData = Land.networks[networkId];
if (LandData) {
const landList = new web3.eth.Contract(Land.abi, LandData.address);
setState(prevState => ({
...prevState,
landList,
}));
}
}, []);
return (
...
);
};
```
With the `useState` hook, however, you aren't limited to a single state object, you can declare as many state variables necessary for your code to function properly. In fact it is recommended to split your state out into the discrete chunks of related state.
Example:
```
const Dashboard = () => {
const [assetLists, setAssetLists] = React.useState({
assetList: [],
assetList1: []
});
const [landList, setLandList] = React.useState([]);
useEffect(() => {
const web3 = window.web3;
const LandData = Land.networks[networkId];
if (LandData) {
const landList = new web3.eth.Contract(Land.abi, LandData.address);
setLandList(landList);
}
}, []);
return (
...
);
};
``` | ```
const Dashboard = () => {
const [assetList, setAssetList] = useState([])
const [assetList1, setAssetList1] = useState([])
useEffect(() => {
const web3 = window.web3
const LandData = Land.networks[networkId]
if (LandData) {
const landList = new web3.eth.Contract(Land.abi, LandData.address)
setAssetList(landList)
}
}, [])
``` |
66,386,300 | I am doing below steps , and in the process I am losing the transformed data though I am using cache() on the data .
**STEP -1 : READ DATA FROM CASSANDRA:**
```
data = spark_session.read \
.format('org.apache.spark.sql.cassandra') \
.options(table=table, keyspace=keyspace) \
.load()
data_cached = data.cache()
```
**STEP-2: READ DATA FROM AWS S3 BUCKET LET'S SAY S3\_data\_path**
```
s3_full_df = spark.read.format("parquet").load(S3_data_path)
full_data = s3_full_df .cache()
full_data.show(n=1, truncate=False)
```
**STEP-3: Finding difference between cassandra data from step-1 and s3 parquet file data from step -2**
```
diff_data = data_cached.subtract(full_data)
diff_data_cached = diff_data .cache()
diff_data_cached.count()
```
**STEP-4: writing step-3 data diff\_data\_cached into aws s3 bucket , let's say s3\_diff\_path**
```
diff_data_cached.write.parquet(inc_path)
```
**STEP-5: IMP STEP : overwriting cassandra data from step -1 to aws s3 path S3\_data\_path ( in STEP-2)**
```
data_cached.write.parquet(full_path, mode="overwrite")
```
**STEP -6 : writing diff\_data\_cached in database . This step has issue .**
diff\_data\_cached is available in STEP-3 is written to data base but after STEP-5 diff\_data\_cached is empty , My assumption is as in STEP-5 , data is overwritten with STEP-1 data and hence there is no difference between two data-frames, but since I have run cache() operation on diff\_data\_cached and then have run count() to load data in memory so my expectation is diff\_data\_cached should be available in memory for STEP-6 , rather than spark lazily evaluates. | 2021/02/26 | [
"https://Stackoverflow.com/questions/66386300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8236029/"
] | **1. General approach: You can create a matrix in base R:**
```
## vectors with same length
obs_date <- c(1,2,3,1,2)
yields <- c(0.05,0.06,0.01,0.02,0.04)
maturities <- c(3,3,4,5,3)
# creating matrix
m <- matrix(c(obs_date, yields, maturities), ncol = 3)
# print matrix
print(m)
# print class of m
class(m)
```
**2. How to create a matrix with vectors of different length:**
```
## vectors of different length
obs_date_1 <- c(1,2,3,1)
yields_1 <- c(0.05,0.06,0.01,0.02,0.04)
maturities_1 <- c(3,3,4)
# create a list of vectors
listofvectors <- list(obs_date_1, yields_1, maturities_1)
# create the matrix
matrixofdiffvec_length <- sapply(listofvectors, '[', seq(max(sapply(listofvectors, length))))
matrixofdiffvec_length
class(matrixofdiffvec_length)
``` | Try this below code segment. You will need tidyverse package to be installed on your machine.
```
obs_date <- c(1,2,3,1,2)
yields <- c(0.05,0.06,0.01,0.02,0.04)
maturities <- c(3,3,4,5,3)
library(tidyverse)
mat <- tibble(obs_date, yields, maturities)
mat
```
[](https://i.stack.imgur.com/eCsuR.png) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.