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
|
---|---|---|---|---|---|
433,009 | I can't seem to be able to type in a password so that I may acquire access to #apt-get. I'm looking to update my system via terminal, but typing out my password does no good to get me into su, as the spaces stay blank, and what I know is the password won't go through. Has anyone else had this issue? | 2014/03/12 | [
"https://askubuntu.com/questions/433009",
"https://askubuntu.com",
"https://askubuntu.com/users/257348/"
] | In order to set up the `Alt-Gr` key you must go to (setting -> keyboard -> layout settings -> keyboard settings -> then go to the typing tab -> press and hold the Alternative Keyboard Key setting -> move you mouse down to select the key you want to assign `Alt-Gr` to.



 | AltGr sounds like a lot of trouble for only a few symbols. A better choice might be the United States Alternative International keyboard. This one gives a choice of dozens of letters with diacritical marks . The k'bd is just like the standard k'bd except that the `~ ^' and the " are --dead-- keys ( delayed action ) until the next key is pressed.
These are the accent grave, tilde, circumflex and the accent agut. Just these 5 added to all the vowels and many consonants gives dozens of extra characters . If you want to type the apostrophe by it self just hit the space bar. ( Or the quote sign ) I have Ubuntu 12.10 and it works OK. I used the instructions for Ubuntu 14.04 so I had to do some guessing but I finally got it to work.
<http://www.wikihow.com/Change-Keyboard-Layout-in-Ubuntu>
```
ã â ś Ḱ ç ŕ ï ḿ ĝ ĥ â ŝ ó õ------samples
```
the 'and the v = ǘ this u with 2 marks above it ,,, wonder where it is used ? |
433,009 | I can't seem to be able to type in a password so that I may acquire access to #apt-get. I'm looking to update my system via terminal, but typing out my password does no good to get me into su, as the spaces stay blank, and what I know is the password won't go through. Has anyone else had this issue? | 2014/03/12 | [
"https://askubuntu.com/questions/433009",
"https://askubuntu.com",
"https://askubuntu.com/users/257348/"
] | This answer has screenshots for Gnome-Shell (Ubuntu Gnome 13.10). I suppose it will be similar for standard Unity, but if not, please chime in.
First of all (and this is the most common problem), **to have AltGr working you need a keyboard layout which uses it**. For example, this is my keyboard layout (Settings -> Region and Language):
[](https://i.stack.imgur.com/zE3UR.png)
* English (US, international with dead keys) has AltGr.
* English (US) has NO AltGr.
* English (international AltGr dead keys) has AltGr.
(My preferred layout is the third one, really).
If the layout does not map AltGr+Key to anything, like for example the default "English (US)", AltGr **will not work** even if it's activated in the Keyboard -> Shortcuts panel.
This is normally sufficient. To change the position of the AltGr you go to Settings -> Keyboard and set the "Alternative Characters Key":
[](https://i.stack.imgur.com/QNOB1.png)
For example, my keyboard has no physical AltGr key, so I mapped it to the Right Alt key.
Now with the third layout, pressing `AltGr` and `n` **together** gives ñ.
[Compose](https://help.ubuntu.com/community/ComposeKey) (the option before) is a very different beast. If you enable it, then you will have a set of characters available with three (or more) keystrokes. For example, pressing `Compose`, `o`, `e` gives œ. That's three sequential keystrokes, not together.
Take into account that there is a [bug related to the layout switching](https://bugs.launchpad.net/ubuntu/+source/gnome-settings-daemon/+bug/1218322) in 13.10 which is being worked on, so check it if you have problems changing layout. | AltGr sounds like a lot of trouble for only a few symbols. A better choice might be the United States Alternative International keyboard. This one gives a choice of dozens of letters with diacritical marks . The k'bd is just like the standard k'bd except that the `~ ^' and the " are --dead-- keys ( delayed action ) until the next key is pressed.
These are the accent grave, tilde, circumflex and the accent agut. Just these 5 added to all the vowels and many consonants gives dozens of extra characters . If you want to type the apostrophe by it self just hit the space bar. ( Or the quote sign ) I have Ubuntu 12.10 and it works OK. I used the instructions for Ubuntu 14.04 so I had to do some guessing but I finally got it to work.
<http://www.wikihow.com/Change-Keyboard-Layout-in-Ubuntu>
```
ã â ś Ḱ ç ŕ ï ḿ ĝ ĥ â ŝ ó õ------samples
```
the 'and the v = ǘ this u with 2 marks above it ,,, wonder where it is used ? |
33,610,111 | I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized
It refers to a `cmd.ExecuteNonQuery();`
I'm not really sure what is going on, maybe the insert is not correct, but here is my code:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace md2
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void button2_Click(object sender, EventArgs e)
{
if (izd_adr.Text != "" && izd_nos.Text != "") {
cn.Open();
cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Ir pievienots");
cn.Close();
new Form1().Show();
}
}
}
}
```
I followed a tutorial in how to do this, but I'm getting this error.
That Database looks like this: [](https://i.stack.imgur.com/pqLFv.png)
This seems like a easy mistake somewhere, but is really frustrating... | 2015/11/09 | [
"https://Stackoverflow.com/questions/33610111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816142/"
] | 1: Use an IntentService to do your downloads.
<http://developer.android.com/reference/android/app/IntentService.html>
2: Set up your IntentService using AlarmManager so that it runs even if the
application is not running. You register with the AlarmManager
<http://developer.android.com/reference/android/app/AlarmManager.html>
There are a variety of ways you can have the AlarmManager start your
intent.
For Example:
// Register first run and then interval for repeated cycles.
alarmManager.setInexactRepeating(AlarmManager.ELAPSED\_REALTIME\_WAKEUP,
SystemClock.elapsedRealtime() + DEFAULT\_INITIAL\_RUN,
DEFAULT\_RUN\_INTERVAL, pi);
3: Storing Data
There are several options here depending on how public you want your
pictures/data to be.
<http://developer.android.com/reference/android/os/Environment.html>
Example: External Public Storage
File dirBackup = Environment.getExternalStoragePublicDirectory(
"YourDirectory" );
4: Downloading
Your option here. You can using anything from your current API to a
basic URLConnection.
You may want to look at:
```
http://developer.android.com/reference/android/app/DownloadManager.html
```
Also, watch your permissions you will need to add
and
Hope this points you in a useful direction. | The important things to think about here is
`Thread` , `Service` ,`File` , `Json`, `Context`,`Receiver` & `if else` & `for`
maybe i did not understand your question but this is not a big deal sir,
your programm your app to work in way where your app starts when the os broadcast `onBootCompleted`, then create a `Thread` where you are going to do a lot of code - getting your json file-(when you need it), since its an array you get your `jsonObject` images, whether its a thousand or million you just iterate it and use any approach to download it, i'd say use the traditional way of downloading your images so as you better control it.
With the help of `File` class you save it alongside `Context` you can get your app's cache's directory, which is an internal memory save it there and create a column in your database where you can save the path to the file in your database as String.
When your app start in `onPrepareOptionsMenu()` check if your app's cache's directory is empty-if not you have some files, now since you have every file and its respective path you can check if it exists with `File.exist()` if it does no need to download.
if you need pace you can always create new Threads. The `Reciever` was to be the guy who gets notified when your device boots, if else for a lot of logic checking, `for` for your loopings, Service to be able to do long running work and have a way to communicate between the UI and background thread.
*sorry for the last paragraph i was just trying to buy space :)* |
33,610,111 | I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized
It refers to a `cmd.ExecuteNonQuery();`
I'm not really sure what is going on, maybe the insert is not correct, but here is my code:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace md2
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void button2_Click(object sender, EventArgs e)
{
if (izd_adr.Text != "" && izd_nos.Text != "") {
cn.Open();
cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Ir pievienots");
cn.Close();
new Form1().Show();
}
}
}
}
```
I followed a tutorial in how to do this, but I'm getting this error.
That Database looks like this: [](https://i.stack.imgur.com/pqLFv.png)
This seems like a easy mistake somewhere, but is really frustrating... | 2015/11/09 | [
"https://Stackoverflow.com/questions/33610111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816142/"
] | You should try downloading with this,
```
class DownloadFile extends AsyncTask<String,Integer,Long> {
ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Downloading Image ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
@Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="downloadedimage.jpg";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+"/myImage/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress ((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Download Completed !", Toast.LENGTH_LONG).show();
}
}
protected void onPostExecute(String result) {
}
}
```
This code will let you to download all the url of images,
```
new DownloadFile().execute("https://i.stack.imgur.com/w4kCo.jpg");
```
.....
```
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```
Change Folder Name as you desired and try to set this images to app bitmap and also avoiding rotate error of images by using this. | The important things to think about here is
`Thread` , `Service` ,`File` , `Json`, `Context`,`Receiver` & `if else` & `for`
maybe i did not understand your question but this is not a big deal sir,
your programm your app to work in way where your app starts when the os broadcast `onBootCompleted`, then create a `Thread` where you are going to do a lot of code - getting your json file-(when you need it), since its an array you get your `jsonObject` images, whether its a thousand or million you just iterate it and use any approach to download it, i'd say use the traditional way of downloading your images so as you better control it.
With the help of `File` class you save it alongside `Context` you can get your app's cache's directory, which is an internal memory save it there and create a column in your database where you can save the path to the file in your database as String.
When your app start in `onPrepareOptionsMenu()` check if your app's cache's directory is empty-if not you have some files, now since you have every file and its respective path you can check if it exists with `File.exist()` if it does no need to download.
if you need pace you can always create new Threads. The `Reciever` was to be the guy who gets notified when your device boots, if else for a lot of logic checking, `for` for your loopings, Service to be able to do long running work and have a way to communicate between the UI and background thread.
*sorry for the last paragraph i was just trying to buy space :)* |
33,610,111 | I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized
It refers to a `cmd.ExecuteNonQuery();`
I'm not really sure what is going on, maybe the insert is not correct, but here is my code:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace md2
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void button2_Click(object sender, EventArgs e)
{
if (izd_adr.Text != "" && izd_nos.Text != "") {
cn.Open();
cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Ir pievienots");
cn.Close();
new Form1().Show();
}
}
}
}
```
I followed a tutorial in how to do this, but I'm getting this error.
That Database looks like this: [](https://i.stack.imgur.com/pqLFv.png)
This seems like a easy mistake somewhere, but is really frustrating... | 2015/11/09 | [
"https://Stackoverflow.com/questions/33610111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816142/"
] | Try out this [library](https://github.com/nostra13/Android-Universal-Image-Loader) to manage images loading.
>
> Use a service to download the images. This I feel is mandatory because
> I do not know how many images there will be, and I want the download
> to proceed even if user exits the app
>
>
>
All downloading done in worker threads so it's alive while application process is alive. There may a problem appear: application dies while loading is in progress. To workaround this I suggest to use `AlarmManager` in combination with `Service`. Set it up to start by timer, check you database or UIL cache for image files being not loaded and start their loading again.
>
> Glide has a download only option for images and you can configure
> where its cache is located (internal private or external public) as I
> read here and here. Problem is I do not feel comfortable with setting
> the cache size as I do not know what is required. I would like to set
> unlimited.
>
>
>
UIL has several disc cache implementations out of the box including unlimited one. It also provides you cache interface so you can implement your own.
>
> I need to be able to delete the saved menu data especially if its
> saved on the external public directory as this is not removed when the
> app is deleted etc. or if the user chooses to delete a saved menu from
> within the app. I was thinking I could store the file image URIs or
> location of the entire saved menu in database for this but not sure if
> this is a good way
>
>
>
UIL generates unique filename for each loaded file using provided file link. You can delete any loaded image or cancel any download using link from your JSON.
>
> I read in different sources and answers that in this use case for just
> caching images to SD card etc. that I should specifically use a
> network library to do so to avoid the allocation of a bitmap to heap
> memory. I am using OK HTTP in my app at the moment.
>
>
>
UIL does it OK. It manages memory very accurately also provide you several options for memory management configuration. For example you can choose between several memory cache implementations out of the box.
In conclusion I suggest you to the visit the link above and read library documentation/description by yourself. It's very flexible and contatins lots of useful features. | The important things to think about here is
`Thread` , `Service` ,`File` , `Json`, `Context`,`Receiver` & `if else` & `for`
maybe i did not understand your question but this is not a big deal sir,
your programm your app to work in way where your app starts when the os broadcast `onBootCompleted`, then create a `Thread` where you are going to do a lot of code - getting your json file-(when you need it), since its an array you get your `jsonObject` images, whether its a thousand or million you just iterate it and use any approach to download it, i'd say use the traditional way of downloading your images so as you better control it.
With the help of `File` class you save it alongside `Context` you can get your app's cache's directory, which is an internal memory save it there and create a column in your database where you can save the path to the file in your database as String.
When your app start in `onPrepareOptionsMenu()` check if your app's cache's directory is empty-if not you have some files, now since you have every file and its respective path you can check if it exists with `File.exist()` if it does no need to download.
if you need pace you can always create new Threads. The `Reciever` was to be the guy who gets notified when your device boots, if else for a lot of logic checking, `for` for your loopings, Service to be able to do long running work and have a way to communicate between the UI and background thread.
*sorry for the last paragraph i was just trying to buy space :)* |
33,610,111 | I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized
It refers to a `cmd.ExecuteNonQuery();`
I'm not really sure what is going on, maybe the insert is not correct, but here is my code:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace md2
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void button2_Click(object sender, EventArgs e)
{
if (izd_adr.Text != "" && izd_nos.Text != "") {
cn.Open();
cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Ir pievienots");
cn.Close();
new Form1().Show();
}
}
}
}
```
I followed a tutorial in how to do this, but I'm getting this error.
That Database looks like this: [](https://i.stack.imgur.com/pqLFv.png)
This seems like a easy mistake somewhere, but is really frustrating... | 2015/11/09 | [
"https://Stackoverflow.com/questions/33610111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816142/"
] | Using a service can be a good option if you want the downloads to continue even if the user exits. Images that are stored in directories created using `getExternalStorageDirectory()` are automatically deleted when your app is uninstalled. Moreover you can check if the internal memory is large enough to store images. If you use this methods these images will be deleted upon the uninstallion of the app. | You should try downloading with this,
```
class DownloadFile extends AsyncTask<String,Integer,Long> {
ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Downloading Image ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
@Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="downloadedimage.jpg";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+"/myImage/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress ((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Download Completed !", Toast.LENGTH_LONG).show();
}
}
protected void onPostExecute(String result) {
}
}
```
This code will let you to download all the url of images,
```
new DownloadFile().execute("https://i.stack.imgur.com/w4kCo.jpg");
```
.....
```
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```
Change Folder Name as you desired and try to set this images to app bitmap and also avoiding rotate error of images by using this. |
33,610,111 | I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized
It refers to a `cmd.ExecuteNonQuery();`
I'm not really sure what is going on, maybe the insert is not correct, but here is my code:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace md2
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void button2_Click(object sender, EventArgs e)
{
if (izd_adr.Text != "" && izd_nos.Text != "") {
cn.Open();
cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Ir pievienots");
cn.Close();
new Form1().Show();
}
}
}
}
```
I followed a tutorial in how to do this, but I'm getting this error.
That Database looks like this: [](https://i.stack.imgur.com/pqLFv.png)
This seems like a easy mistake somewhere, but is really frustrating... | 2015/11/09 | [
"https://Stackoverflow.com/questions/33610111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816142/"
] | Try out this [library](https://github.com/nostra13/Android-Universal-Image-Loader) to manage images loading.
>
> Use a service to download the images. This I feel is mandatory because
> I do not know how many images there will be, and I want the download
> to proceed even if user exits the app
>
>
>
All downloading done in worker threads so it's alive while application process is alive. There may a problem appear: application dies while loading is in progress. To workaround this I suggest to use `AlarmManager` in combination with `Service`. Set it up to start by timer, check you database or UIL cache for image files being not loaded and start their loading again.
>
> Glide has a download only option for images and you can configure
> where its cache is located (internal private or external public) as I
> read here and here. Problem is I do not feel comfortable with setting
> the cache size as I do not know what is required. I would like to set
> unlimited.
>
>
>
UIL has several disc cache implementations out of the box including unlimited one. It also provides you cache interface so you can implement your own.
>
> I need to be able to delete the saved menu data especially if its
> saved on the external public directory as this is not removed when the
> app is deleted etc. or if the user chooses to delete a saved menu from
> within the app. I was thinking I could store the file image URIs or
> location of the entire saved menu in database for this but not sure if
> this is a good way
>
>
>
UIL generates unique filename for each loaded file using provided file link. You can delete any loaded image or cancel any download using link from your JSON.
>
> I read in different sources and answers that in this use case for just
> caching images to SD card etc. that I should specifically use a
> network library to do so to avoid the allocation of a bitmap to heap
> memory. I am using OK HTTP in my app at the moment.
>
>
>
UIL does it OK. It manages memory very accurately also provide you several options for memory management configuration. For example you can choose between several memory cache implementations out of the box.
In conclusion I suggest you to the visit the link above and read library documentation/description by yourself. It's very flexible and contatins lots of useful features. | You should try downloading with this,
```
class DownloadFile extends AsyncTask<String,Integer,Long> {
ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Downloading Image ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
@Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="downloadedimage.jpg";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+"/myImage/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress ((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Download Completed !", Toast.LENGTH_LONG).show();
}
}
protected void onPostExecute(String result) {
}
}
```
This code will let you to download all the url of images,
```
new DownloadFile().execute("https://i.stack.imgur.com/w4kCo.jpg");
```
.....
```
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```
Change Folder Name as you desired and try to set this images to app bitmap and also avoiding rotate error of images by using this. |
33,610,111 | I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized
It refers to a `cmd.ExecuteNonQuery();`
I'm not really sure what is going on, maybe the insert is not correct, but here is my code:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace md2
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void button2_Click(object sender, EventArgs e)
{
if (izd_adr.Text != "" && izd_nos.Text != "") {
cn.Open();
cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Ir pievienots");
cn.Close();
new Form1().Show();
}
}
}
}
```
I followed a tutorial in how to do this, but I'm getting this error.
That Database looks like this: [](https://i.stack.imgur.com/pqLFv.png)
This seems like a easy mistake somewhere, but is really frustrating... | 2015/11/09 | [
"https://Stackoverflow.com/questions/33610111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816142/"
] | Using a service can be a good option if you want the downloads to continue even if the user exits. Images that are stored in directories created using `getExternalStorageDirectory()` are automatically deleted when your app is uninstalled. Moreover you can check if the internal memory is large enough to store images. If you use this methods these images will be deleted upon the uninstallion of the app. | The important things to think about here is
`Thread` , `Service` ,`File` , `Json`, `Context`,`Receiver` & `if else` & `for`
maybe i did not understand your question but this is not a big deal sir,
your programm your app to work in way where your app starts when the os broadcast `onBootCompleted`, then create a `Thread` where you are going to do a lot of code - getting your json file-(when you need it), since its an array you get your `jsonObject` images, whether its a thousand or million you just iterate it and use any approach to download it, i'd say use the traditional way of downloading your images so as you better control it.
With the help of `File` class you save it alongside `Context` you can get your app's cache's directory, which is an internal memory save it there and create a column in your database where you can save the path to the file in your database as String.
When your app start in `onPrepareOptionsMenu()` check if your app's cache's directory is empty-if not you have some files, now since you have every file and its respective path you can check if it exists with `File.exist()` if it does no need to download.
if you need pace you can always create new Threads. The `Reciever` was to be the guy who gets notified when your device boots, if else for a lot of logic checking, `for` for your loopings, Service to be able to do long running work and have a way to communicate between the UI and background thread.
*sorry for the last paragraph i was just trying to buy space :)* |
33,610,111 | I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized
It refers to a `cmd.ExecuteNonQuery();`
I'm not really sure what is going on, maybe the insert is not correct, but here is my code:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace md2
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void button2_Click(object sender, EventArgs e)
{
if (izd_adr.Text != "" && izd_nos.Text != "") {
cn.Open();
cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Ir pievienots");
cn.Close();
new Form1().Show();
}
}
}
}
```
I followed a tutorial in how to do this, but I'm getting this error.
That Database looks like this: [](https://i.stack.imgur.com/pqLFv.png)
This seems like a easy mistake somewhere, but is really frustrating... | 2015/11/09 | [
"https://Stackoverflow.com/questions/33610111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816142/"
] | I use this class when downloading images, it caches the images, next time you will be downloading them it will just load from external memory, it manages the cache for you as well so you wont have to worry about setting cache to limited or unlimited, pretty efficient and fast.
```
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.placeholder;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Recommended Size 512
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
```
}
To use it Just create an instance of it like
```
ImageLoader Imageloaer = new ImageLoader(getBaseContext());
Imageloaer.DisplayImage(imageUrl, imageView);
``` | You should try downloading with this,
```
class DownloadFile extends AsyncTask<String,Integer,Long> {
ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Downloading Image ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
@Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="downloadedimage.jpg";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+"/myImage/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress ((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Download Completed !", Toast.LENGTH_LONG).show();
}
}
protected void onPostExecute(String result) {
}
}
```
This code will let you to download all the url of images,
```
new DownloadFile().execute("https://i.stack.imgur.com/w4kCo.jpg");
```
.....
```
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```
Change Folder Name as you desired and try to set this images to app bitmap and also avoiding rotate error of images by using this. |
33,610,111 | I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized
It refers to a `cmd.ExecuteNonQuery();`
I'm not really sure what is going on, maybe the insert is not correct, but here is my code:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace md2
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void button2_Click(object sender, EventArgs e)
{
if (izd_adr.Text != "" && izd_nos.Text != "") {
cn.Open();
cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Ir pievienots");
cn.Close();
new Form1().Show();
}
}
}
}
```
I followed a tutorial in how to do this, but I'm getting this error.
That Database looks like this: [](https://i.stack.imgur.com/pqLFv.png)
This seems like a easy mistake somewhere, but is really frustrating... | 2015/11/09 | [
"https://Stackoverflow.com/questions/33610111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816142/"
] | I'm using ormlite to store objects with urls too, I have a synchronization after the "sign in" screen on my app, on my experience I really recommend this library <https://github.com/thest1/LazyList>
It's very simple:
```
ImageLoader imageLoader=new ImageLoader(context);
imageLoader.DisplayImage(url, imageView);
```
This library saves the image using the url on the external sd with basic and simple configuration about the memory issues, so if you actually have two or more items with the same url this library works perfectly, the url and imageView are the parameters, if the image is not on the phone begins a new task and put the image in the view when the download is finish, and btw this library also saves the images encoded, so these pictures don't appear on the gallery.
Actually you only need these files to implement the library:<https://github.com/thest1/LazyList/tree/master/src/com/fedorvlasov/lazylist>
If you wanna manipulate some files, you can change the folder name in the FileCache class:
```
public FileCache(Context context){
//Find the dir to save cached images
...
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
...
}
```
Where "LazyList" is the folder name, and them you can delete, move, etc.
Delete sample:
```
/**
* This method delete a file if exist
*/
public static void deleteFile(File file){
if(file!=null && file.exists()) {
file.delete();
}
}
```
Now I learned more about memory cache and the allocation of a bitmap to heap memory, for the first time manipulating images online and offline, I recommend this library, also when you learn more about it, you can implement and edit the library to your needs. | You should try downloading with this,
```
class DownloadFile extends AsyncTask<String,Integer,Long> {
ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Downloading Image ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
@Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="downloadedimage.jpg";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+"/myImage/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress ((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Download Completed !", Toast.LENGTH_LONG).show();
}
}
protected void onPostExecute(String result) {
}
}
```
This code will let you to download all the url of images,
```
new DownloadFile().execute("https://i.stack.imgur.com/w4kCo.jpg");
```
.....
```
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```
Change Folder Name as you desired and try to set this images to app bitmap and also avoiding rotate error of images by using this. |
33,610,111 | I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized
It refers to a `cmd.ExecuteNonQuery();`
I'm not really sure what is going on, maybe the insert is not correct, but here is my code:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace md2
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void button2_Click(object sender, EventArgs e)
{
if (izd_adr.Text != "" && izd_nos.Text != "") {
cn.Open();
cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Ir pievienots");
cn.Close();
new Form1().Show();
}
}
}
}
```
I followed a tutorial in how to do this, but I'm getting this error.
That Database looks like this: [](https://i.stack.imgur.com/pqLFv.png)
This seems like a easy mistake somewhere, but is really frustrating... | 2015/11/09 | [
"https://Stackoverflow.com/questions/33610111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816142/"
] | 1: Use an IntentService to do your downloads.
<http://developer.android.com/reference/android/app/IntentService.html>
2: Set up your IntentService using AlarmManager so that it runs even if the
application is not running. You register with the AlarmManager
<http://developer.android.com/reference/android/app/AlarmManager.html>
There are a variety of ways you can have the AlarmManager start your
intent.
For Example:
// Register first run and then interval for repeated cycles.
alarmManager.setInexactRepeating(AlarmManager.ELAPSED\_REALTIME\_WAKEUP,
SystemClock.elapsedRealtime() + DEFAULT\_INITIAL\_RUN,
DEFAULT\_RUN\_INTERVAL, pi);
3: Storing Data
There are several options here depending on how public you want your
pictures/data to be.
<http://developer.android.com/reference/android/os/Environment.html>
Example: External Public Storage
File dirBackup = Environment.getExternalStoragePublicDirectory(
"YourDirectory" );
4: Downloading
Your option here. You can using anything from your current API to a
basic URLConnection.
You may want to look at:
```
http://developer.android.com/reference/android/app/DownloadManager.html
```
Also, watch your permissions you will need to add
and
Hope this points you in a useful direction. | You should try downloading with this,
```
class DownloadFile extends AsyncTask<String,Integer,Long> {
ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);// Change Mainactivity.this with your activity name.
String strFolderName;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Downloading Image ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
}
@Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="downloadedimage.jpg";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+"/myImage/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress ((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Download Completed !", Toast.LENGTH_LONG).show();
}
}
protected void onPostExecute(String result) {
}
}
```
This code will let you to download all the url of images,
```
new DownloadFile().execute("https://i.stack.imgur.com/w4kCo.jpg");
```
.....
```
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```
Change Folder Name as you desired and try to set this images to app bitmap and also avoiding rotate error of images by using this. |
33,610,111 | I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized
It refers to a `cmd.ExecuteNonQuery();`
I'm not really sure what is going on, maybe the insert is not correct, but here is my code:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace md2
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void button2_Click(object sender, EventArgs e)
{
if (izd_adr.Text != "" && izd_nos.Text != "") {
cn.Open();
cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Ir pievienots");
cn.Close();
new Form1().Show();
}
}
}
}
```
I followed a tutorial in how to do this, but I'm getting this error.
That Database looks like this: [](https://i.stack.imgur.com/pqLFv.png)
This seems like a easy mistake somewhere, but is really frustrating... | 2015/11/09 | [
"https://Stackoverflow.com/questions/33610111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816142/"
] | I use this class when downloading images, it caches the images, next time you will be downloading them it will just load from external memory, it manages the cache for you as well so you wont have to worry about setting cache to limited or unlimited, pretty efficient and fast.
```
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.placeholder;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Recommended Size 512
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
```
}
To use it Just create an instance of it like
```
ImageLoader Imageloaer = new ImageLoader(getBaseContext());
Imageloaer.DisplayImage(imageUrl, imageView);
``` | The important things to think about here is
`Thread` , `Service` ,`File` , `Json`, `Context`,`Receiver` & `if else` & `for`
maybe i did not understand your question but this is not a big deal sir,
your programm your app to work in way where your app starts when the os broadcast `onBootCompleted`, then create a `Thread` where you are going to do a lot of code - getting your json file-(when you need it), since its an array you get your `jsonObject` images, whether its a thousand or million you just iterate it and use any approach to download it, i'd say use the traditional way of downloading your images so as you better control it.
With the help of `File` class you save it alongside `Context` you can get your app's cache's directory, which is an internal memory save it there and create a column in your database where you can save the path to the file in your database as String.
When your app start in `onPrepareOptionsMenu()` check if your app's cache's directory is empty-if not you have some files, now since you have every file and its respective path you can check if it exists with `File.exist()` if it does no need to download.
if you need pace you can always create new Threads. The `Reciever` was to be the guy who gets notified when your device boots, if else for a lot of logic checking, `for` for your loopings, Service to be able to do long running work and have a way to communicate between the UI and background thread.
*sorry for the last paragraph i was just trying to buy space :)* |
36,252,233 | I made One Class for executing hibernate select operations my code is
working fine but i just need some help
I am passing hibernate select query from some other class to get the
result if my select query contains more than one column than I call the
method getListbylimit(String query,int limit) its returns
List but when my select query column contains only one than it
gives exception java.lang.String cannot be cast to
`[Ljava.lang.Object;`
for that I made second method List
getListForSingleColumn(String query) to get the result for single
column
is there any way to write method for this so that I can call only
one method. Rather my select query contain one column or more than one columns.
can I get return type `List<Object[]>` if I select only one column instead of `List<String>` so that I can use only one method for select operation
Here is my code
```
public class ContentDomain {
Session session;
public List<Object[]> getListbylimit(String query,int limit){
session = HibernateUtil.getSessionFactory().getCurrentSession();
/* session = HibernateUtil.getSessionFactory().openSession();
*/
List<Object[]> ls_ob = new ArrayList<Object[]>();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q = session.createQuery(query);
q.setMaxResults(limit);
ls_ob = (List<Object[]>)q.list();
}catch (HibernateException ex) {
if (tx != null) {
System.out.println("Exception in getList method " + ex);
tx.rollback();
ex.printStackTrace();
}
System.out.println("Exception getList tx open" + ex);
} finally {
session.close();
}
return ls_ob;
}
public List<String> getListForSingleColumn(String query){
session = HibernateUtil.getSessionFactory().getCurrentSession();
/* session = HibernateUtil.getSessionFactory().openSession();*/
List<String> ls_ob = new ArrayList<String>();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q = session.createQuery(query);
ls_ob = q.list();
}catch (HibernateException ex) {
if (tx != null) {
System.out.println("Exception in getList method " + ex);
tx.rollback();
ex.printStackTrace();
}
System.out.println("Exception getList tx open" + ex);
} finally {
session.close();
}
return ls_ob;
}
}
``` | 2016/03/27 | [
"https://Stackoverflow.com/questions/36252233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5194837/"
] | Here is a general implementation using a helper class for finding the lowest X integers.
With three columns, three instances of the helper class is created, and the data is then iterated to collect the 3 lowest values for each column.
The advantages of this code are:
* Only retains the lowest X values
* Does not need to box the integers
* Uses binary search for improved performance of higher values of X
This means it should be fast and have a low memory footprint, supporting unlimited amounts of data (if streamed).
See [IDEONE](https://ideone.com/v0CCri) for demo.
```
import java.util.Arrays;
class Ideone {
private static final int MIN_COUNT = 3;
public static void main(String[] args) {
int[][] data = { { 74, 85, 123 },
{ 73, 84, 122 },
{ 72, 83, 121 },
{ 70, 81, 119 },
{ 69, 80, 118 },
{ 76, 87, 125 },
{ 77, 88, 126 },
{ 78, 89, 127 } };
// Initialize min collectors
Min[] min = new Min[data[0].length];
for (int col = 0; col < min.length; col++)
min[col] = new Min(MIN_COUNT);
// Collect data
for (int row = 0; row < data.length; row++)
for (int col = 0; col < min.length; col++)
min[col].add(data[row][col]);
// Print result
for (int i = 0; i < MIN_COUNT; i++) {
for (int col = 0; col < min.length; col++)
System.out.printf("min%d = %-5d ", i + 1, min[col].get(i));
System.out.println();
}
}
}
class Min {
private int[] min;
public Min(int count) {
this.min = new int[count];
Arrays.fill(this.min, Integer.MAX_VALUE);
}
public void add(int value) {
int idx = Arrays.binarySearch(this.min, value);
if (idx != -this.min.length - 1) { // not insert at end
if (idx < 0)
idx = -idx - 1;
System.arraycopy(this.min, idx, this.min, idx + 1, this.min.length - idx - 1);
this.min[idx] = value;
}
}
public int get(int index) {
return this.min[index];
}
}
``` | Say your data has N rows and M columns
1. Iterate over each column
2. Add all the elements in the column into a minHeap ( min priority queue)
3. Retrieve the first 3 numbers from the minHeap (these will be the 3 mins)
4. Clear the queue and move onto the next column
O(n) space, O(M*N*lg(N)) time |
44,426,498 | When i setup static resources like js,css,templates on my web server, i forget to set cache period for them. by default web server set it "cache forever" (this is tomcat server and spring mvc)
```
<mvc:resources mapping="/resources/**" location="/resources/" />
```
if dont specify `cache-period` then server will send headers like "cache it forever".
now i try different ways to solve this:
1. try to change static resource url
```
mvc:resources mapping="/static/**" location="/resources/" cache-period="10800"
```
but this does not help(i think that browser cache the whole html page, but it does not)
2. i try to force reloading page using JS:
location.reload(true)
but this does not help much to
how can i force browser to reload cached files?
P.S. i dont send any cache headers to cache my html pages | 2017/06/08 | [
"https://Stackoverflow.com/questions/44426498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4760059/"
] | You can append a version number to the URL
```
http://mydomin.com/resources/file.css?version=1
```
For example;
```
<html>
<head>
<link href="resources/file.css?version=1" type="text/css" rel="stylesheet"/>
<head>
<body></body>
</html>
``` | I know you do not have jQuery or Ajax tagged in this, but the easiest way to reload your .js files is to use the jQuery getScript() function, which is just a shortcut way of doing an ajax http request.
```
$.getScript('../path_or_URL_to_your_js_file.js');
```
This loads the external resource with a timestamp appended to it so it will load from the server instead of cache by default. You just need to be sure your jquery is included before you call the getScript function.
To preventing cached versions of your .css files, you can use jQuery/ajax to build the link elements dynamically in the head of your html after the page is loaded, which will prevent loading a cached resource.
```
$('<link/>', {
rel: 'stylesheet',
type: 'text/css',
href: 'path_to_the.css'
}).appendTo('head');
``` |
27,450,369 | I have the following homework assignment:
>
> Add a new method `retrieveAt` for the class `IntSLList` that takes an integer index position as a parameter.
>
>
> The method returns the info inside the node at the index position. The index of the first node is 0. If the list is empty or the index is invalid, then display an error message.
>
>
>
I have implemented a solution using the following code:
```java
public int retrieveAt(int pos){
IntSLLNode tmp;
int count = 0;
int c;
for(tmp = head; tmp != null; tmp = tmp.next){
count++;
}
if(isEmpty()|| count<pos){
return 0;
} else {
IntSLLNode tmp1 = head;
for(int i = 1; i < pos; i++){
if(tmp1.next == null)
return 0;
tmp1 = tmp1.next;
}
return tmp1.info;
}
}
```
It appears to traverse the list properly, but it does not retrieve the correct element.
An example case where this does not appear to give the correct output:
```java
IntSLList myn = new IntSLList();
myn.addToHead(10);
myn.addToHead(20);
myn.addToHead(30);
myn.addToHead(40);
myn.addToTail(60);
myn.printAll();
int x = myn.retrieveAt(4);
if(x == 0)
System.out.println("NOT VALID ");
else
System.out.println("elm : " + x);
```
The output is:
```
40
30
20
10
60
elm : 10
``` | 2014/12/12 | [
"https://Stackoverflow.com/questions/27450369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4238558/"
] | `Received:` headers are timestamped:
```
Received: from lb-ex1.int.icgroup.com (localhost [127.0.0.1])
by lb-ex1.localdomain (Postfix) with ESMTP id D6BDB1E26393
for <[email protected]>; Fri, 12 Dec 2014 12:09:24 -0500 (EST)
```
So, do `messageInstance.get_all()` and [sort](https://wiki.python.org/moin/HowTo/Sorting) the resulting list however you see fit, an example of how to do this:
```
import email.utils
import operator
def sort_key(received_header):
received_date = email.utils.parsedate_tz(received_header)
return received_date
received_header_list.sort(key=sort_key)
```
If it doesn't work, do leave a comment and I'll be happy to look into it further. | The `email.parser` class `HeaderParser` implements a dictionary-like interface, but actually seems to return the headers in the order you expect.
```
from email.parser import HeaderParser
headers = HeaderParser().parse(open_filehandle, headersonly=True)
for key, value in headers.items():
if key == 'Received':
... do things with the value
```
The [`parse` method](https://docs.python.org/2/library/email.parser.html#email.parser.Parser.parse) has a sister [`parsestr` method](https://docs.python.org/2/library/email.parser.html#email.parser.Parser.parsestr) which accepts a byte string instead of a file-like object.
If by "final" you mean the "newest", that will be the first one which matches the `if` so you can simply `break` after reading it. If by "final" you mean something else, you can implement that inside the `if` in whatever way you see fit.
This is adapted from [this answer to a related question](https://stackoverflow.com/questions/8424317/extract-just-email-headers-in-python). |
27,450,369 | I have the following homework assignment:
>
> Add a new method `retrieveAt` for the class `IntSLList` that takes an integer index position as a parameter.
>
>
> The method returns the info inside the node at the index position. The index of the first node is 0. If the list is empty or the index is invalid, then display an error message.
>
>
>
I have implemented a solution using the following code:
```java
public int retrieveAt(int pos){
IntSLLNode tmp;
int count = 0;
int c;
for(tmp = head; tmp != null; tmp = tmp.next){
count++;
}
if(isEmpty()|| count<pos){
return 0;
} else {
IntSLLNode tmp1 = head;
for(int i = 1; i < pos; i++){
if(tmp1.next == null)
return 0;
tmp1 = tmp1.next;
}
return tmp1.info;
}
}
```
It appears to traverse the list properly, but it does not retrieve the correct element.
An example case where this does not appear to give the correct output:
```java
IntSLList myn = new IntSLList();
myn.addToHead(10);
myn.addToHead(20);
myn.addToHead(30);
myn.addToHead(40);
myn.addToTail(60);
myn.printAll();
int x = myn.retrieveAt(4);
if(x == 0)
System.out.println("NOT VALID ");
else
System.out.println("elm : " + x);
```
The output is:
```
40
30
20
10
60
elm : 10
``` | 2014/12/12 | [
"https://Stackoverflow.com/questions/27450369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4238558/"
] | In python 3.6.7, the comments on the get\_all() method explicity state that the values are returned in the same order as they are in the message, so `messageInstance.get_all('Received')` should work fine.
```
def get_all(self, name, failobj=None):
"""Return a list of all the values for the named field.
These will be sorted in the order they appeared in the original
message, and may contain duplicates. Any fields deleted and
re-inserted are always appended to the header list.
If no such fields exist, failobj is returned (defaults to None).
"""
``` | The `email.parser` class `HeaderParser` implements a dictionary-like interface, but actually seems to return the headers in the order you expect.
```
from email.parser import HeaderParser
headers = HeaderParser().parse(open_filehandle, headersonly=True)
for key, value in headers.items():
if key == 'Received':
... do things with the value
```
The [`parse` method](https://docs.python.org/2/library/email.parser.html#email.parser.Parser.parse) has a sister [`parsestr` method](https://docs.python.org/2/library/email.parser.html#email.parser.Parser.parsestr) which accepts a byte string instead of a file-like object.
If by "final" you mean the "newest", that will be the first one which matches the `if` so you can simply `break` after reading it. If by "final" you mean something else, you can implement that inside the `if` in whatever way you see fit.
This is adapted from [this answer to a related question](https://stackoverflow.com/questions/8424317/extract-just-email-headers-in-python). |
30,251,819 | I am developing a project using primefaces.
**Code:**
```
<p:panel id="accountPolicyRichPanel">
<h:panelGrid id="outputPanelGrid">
<h:outputText value=""...../>
<p:inputText id="InputTextId"/>
<p:selectOneMenu id="suspendTypeId" value="...">
<f:selectItems value="#{AccountPolicy.suspendTypeItemList}"/>
<p:ajax listener="#AccountPolicy.suspendTypeComboboxAction}"event="change" update="outputPanelGrid"/>
</p:selectOneMenu>
</panelGrid>
<p:commandButton id="saveButtonId" value="..." action="..."
update="accountPolicyRichPanel" />
</p:panel>
```
My issue is when i select the `<p:selectOneMenu>` I upadte the `<h:panelGrid id="outputPanelGrid">` at the time my previous entered value in `<p:inputText id="InputTextId"/>` is removed.
How to update the `<h:panelGrid id="outputPanelGrid">` or `<p:panel>` without remove the previous entered value in `p:inputText`. | 2015/05/15 | [
"https://Stackoverflow.com/questions/30251819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4513434/"
] | You have a problem and you want to use multi-threading to solve it. Now you have two problems. :)
First of all you have to look at a way to decompose your problem into something that can be done in parallel. The way you have decomposed your problem right now is inherently sequential. There is no advantage to multi-threading when you decompose it this way because the through put will be limited by the slowest step in the process.
A better way to decompose your problem would be to break up the job into tasks that are repeatedly executed. The slowest, but also most easily parallel part is reading and uploading the files. You can do this for each file in parallel. This allows you to leverage Javas [High Level Concurrency Objects](http://docs.oracle.com/javase/tutorial/essential/concurrency/highlevel.html) which will safe you a world of pain.
Thread 1: Watch input folder for files. When a new file appears, create a task. This task is submitted to a [Task Executor](http://www.javaworld.com/article/2078809/java-concurrency/java-101-the-next-generation-java-concurrency-without-the-pain-part-1.html). The executor will then execute the task on its own thread using one of the available threads.
Task: For a given file a task reads, parses and validate the data in the file. When the data is valid write it to the database and delete/move the original file.
Thread 2: Watch the task executor for completed tasks. When a task is complete, read its information and write a report or log an error if something went wrong.
Thread 3: Since you have tasks going on in parallel you need something to monitor user requests to stop the service gracefully. You don't want to stop the service halfway through writing a report.
Logging: Logging is a separate concern but has nothing (much) to do with threading. You should use a logging framework for this. Most frameworks can handle logging from multiple threads.
Finally note that your problem doesn't sound like a problem that would benefit much form parallel processing. Reading files, and uploading them to a database are both IO operations and IO operations are glacially slow compared to other computations. They're also the bottle neck for all parallel processes. You can't read files faster then your disk can provide them and you can't upload faster then your connection can handle. So you have to ask yourself if the marginally improved speed is worth the added complexity. | you can use Thread3.setPriority(Thread.MIN\_PRIORITY); priority is int number 1-10 1 is the minimum and 10 is the maximum |
43,836,829 | This sounded simple, but I haven't been able to figure it out.
Context: a VC tells a view to animate itself and the VC waits the animation to be completed before.
I thought about doing something like this:
In ViewController:
```
loadingView.animate()
```
In LoadingView (UIView subclass):
```
animate() -> Bool {
UIView.animate(withDuration: 1.0, animations: {
self.imageViewCenterYConstraint.constant -= 20
self.layoutIfNeeded()
}, completion {
return true // This line obviously doesn't work.
})
}
```
I do not want to include the rest of the code inside the completion block. The rest of the code is in the VC.
I suspect that all this should rather be done with an additional completion handler to add to the animate func.
PS: Just in case you know of a better solution/best practices, here is more context: I display a loading animation and remove it once I have retrieved data from the network. I always want to wait for the animation to complete before removing, even if the network data was already downloaded. Don't want to stop the animation at half of it. | 2017/05/07 | [
"https://Stackoverflow.com/questions/43836829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7698127/"
] | My experience with Selenium is limited to some niche cases where I wanted some automation (for scraping I can normally get by with requests and BeautifulSoup) but I believe the reason you are getting **None** is because `execute_script` doesn't return a value to begin with (your script is basically just being injected into the webpage and executed within the browser). Iirc, you should be able to parse your jquery out to (verbosely):
```
div = driver.find_element_by_class_name("targetclass")
targeta = div.find_element_by_link_text("[email protected]")
tr = targeta.parent.parent
retrieve = tr.find_element_by_tag_name("a")
aurlval = retrieve.getattribute("href")
```
I can't recall of the top of my head if Selenium has separate methods for list vs first-element, so you may have to take the zero index on those lines. | One way is to use javascript as below to get the table row along with the previous answers steps. WebDriver doesn't have a 'parent' method of its own.
```
div = driver.find_element_by_class_name("targetclass")
targeta = div.find_element_by_link_text("[email protected]")
tr = self.driver.execute_script("return arguments[0].parentNode.parentNode;", targeta)
```
Then you can find elements in the row.
Or you can try "return arguments[0].parentNode;" which should get the td and then try to get previous-sibling, but I haven't tried that. |
32,488,101 | I want to do an animation that zooms in from a calendar, specifically with the origin and frame size being that of the button that represent's today's date. Here is the code for determining the todayButton inside CalendarMonthView.m:
```
NSDate *date = (weekdayOffset > 0) ? [_monthStartDate dateByAddingTimeInterval:-1 * weekdayOffset * D_DAY] : _monthStartDate;
BOOL bEnabled = (weekdayOffset == 0);
CGRect buttonFrame = CGRectMake (0, 0, 81, 61);
int idx = -1 * weekdayOffset;
for (int y = 0; y < 6; y++) {
buttonFrame.origin.x = 0;
for (int x = 0; x < 7; x++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = idx++;
[button setFrame:buttonFrame];
[button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_dayContainer_today.png"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_selected.png"] forState:UIControlStateHighlighted];
button.titleLabel.font = [UIFont fontWithName:@"TitilliumWeb-Regular" size:18.0];
button.titleLabel.textAlignment = NSTextAlignmentCenter;
// TODO: optimize performance
int dayOfMonth = (int)[_calendar component:NSCalendarUnitDay fromDate:date];
if (dayOfMonth < prevDayOfMonth) {
bEnabled = !bEnabled;
}
prevDayOfMonth = dayOfMonth;
[button setTitle:[NSString stringWithFormat:@"%d", dayOfMonth] forState:UIControlStateNormal];
[button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:((bEnabled) ? @"calendarFlyout_dayContainer_insideMonth.png"
: @"calendarFlyout_dayContainer_outsideMonth.png")]
forState:UIControlStateNormal];
// button.enabled = bEnabled;
button.selected = [date isToday];
if (button.selected == NO) {
button.highlighted = (_currentDayDate) ? [date isEqualToDateIgnoringTime:_currentDayDate] : NO;
} else {
// Set buttonHolder to today
}
[button addTarget:self action:@selector (dayButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[_dayButtonsHolderView addSubview:button];
buttonFrame.origin.x += buttonFrame.size.width;
date = [date dateByAddingTimeInterval:D_DAY];
}
buttonFrame.origin.y += buttonFrame.size.height;
}
- (IBAction)dayButtonTapped:(id)sender
{
if (_delegate) {
UIButton *button = (UIButton *)sender;
NSDate *selectedDate = [_monthStartDate dateByAddingDays:button.tag];
[_delegate performSelector:@selector (calendarMonthView:dateSelected:) withObject:self withObject:selectedDate];
}
}
```
I want to get the frame of `button` and use it in this animation used in CalendarFlyoutView.m.
I'm new to iOS programming and I read up on some delegate information and passing information through segues, but it doesn't seem to help me here.
Any help would be greatly appreciated. | 2015/09/09 | [
"https://Stackoverflow.com/questions/32488101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5125365/"
] | If you are making a segue from the `CalendarMonthView` to the `CalendarFlyoutView` then you can just add this method to the `CalendarMonthView`.
```
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
CalendarFlyoutView * view = segue.destinationViewController;
view.buttonFrame = button.frame;
}
```
and in your `CalendarFlyoutView.h`
```
@interface CalendarFlyoutView : UIViewController
@property CGRect buttonFrame;
@end
``` | A couple of questions that need to be answered to best help you:
1) Are CalendarMonthView and CalendarFlyoutView UIView or UIViewController? You say view controller, but the class name says otherwise.
2) What is happening in the method 'dayButtonTapped'? Are you performing a segue there? Are you somehow creating or loading an instance of CalendarFlyoutView?
3) If you are not using a segue, are you somehow creating and add a child view controller for CalendarFlyoutView to CalendarMonthView?
4) What is the desired transition (your animation)? Does the CalendarFlyoutView start at the same size as the button, then fill the whole screen?
5) Is there a specific reason that you are setting the button's frame instead of constraining it in the correct place?
Once we know a little more about these questions we should be able to provide some more concrete suggestions. |
32,488,101 | I want to do an animation that zooms in from a calendar, specifically with the origin and frame size being that of the button that represent's today's date. Here is the code for determining the todayButton inside CalendarMonthView.m:
```
NSDate *date = (weekdayOffset > 0) ? [_monthStartDate dateByAddingTimeInterval:-1 * weekdayOffset * D_DAY] : _monthStartDate;
BOOL bEnabled = (weekdayOffset == 0);
CGRect buttonFrame = CGRectMake (0, 0, 81, 61);
int idx = -1 * weekdayOffset;
for (int y = 0; y < 6; y++) {
buttonFrame.origin.x = 0;
for (int x = 0; x < 7; x++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = idx++;
[button setFrame:buttonFrame];
[button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_dayContainer_today.png"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_selected.png"] forState:UIControlStateHighlighted];
button.titleLabel.font = [UIFont fontWithName:@"TitilliumWeb-Regular" size:18.0];
button.titleLabel.textAlignment = NSTextAlignmentCenter;
// TODO: optimize performance
int dayOfMonth = (int)[_calendar component:NSCalendarUnitDay fromDate:date];
if (dayOfMonth < prevDayOfMonth) {
bEnabled = !bEnabled;
}
prevDayOfMonth = dayOfMonth;
[button setTitle:[NSString stringWithFormat:@"%d", dayOfMonth] forState:UIControlStateNormal];
[button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:((bEnabled) ? @"calendarFlyout_dayContainer_insideMonth.png"
: @"calendarFlyout_dayContainer_outsideMonth.png")]
forState:UIControlStateNormal];
// button.enabled = bEnabled;
button.selected = [date isToday];
if (button.selected == NO) {
button.highlighted = (_currentDayDate) ? [date isEqualToDateIgnoringTime:_currentDayDate] : NO;
} else {
// Set buttonHolder to today
}
[button addTarget:self action:@selector (dayButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[_dayButtonsHolderView addSubview:button];
buttonFrame.origin.x += buttonFrame.size.width;
date = [date dateByAddingTimeInterval:D_DAY];
}
buttonFrame.origin.y += buttonFrame.size.height;
}
- (IBAction)dayButtonTapped:(id)sender
{
if (_delegate) {
UIButton *button = (UIButton *)sender;
NSDate *selectedDate = [_monthStartDate dateByAddingDays:button.tag];
[_delegate performSelector:@selector (calendarMonthView:dateSelected:) withObject:self withObject:selectedDate];
}
}
```
I want to get the frame of `button` and use it in this animation used in CalendarFlyoutView.m.
I'm new to iOS programming and I read up on some delegate information and passing information through segues, but it doesn't seem to help me here.
Any help would be greatly appreciated. | 2015/09/09 | [
"https://Stackoverflow.com/questions/32488101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5125365/"
] | Use the `transform` feature.
// animate in year calendar
\_yearCalendarView.hidden = NO;
self.curMonthView.monthLabel.hidden = YES;
```
CalendarMonthView *monthView = [CalendarMonthView new];
monthView.delegate = self;
CGRect buttonFrame = _currentDayButtonFrame;
_yearCalendarView.frame = CGRectMake(buttonFrame.origin.x, buttonFrame.origin.y + buttonFrame.size.height, buttonFrame.size.width, buttonFrame.size.height);
NSLog(@"_yearCalendarView frame: %@", NSStringFromCGRect(_yearCalendarView.frame));
_yearCalendarView.transform = CGAffineTransformMakeScale(0.01, 0.01);
[UIView animateWithDuration:kAnimation_ExpandCalendarDuration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
_yearCalendarView.transform = CGAffineTransformIdentity;
_yearCalendarView.frame = CGRectMake(_monthSwiperScrollView.frame.origin.x, _monthBarImageView.frame.size.height + 20, _monthSwiperScrollView.frame.size.width + 2, _yearFlyoutHeight);
} completion:^(BOOL finished) {
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector (yearCalendarAnimationDidStop:finished:context:)];
}];
``` | If you are making a segue from the `CalendarMonthView` to the `CalendarFlyoutView` then you can just add this method to the `CalendarMonthView`.
```
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
CalendarFlyoutView * view = segue.destinationViewController;
view.buttonFrame = button.frame;
}
```
and in your `CalendarFlyoutView.h`
```
@interface CalendarFlyoutView : UIViewController
@property CGRect buttonFrame;
@end
``` |
32,488,101 | I want to do an animation that zooms in from a calendar, specifically with the origin and frame size being that of the button that represent's today's date. Here is the code for determining the todayButton inside CalendarMonthView.m:
```
NSDate *date = (weekdayOffset > 0) ? [_monthStartDate dateByAddingTimeInterval:-1 * weekdayOffset * D_DAY] : _monthStartDate;
BOOL bEnabled = (weekdayOffset == 0);
CGRect buttonFrame = CGRectMake (0, 0, 81, 61);
int idx = -1 * weekdayOffset;
for (int y = 0; y < 6; y++) {
buttonFrame.origin.x = 0;
for (int x = 0; x < 7; x++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = idx++;
[button setFrame:buttonFrame];
[button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_dayContainer_today.png"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_selected.png"] forState:UIControlStateHighlighted];
button.titleLabel.font = [UIFont fontWithName:@"TitilliumWeb-Regular" size:18.0];
button.titleLabel.textAlignment = NSTextAlignmentCenter;
// TODO: optimize performance
int dayOfMonth = (int)[_calendar component:NSCalendarUnitDay fromDate:date];
if (dayOfMonth < prevDayOfMonth) {
bEnabled = !bEnabled;
}
prevDayOfMonth = dayOfMonth;
[button setTitle:[NSString stringWithFormat:@"%d", dayOfMonth] forState:UIControlStateNormal];
[button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:((bEnabled) ? @"calendarFlyout_dayContainer_insideMonth.png"
: @"calendarFlyout_dayContainer_outsideMonth.png")]
forState:UIControlStateNormal];
// button.enabled = bEnabled;
button.selected = [date isToday];
if (button.selected == NO) {
button.highlighted = (_currentDayDate) ? [date isEqualToDateIgnoringTime:_currentDayDate] : NO;
} else {
// Set buttonHolder to today
}
[button addTarget:self action:@selector (dayButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[_dayButtonsHolderView addSubview:button];
buttonFrame.origin.x += buttonFrame.size.width;
date = [date dateByAddingTimeInterval:D_DAY];
}
buttonFrame.origin.y += buttonFrame.size.height;
}
- (IBAction)dayButtonTapped:(id)sender
{
if (_delegate) {
UIButton *button = (UIButton *)sender;
NSDate *selectedDate = [_monthStartDate dateByAddingDays:button.tag];
[_delegate performSelector:@selector (calendarMonthView:dateSelected:) withObject:self withObject:selectedDate];
}
}
```
I want to get the frame of `button` and use it in this animation used in CalendarFlyoutView.m.
I'm new to iOS programming and I read up on some delegate information and passing information through segues, but it doesn't seem to help me here.
Any help would be greatly appreciated. | 2015/09/09 | [
"https://Stackoverflow.com/questions/32488101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5125365/"
] | If you are making a segue from the `CalendarMonthView` to the `CalendarFlyoutView` then you can just add this method to the `CalendarMonthView`.
```
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
CalendarFlyoutView * view = segue.destinationViewController;
view.buttonFrame = button.frame;
}
```
and in your `CalendarFlyoutView.h`
```
@interface CalendarFlyoutView : UIViewController
@property CGRect buttonFrame;
@end
``` | It's still not very clear where the actual animation code is being run. In your question, you state "I want to get the frame of button and use it in this animation used in CalendarFlyoutView.m." which seems to imply the animation code is in CalendarFlyoutView, which seems like an odd place for it.
There are a few things I could recommend, given my incomplete understanding of the whole of the code:
1) Move the animation code to the dayButtonTapped method, where you already have a reference to the button, and therefore it's frame. It also seems like a more logical place for it.
2) Where ever you are instantiating the CalendarFlyoutView (not shown in the code you posted), assign the button frame there.
3) If there is only a single instance of CalendarFlyoutView and you have a reference to it in CalendarMonthView, you could assign a property of the flyout view that is the frame of the button you already have a reference to in the dayButtonTapped method.
I have to add though, that these are just work arounds to what seems like a structural issue. Is this a reusable control you are trying to write? Why did you decide to not use the storyboard or view controllers? Why are you using frames and absolute sizes and positions at all instead of letting auto layout do it's job (you will bang your head against the wall for hours trying to tweak everything to run correctly in all orientations and all possible device screen sizes). |
32,488,101 | I want to do an animation that zooms in from a calendar, specifically with the origin and frame size being that of the button that represent's today's date. Here is the code for determining the todayButton inside CalendarMonthView.m:
```
NSDate *date = (weekdayOffset > 0) ? [_monthStartDate dateByAddingTimeInterval:-1 * weekdayOffset * D_DAY] : _monthStartDate;
BOOL bEnabled = (weekdayOffset == 0);
CGRect buttonFrame = CGRectMake (0, 0, 81, 61);
int idx = -1 * weekdayOffset;
for (int y = 0; y < 6; y++) {
buttonFrame.origin.x = 0;
for (int x = 0; x < 7; x++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = idx++;
[button setFrame:buttonFrame];
[button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_dayContainer_today.png"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_selected.png"] forState:UIControlStateHighlighted];
button.titleLabel.font = [UIFont fontWithName:@"TitilliumWeb-Regular" size:18.0];
button.titleLabel.textAlignment = NSTextAlignmentCenter;
// TODO: optimize performance
int dayOfMonth = (int)[_calendar component:NSCalendarUnitDay fromDate:date];
if (dayOfMonth < prevDayOfMonth) {
bEnabled = !bEnabled;
}
prevDayOfMonth = dayOfMonth;
[button setTitle:[NSString stringWithFormat:@"%d", dayOfMonth] forState:UIControlStateNormal];
[button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:((bEnabled) ? @"calendarFlyout_dayContainer_insideMonth.png"
: @"calendarFlyout_dayContainer_outsideMonth.png")]
forState:UIControlStateNormal];
// button.enabled = bEnabled;
button.selected = [date isToday];
if (button.selected == NO) {
button.highlighted = (_currentDayDate) ? [date isEqualToDateIgnoringTime:_currentDayDate] : NO;
} else {
// Set buttonHolder to today
}
[button addTarget:self action:@selector (dayButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[_dayButtonsHolderView addSubview:button];
buttonFrame.origin.x += buttonFrame.size.width;
date = [date dateByAddingTimeInterval:D_DAY];
}
buttonFrame.origin.y += buttonFrame.size.height;
}
- (IBAction)dayButtonTapped:(id)sender
{
if (_delegate) {
UIButton *button = (UIButton *)sender;
NSDate *selectedDate = [_monthStartDate dateByAddingDays:button.tag];
[_delegate performSelector:@selector (calendarMonthView:dateSelected:) withObject:self withObject:selectedDate];
}
}
```
I want to get the frame of `button` and use it in this animation used in CalendarFlyoutView.m.
I'm new to iOS programming and I read up on some delegate information and passing information through segues, but it doesn't seem to help me here.
Any help would be greatly appreciated. | 2015/09/09 | [
"https://Stackoverflow.com/questions/32488101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5125365/"
] | Use the `transform` feature.
// animate in year calendar
\_yearCalendarView.hidden = NO;
self.curMonthView.monthLabel.hidden = YES;
```
CalendarMonthView *monthView = [CalendarMonthView new];
monthView.delegate = self;
CGRect buttonFrame = _currentDayButtonFrame;
_yearCalendarView.frame = CGRectMake(buttonFrame.origin.x, buttonFrame.origin.y + buttonFrame.size.height, buttonFrame.size.width, buttonFrame.size.height);
NSLog(@"_yearCalendarView frame: %@", NSStringFromCGRect(_yearCalendarView.frame));
_yearCalendarView.transform = CGAffineTransformMakeScale(0.01, 0.01);
[UIView animateWithDuration:kAnimation_ExpandCalendarDuration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
_yearCalendarView.transform = CGAffineTransformIdentity;
_yearCalendarView.frame = CGRectMake(_monthSwiperScrollView.frame.origin.x, _monthBarImageView.frame.size.height + 20, _monthSwiperScrollView.frame.size.width + 2, _yearFlyoutHeight);
} completion:^(BOOL finished) {
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector (yearCalendarAnimationDidStop:finished:context:)];
}];
``` | A couple of questions that need to be answered to best help you:
1) Are CalendarMonthView and CalendarFlyoutView UIView or UIViewController? You say view controller, but the class name says otherwise.
2) What is happening in the method 'dayButtonTapped'? Are you performing a segue there? Are you somehow creating or loading an instance of CalendarFlyoutView?
3) If you are not using a segue, are you somehow creating and add a child view controller for CalendarFlyoutView to CalendarMonthView?
4) What is the desired transition (your animation)? Does the CalendarFlyoutView start at the same size as the button, then fill the whole screen?
5) Is there a specific reason that you are setting the button's frame instead of constraining it in the correct place?
Once we know a little more about these questions we should be able to provide some more concrete suggestions. |
32,488,101 | I want to do an animation that zooms in from a calendar, specifically with the origin and frame size being that of the button that represent's today's date. Here is the code for determining the todayButton inside CalendarMonthView.m:
```
NSDate *date = (weekdayOffset > 0) ? [_monthStartDate dateByAddingTimeInterval:-1 * weekdayOffset * D_DAY] : _monthStartDate;
BOOL bEnabled = (weekdayOffset == 0);
CGRect buttonFrame = CGRectMake (0, 0, 81, 61);
int idx = -1 * weekdayOffset;
for (int y = 0; y < 6; y++) {
buttonFrame.origin.x = 0;
for (int x = 0; x < 7; x++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = idx++;
[button setFrame:buttonFrame];
[button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_dayContainer_today.png"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_selected.png"] forState:UIControlStateHighlighted];
button.titleLabel.font = [UIFont fontWithName:@"TitilliumWeb-Regular" size:18.0];
button.titleLabel.textAlignment = NSTextAlignmentCenter;
// TODO: optimize performance
int dayOfMonth = (int)[_calendar component:NSCalendarUnitDay fromDate:date];
if (dayOfMonth < prevDayOfMonth) {
bEnabled = !bEnabled;
}
prevDayOfMonth = dayOfMonth;
[button setTitle:[NSString stringWithFormat:@"%d", dayOfMonth] forState:UIControlStateNormal];
[button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:((bEnabled) ? @"calendarFlyout_dayContainer_insideMonth.png"
: @"calendarFlyout_dayContainer_outsideMonth.png")]
forState:UIControlStateNormal];
// button.enabled = bEnabled;
button.selected = [date isToday];
if (button.selected == NO) {
button.highlighted = (_currentDayDate) ? [date isEqualToDateIgnoringTime:_currentDayDate] : NO;
} else {
// Set buttonHolder to today
}
[button addTarget:self action:@selector (dayButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[_dayButtonsHolderView addSubview:button];
buttonFrame.origin.x += buttonFrame.size.width;
date = [date dateByAddingTimeInterval:D_DAY];
}
buttonFrame.origin.y += buttonFrame.size.height;
}
- (IBAction)dayButtonTapped:(id)sender
{
if (_delegate) {
UIButton *button = (UIButton *)sender;
NSDate *selectedDate = [_monthStartDate dateByAddingDays:button.tag];
[_delegate performSelector:@selector (calendarMonthView:dateSelected:) withObject:self withObject:selectedDate];
}
}
```
I want to get the frame of `button` and use it in this animation used in CalendarFlyoutView.m.
I'm new to iOS programming and I read up on some delegate information and passing information through segues, but it doesn't seem to help me here.
Any help would be greatly appreciated. | 2015/09/09 | [
"https://Stackoverflow.com/questions/32488101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5125365/"
] | A couple of questions that need to be answered to best help you:
1) Are CalendarMonthView and CalendarFlyoutView UIView or UIViewController? You say view controller, but the class name says otherwise.
2) What is happening in the method 'dayButtonTapped'? Are you performing a segue there? Are you somehow creating or loading an instance of CalendarFlyoutView?
3) If you are not using a segue, are you somehow creating and add a child view controller for CalendarFlyoutView to CalendarMonthView?
4) What is the desired transition (your animation)? Does the CalendarFlyoutView start at the same size as the button, then fill the whole screen?
5) Is there a specific reason that you are setting the button's frame instead of constraining it in the correct place?
Once we know a little more about these questions we should be able to provide some more concrete suggestions. | It's still not very clear where the actual animation code is being run. In your question, you state "I want to get the frame of button and use it in this animation used in CalendarFlyoutView.m." which seems to imply the animation code is in CalendarFlyoutView, which seems like an odd place for it.
There are a few things I could recommend, given my incomplete understanding of the whole of the code:
1) Move the animation code to the dayButtonTapped method, where you already have a reference to the button, and therefore it's frame. It also seems like a more logical place for it.
2) Where ever you are instantiating the CalendarFlyoutView (not shown in the code you posted), assign the button frame there.
3) If there is only a single instance of CalendarFlyoutView and you have a reference to it in CalendarMonthView, you could assign a property of the flyout view that is the frame of the button you already have a reference to in the dayButtonTapped method.
I have to add though, that these are just work arounds to what seems like a structural issue. Is this a reusable control you are trying to write? Why did you decide to not use the storyboard or view controllers? Why are you using frames and absolute sizes and positions at all instead of letting auto layout do it's job (you will bang your head against the wall for hours trying to tweak everything to run correctly in all orientations and all possible device screen sizes). |
32,488,101 | I want to do an animation that zooms in from a calendar, specifically with the origin and frame size being that of the button that represent's today's date. Here is the code for determining the todayButton inside CalendarMonthView.m:
```
NSDate *date = (weekdayOffset > 0) ? [_monthStartDate dateByAddingTimeInterval:-1 * weekdayOffset * D_DAY] : _monthStartDate;
BOOL bEnabled = (weekdayOffset == 0);
CGRect buttonFrame = CGRectMake (0, 0, 81, 61);
int idx = -1 * weekdayOffset;
for (int y = 0; y < 6; y++) {
buttonFrame.origin.x = 0;
for (int x = 0; x < 7; x++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = idx++;
[button setFrame:buttonFrame];
[button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_dayContainer_today.png"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:@"calendarFlyout_selected.png"] forState:UIControlStateHighlighted];
button.titleLabel.font = [UIFont fontWithName:@"TitilliumWeb-Regular" size:18.0];
button.titleLabel.textAlignment = NSTextAlignmentCenter;
// TODO: optimize performance
int dayOfMonth = (int)[_calendar component:NSCalendarUnitDay fromDate:date];
if (dayOfMonth < prevDayOfMonth) {
bEnabled = !bEnabled;
}
prevDayOfMonth = dayOfMonth;
[button setTitle:[NSString stringWithFormat:@"%d", dayOfMonth] forState:UIControlStateNormal];
[button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:((bEnabled) ? @"calendarFlyout_dayContainer_insideMonth.png"
: @"calendarFlyout_dayContainer_outsideMonth.png")]
forState:UIControlStateNormal];
// button.enabled = bEnabled;
button.selected = [date isToday];
if (button.selected == NO) {
button.highlighted = (_currentDayDate) ? [date isEqualToDateIgnoringTime:_currentDayDate] : NO;
} else {
// Set buttonHolder to today
}
[button addTarget:self action:@selector (dayButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[_dayButtonsHolderView addSubview:button];
buttonFrame.origin.x += buttonFrame.size.width;
date = [date dateByAddingTimeInterval:D_DAY];
}
buttonFrame.origin.y += buttonFrame.size.height;
}
- (IBAction)dayButtonTapped:(id)sender
{
if (_delegate) {
UIButton *button = (UIButton *)sender;
NSDate *selectedDate = [_monthStartDate dateByAddingDays:button.tag];
[_delegate performSelector:@selector (calendarMonthView:dateSelected:) withObject:self withObject:selectedDate];
}
}
```
I want to get the frame of `button` and use it in this animation used in CalendarFlyoutView.m.
I'm new to iOS programming and I read up on some delegate information and passing information through segues, but it doesn't seem to help me here.
Any help would be greatly appreciated. | 2015/09/09 | [
"https://Stackoverflow.com/questions/32488101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5125365/"
] | Use the `transform` feature.
// animate in year calendar
\_yearCalendarView.hidden = NO;
self.curMonthView.monthLabel.hidden = YES;
```
CalendarMonthView *monthView = [CalendarMonthView new];
monthView.delegate = self;
CGRect buttonFrame = _currentDayButtonFrame;
_yearCalendarView.frame = CGRectMake(buttonFrame.origin.x, buttonFrame.origin.y + buttonFrame.size.height, buttonFrame.size.width, buttonFrame.size.height);
NSLog(@"_yearCalendarView frame: %@", NSStringFromCGRect(_yearCalendarView.frame));
_yearCalendarView.transform = CGAffineTransformMakeScale(0.01, 0.01);
[UIView animateWithDuration:kAnimation_ExpandCalendarDuration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
_yearCalendarView.transform = CGAffineTransformIdentity;
_yearCalendarView.frame = CGRectMake(_monthSwiperScrollView.frame.origin.x, _monthBarImageView.frame.size.height + 20, _monthSwiperScrollView.frame.size.width + 2, _yearFlyoutHeight);
} completion:^(BOOL finished) {
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector (yearCalendarAnimationDidStop:finished:context:)];
}];
``` | It's still not very clear where the actual animation code is being run. In your question, you state "I want to get the frame of button and use it in this animation used in CalendarFlyoutView.m." which seems to imply the animation code is in CalendarFlyoutView, which seems like an odd place for it.
There are a few things I could recommend, given my incomplete understanding of the whole of the code:
1) Move the animation code to the dayButtonTapped method, where you already have a reference to the button, and therefore it's frame. It also seems like a more logical place for it.
2) Where ever you are instantiating the CalendarFlyoutView (not shown in the code you posted), assign the button frame there.
3) If there is only a single instance of CalendarFlyoutView and you have a reference to it in CalendarMonthView, you could assign a property of the flyout view that is the frame of the button you already have a reference to in the dayButtonTapped method.
I have to add though, that these are just work arounds to what seems like a structural issue. Is this a reusable control you are trying to write? Why did you decide to not use the storyboard or view controllers? Why are you using frames and absolute sizes and positions at all instead of letting auto layout do it's job (you will bang your head against the wall for hours trying to tweak everything to run correctly in all orientations and all possible device screen sizes). |
1,474,968 | What is the coefficient of $x^9$ in the expansion of $(1+x)(1+x^2)(1+x^3)\cdots (1+x^{100})?$
---
I manually expanded $(1+x)(1+x^2)(1+x^3)...(1+x^{10})$ and calculated the coefficient of $x^9$ as $8$ but i dont know how to solve it without expanding.Please help me. | 2015/10/11 | [
"https://math.stackexchange.com/questions/1474968",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/262197/"
] | The coefficient of $x^9$ is the number of [partitions](https://en.wikipedia.org/wiki/Partition_%28number_theory%29) of $9$ into distinct parts, i.e., the number of ways of writing $9$ as the sum of distinct positive integers when the order of the summands doesn’t matter. The sequence of these numbers is [OEIS A000009](https://oeis.org/A000009), and as you can see there, there is no nice formula. However, for small $n$ it’s not hard to write out the partitions by hand: $9$, $8+1$, $7+2$, $6+3$, $5+4$, $6+2+1$, $5+3+1$, and $4+3+2$. | In every factor of your product, you will need to pick either the $1$ or the $x^i$, so immediatly we see that for all factors with $i > 9$ we need to pick the $1$, otherwise we will get $x^k$ with $k > 9$. So we can just look at the product up till $(1 + x^9)$. Now we look at the number of ways to pick $1$ and $x^i$ here such that we end up with $x^9$. Because all our coefficients are $1$, we do not need to worry about those, and count only the number of ways.
To simplify this, assume you always pick the $1$ if you don't write them down, then all possible combinations are:
$x^9, x^1\cdot x^8, x^2\cdot x^7, x^3\cdot x^6, x^4\cdot x^5, x^1\cdot x^2\cdot x^6, x^1\cdot x^3\cdot x^5, x^2\cdot x^3\cdot x^4$ which gives us $8$ as the final result.
It is not hard to see that this is equivalent to summing numbers $1, \ldots 9$ to $9$ using every number only once, and then counting the number of summations. |
1,474,968 | What is the coefficient of $x^9$ in the expansion of $(1+x)(1+x^2)(1+x^3)\cdots (1+x^{100})?$
---
I manually expanded $(1+x)(1+x^2)(1+x^3)...(1+x^{10})$ and calculated the coefficient of $x^9$ as $8$ but i dont know how to solve it without expanding.Please help me. | 2015/10/11 | [
"https://math.stackexchange.com/questions/1474968",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/262197/"
] | I think the problem boils down to counting the number of ways to write $9$ as a sum of distinct, positive integers. There is the trivial case of $9=9$, and besides that try by hand to catch all other cases like $1+3+5$, $1+2+6$, etc. I think your best bet is to brute force this problem; one of those times where it's just easier to consider every case than to search for an elegant solution. My reasoning is as follows:
Think of the product $$\prod\_{n=1}^{100} (1+x^n)$$ as a potential game of telephone where a "message" is passed from one parenthetical quantity to the next via multiplication. In each passage the message can either go to $1$ or $x^n$. For example, we could start at $1$ in $(1+x)$, then go to $1$ in $(1+x^2)$ and $\ldots$ and go to $1$ in $(1+x^{99})$ and lastly go to $x^{100}$ in $(1+x^{100})$ , which is to say we get $1^{99}\cdot x^{100} = x^{100}$ at the end of that particular sequence of multiplication. So we'll expect at least one quantity of $x^{100}$ in the fully expanded product. I'll call "getting $x^{100}$ out of that particular sequence of multiplication" the *result* of that message. More generally, the coefficient $R\_p$ that appears on $x^p$ in the fully expanded product $$\prod\_{n=1}^{100} (1+x^n) = R\_0+R\_1x^1+R\_2x^2+\ldots +R\_px^p +\ldots + R\_{5050}x^{5050}$$ tells us the number of ways our message *resulted* in $x^p$.
Hopefully the analogy is clear. Since we now are interested in the coefficient of $x^9$ here is why I said what I did in my first paragraph. We need to know how many ways there are to pass a message through the product so that it results in $x^9$ by the end. One possible path would be to start at $x$, pass to $x^2$, pass to $1$ in $(1+x^3)$, pass to $1$ in $(1+x^4)$, pass to $1$ in $(1+x^5)$, pass to $x^6$. At this point we *have* to pass to $1$ in the rest of the $(1+x^n)$'s. Otherwise at the end of the message we'll have $x^p$ with $p>9$ at the end. The path I just mentioned results in $$x^1\cdot x^2 \cdot 1^3 \cdot x^6 \cdot 1^{94} = x^9$$ which works because the sum of exponents on each $x$ in the product, $1+2+6$ sums to $9$. Hence you really do just want to count the number of ways to write $9$ as a sum of distinct, positive integers; much easier than computing the entire product. I concur that $R\_9 = 8$. | In every factor of your product, you will need to pick either the $1$ or the $x^i$, so immediatly we see that for all factors with $i > 9$ we need to pick the $1$, otherwise we will get $x^k$ with $k > 9$. So we can just look at the product up till $(1 + x^9)$. Now we look at the number of ways to pick $1$ and $x^i$ here such that we end up with $x^9$. Because all our coefficients are $1$, we do not need to worry about those, and count only the number of ways.
To simplify this, assume you always pick the $1$ if you don't write them down, then all possible combinations are:
$x^9, x^1\cdot x^8, x^2\cdot x^7, x^3\cdot x^6, x^4\cdot x^5, x^1\cdot x^2\cdot x^6, x^1\cdot x^3\cdot x^5, x^2\cdot x^3\cdot x^4$ which gives us $8$ as the final result.
It is not hard to see that this is equivalent to summing numbers $1, \ldots 9$ to $9$ using every number only once, and then counting the number of summations. |
7,623 | Helo Guys,
I want to know your experience about carbon material and grease
Can I use normal grease with carbon ?
I want to put grease onto fork and stem....
Or WD-40 or silicone penetrant would be ok ?
Thank you....
Can I use this one ?
 | 2012/01/11 | [
"https://bicycles.stackexchange.com/questions/7623",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/3189/"
] | From [Sheldon Brown](http://sheldonbrown.com/gloss_g.html):
>
> Grease lubrication is commonly used on all ball bearings. Good mechanics also use grease (or oil) on the threads of most threaded fittings and fasteners, and also inside the steerer (to keep the stem from becoming stuck) and the seat tube (to keep the seatpost from becoming stuck.)
>
>
> There are a great many different greases on the market with different special features, mainly for automotive applications. For bicycle use, almost any grease is adequate, since the loads and temperatures are generally low.
>
>
>
Seems to me like the answer is *yes*, although to be safe why don't you invest in some [Finish Line Teflon Grease](http://www.finishlineusa.com/products/fortified-grease.htm) - one tube will last you for years. From the Finish Line [website](http://www.finishlineusa.com/frequentquestions/index.htm):
>
> **Q. Are Finish Line products safe for use on Carbon Fiber Frames and Parts?**
>
>
> **A. Yes.** All of our products are safe to use on carbon fiber bike parts; our three degreasers, four lubes, our polish, grease, etc are all safe to use on and around carbon fiber bike parts. The exception is our DOT Brake Fluid – you don’t want to get DOT fluid on any painted or finished surface because it’ll attack the paint / finish.
>
>
> | Most automotive use grease is too thick for bicycle applications. It will lubricate, but it will add friction to the movement of the bike.
Aside from the "weight" of the grease, you only need to worry about purity.
Phil Wood, of Phil Wood Components, used to say that his most important criteria for his bicycle grease was too make sure it matched the color of his original green sample. If it varied, even a little, he was besieged by inquiries about what he'd changed in his "formula". |
7,623 | Helo Guys,
I want to know your experience about carbon material and grease
Can I use normal grease with carbon ?
I want to put grease onto fork and stem....
Or WD-40 or silicone penetrant would be ok ?
Thank you....
Can I use this one ?
 | 2012/01/11 | [
"https://bicycles.stackexchange.com/questions/7623",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/3189/"
] | From [Sheldon Brown](http://sheldonbrown.com/gloss_g.html):
>
> Grease lubrication is commonly used on all ball bearings. Good mechanics also use grease (or oil) on the threads of most threaded fittings and fasteners, and also inside the steerer (to keep the stem from becoming stuck) and the seat tube (to keep the seatpost from becoming stuck.)
>
>
> There are a great many different greases on the market with different special features, mainly for automotive applications. For bicycle use, almost any grease is adequate, since the loads and temperatures are generally low.
>
>
>
Seems to me like the answer is *yes*, although to be safe why don't you invest in some [Finish Line Teflon Grease](http://www.finishlineusa.com/products/fortified-grease.htm) - one tube will last you for years. From the Finish Line [website](http://www.finishlineusa.com/frequentquestions/index.htm):
>
> **Q. Are Finish Line products safe for use on Carbon Fiber Frames and Parts?**
>
>
> **A. Yes.** All of our products are safe to use on carbon fiber bike parts; our three degreasers, four lubes, our polish, grease, etc are all safe to use on and around carbon fiber bike parts. The exception is our DOT Brake Fluid – you don’t want to get DOT fluid on any painted or finished surface because it’ll attack the paint / finish.
>
>
> | i would be careful of any type of grease i use on a bike.. Grease attracts the dirt and can lead to further issues on the mechanics of your bike. like stated before - use an oil specially formulated for your bike. and make sure after every cycle to clean your bike down and re-oil. |
7,623 | Helo Guys,
I want to know your experience about carbon material and grease
Can I use normal grease with carbon ?
I want to put grease onto fork and stem....
Or WD-40 or silicone penetrant would be ok ?
Thank you....
Can I use this one ?
 | 2012/01/11 | [
"https://bicycles.stackexchange.com/questions/7623",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/3189/"
] | Most automotive use grease is too thick for bicycle applications. It will lubricate, but it will add friction to the movement of the bike.
Aside from the "weight" of the grease, you only need to worry about purity.
Phil Wood, of Phil Wood Components, used to say that his most important criteria for his bicycle grease was too make sure it matched the color of his original green sample. If it varied, even a little, he was besieged by inquiries about what he'd changed in his "formula". | i would be careful of any type of grease i use on a bike.. Grease attracts the dirt and can lead to further issues on the mechanics of your bike. like stated before - use an oil specially formulated for your bike. and make sure after every cycle to clean your bike down and re-oil. |
245,522 | I have a field name where all the values are capitalized so I used title('string') to get my desired results:
```
'OLONGAPO CITY'
```
will result to
```
'Olongapo City'.
```
However, there are strings such as:
```
CITY OF MAKATI
```
I want it to appear as
```
'City of Makati'
```
instead of
```
'City Of Makati'
``` | 2017/06/27 | [
"https://gis.stackexchange.com/questions/245522",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/35246/"
] | You could try using something like the following expression:
```
replace(title("fieldName"), 'Of', 'of')
``` | If you want proper title case rules (including correct handling of a/of/the/etc), you could grab the source of Titlecase.py (See <https://muffinresearch.co.uk/titlecasepy-titlecase-in-python/> ) and insert this in a custom expression function from the "Function Editor" tab in the expression builder:
[](https://i.stack.imgur.com/Qsbcq.png)
The code look something like:
```
@qgsfunction(args='auto', group='String')
def title_case(value1, feature, parent):
return titlecase(value1)
```
...followed by the entire copy/pasted contents of [`https://raw.githubusercontent.com/ppannuto/python-titlecase/master/titlecase/__init__.py`](https://raw.githubusercontent.com/ppannuto/python-titlecase/master/titlecase/__init__.py)
You'll then be able to use this new `title_case` function anywhere in QGIS expressions:[](https://i.stack.imgur.com/j8LTf.png) |
60,862,825 | I find the method `public ValueStateDescriptor(String name,TypeInformation<T> typeInfo,T defaultValue)`is now deprecated and the documentation says to manage the default value by checking whether the contents of the state is null.
I wonder what does this suggestion for? | 2020/03/26 | [
"https://Stackoverflow.com/questions/60862825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13110035/"
] | We have discovered that our own proxy were writing Access-Control-Allow-Origin header as well. That's why together with keycloak we got it twice.
Our devops team has fixed the code of our proxy and it works now. | `*` is not valid value for `Access-Control-Allow-Origin` for sites running on https.
Remove `*` from web origins client configuration in the Keycloak and configure all used web origin explicitly (no wildchars). |
16,877,762 | **This is a spoiler to task #3 of Project Euler! Don't continue to read, if you want to solve it by yourself.**
I am trying to learn Haskell by writing programs for Project Euler. At the moment I'm trying to solve task #3 which asks for the largest prime factor of the number 600851475143.
To do this, I create a list `liste` which contains all numbers, which are divisors of this number (up to its squareroot). My strategy is now, to count the divisors of these numbers, to decide, if they are prime.
```
number = 600851475143
-- sn = sqrt number
sn = 775146
liste = [x | x <- [1..sn], (mod number x == 0)]
-- liste = [1,71,839,1471,6857,59569,104441,486847]
primelist :: Int -> [Int]
primelist z = [y | y <- [1..z], mod z y == 0]
main = print [primelist x | x <- liste]
```
The result, which should appear here, should be a list containing 8 lists with the divisors of the elements of `liste`. Instead, the list
```
[[1],[1,3],[1,29],[1,3,29,87]]
```
is printed.
How is this behaviour to be explained? | 2013/06/01 | [
"https://Stackoverflow.com/questions/16877762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2068635/"
] | The Problem is the type declaration `primelist :: Int -> [Int]`. It forces Haskell to use native integers, i.e. 32-Bit integers on a 32-Bit platform. However, if you leave it out, Haskell will infer the function type to be `Integer -> [Integer]`. Integers allow computations with arbitrary precision, but are a little bit slower than native types.
To quote from "[What's the difference between Integer and Int"](http://www.haskell.org/haskellwiki/FAQ#What.27s_the_difference_between_Integer_and_Int.3F) in the Haskell FAQ:
>
> Operations on Int can be much faster than operations on Integer, but
> overflow and underflow **can cause weird bugs**.
>
>
>
Now isn't that the truth. | I am not sure if this will help you, but I also am working through Project Euler to help teach myself Haskell, and I devised the following solution:
```
defacto :: Integer -> Integer -> Integer
defacto x p | x == p = 1
| x`mod`p==0 = defacto (x`div`p) p
| otherwise = x
gpf :: Integer -> Integer
gpf = \x -> prim (x,primes)
prim :: (Integer,[Integer]) -> Integer
prim (x,(p:ps)) | p > x = 1
| (defacto x p) == 1 = p
| otherwise = prim((defacto x p),ps)
n :: Integer
n = 600851475143
```
Here, `defacto` de-factors a prime out of a number, so `defacto 2 12` returns 4 and `defacto 5 14` returns 14. `gpf` is a function to find the greatest prime factor, though it requires a list of primes up to `x` to be in scope. The key component is `prim`, which either returns 1 if the number is smaller than the next prime, returns the first prime in its prime list if x is a perfect power of that prime (i.e. if all other primes smaller than p have been factored out of x), and otherwise performs a recursive call on the defactored x and the truncated prime list. This has the effect of continuously shrinking x while linearly traversing the prime list, so that we need not test any primes that cannot factor into x, and we don't need to keep retesting the same primes on the reduced value of x. Hope this helps you. |
148,291 | I need to implement an audit trail for Add/Edit/Delete on my objects,I'm using an ORM (XPO) for defining my objects etc. I implemented an audit trail object that is triggered on
1. OnSaving
2. OnDeleting
Of the base object, and I store the changes in Audit-AuditTrail (Mast-Det) table, for field changes. etc. using some method services called.
How do you implement audit trail in you OOP code? Please share your insights? Any patterns etc? Best practices etc? Another thing is that how to disable audit when running unit test,since I don't need to audit them but since base object has the code.
Changes to object (edit/add/del) and what field changes need to be audited | 2008/09/29 | [
"https://Stackoverflow.com/questions/148291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Database triggers are the preferred way to go here, if you can.
However, recently I had to do this in client-side code and I ended up writing a class that created a deep (value) copy of the object when it was opened for editing, compared the two objects at save time (using ToString() only) and wrote any changes to an audit table.
Edit: I had an [Audit] attribute on each property I wanted to consider auditable and used reflection to find them, making the method non-specific to the objects being audited. | I know this doesn't answer your question, but for the record, I prefer to handle this type of auditing logic in the database. |
148,291 | I need to implement an audit trail for Add/Edit/Delete on my objects,I'm using an ORM (XPO) for defining my objects etc. I implemented an audit trail object that is triggered on
1. OnSaving
2. OnDeleting
Of the base object, and I store the changes in Audit-AuditTrail (Mast-Det) table, for field changes. etc. using some method services called.
How do you implement audit trail in you OOP code? Please share your insights? Any patterns etc? Best practices etc? Another thing is that how to disable audit when running unit test,since I don't need to audit them but since base object has the code.
Changes to object (edit/add/del) and what field changes need to be audited | 2008/09/29 | [
"https://Stackoverflow.com/questions/148291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Database triggers are the preferred way to go here, if you can.
However, recently I had to do this in client-side code and I ended up writing a class that created a deep (value) copy of the object when it was opened for editing, compared the two objects at save time (using ToString() only) and wrote any changes to an audit table.
Edit: I had an [Audit] attribute on each property I wanted to consider auditable and used reflection to find them, making the method non-specific to the objects being audited. | We have a table that all audit trail entries are stored in. A database trigger is on every table (it's put there by a stored procedure, but that's not relevant to this answer). When a value is changed, the old value is stored in the audit trail. Ours is a little complex in that we also have a look-up table that contains a list of every table we have, and another table that contains every field for each table. This allows us to look up an entry in audit trail, based on what table it's in by ID of that table in the first column. Then we also know exactly what field we are looking for based on the 2nd table's ID. This keeps us from having to store strings for the table name and the field name. To display it, our grids have an "audit trail" button next to the delete button. This opens a popup-grid with the history of that record. We use kendo grids, but none of this implementation is necessary for that. The popup is a bootstrap popup. |
148,291 | I need to implement an audit trail for Add/Edit/Delete on my objects,I'm using an ORM (XPO) for defining my objects etc. I implemented an audit trail object that is triggered on
1. OnSaving
2. OnDeleting
Of the base object, and I store the changes in Audit-AuditTrail (Mast-Det) table, for field changes. etc. using some method services called.
How do you implement audit trail in you OOP code? Please share your insights? Any patterns etc? Best practices etc? Another thing is that how to disable audit when running unit test,since I don't need to audit them but since base object has the code.
Changes to object (edit/add/del) and what field changes need to be audited | 2008/09/29 | [
"https://Stackoverflow.com/questions/148291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Database triggers are the preferred way to go here, if you can.
However, recently I had to do this in client-side code and I ended up writing a class that created a deep (value) copy of the object when it was opened for editing, compared the two objects at save time (using ToString() only) and wrote any changes to an audit table.
Edit: I had an [Audit] attribute on each property I wanted to consider auditable and used reflection to find them, making the method non-specific to the objects being audited. | I come more from the SW side that the DB side, if you create a set of DAOs (Data access objects) that you use for your interaction with the database. I would then insert the audit functionality into the respective functions in the DAOs that need to be trailed.
The database trigger solution is also feasible, it depends where you like to put your functionality, in the DB or in the code
There are a lot of ORM (Object relational Mapping) tools out there that create the DAO layer for you. |
148,291 | I need to implement an audit trail for Add/Edit/Delete on my objects,I'm using an ORM (XPO) for defining my objects etc. I implemented an audit trail object that is triggered on
1. OnSaving
2. OnDeleting
Of the base object, and I store the changes in Audit-AuditTrail (Mast-Det) table, for field changes. etc. using some method services called.
How do you implement audit trail in you OOP code? Please share your insights? Any patterns etc? Best practices etc? Another thing is that how to disable audit when running unit test,since I don't need to audit them but since base object has the code.
Changes to object (edit/add/del) and what field changes need to be audited | 2008/09/29 | [
"https://Stackoverflow.com/questions/148291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I don't know if it will fit seamlessly with your ORM, but i used [Point-in-Time](http://www.simple-talk.com/sql/database-administration/database-design-a-point-in-time-architecture/) database design for an ERP application and really recommend it. You automatically get History and Audit from this architecture, as well as other benefits. | We've implemented a similar solution, using AOP (aspectJ implementation). Using this particular points can be captured and specific operations can be performed.
This can be plugged in and plugged off when we like.
If you really want to do it in the app layer, i would suggest this.
Hope it helps.. |
148,291 | I need to implement an audit trail for Add/Edit/Delete on my objects,I'm using an ORM (XPO) for defining my objects etc. I implemented an audit trail object that is triggered on
1. OnSaving
2. OnDeleting
Of the base object, and I store the changes in Audit-AuditTrail (Mast-Det) table, for field changes. etc. using some method services called.
How do you implement audit trail in you OOP code? Please share your insights? Any patterns etc? Best practices etc? Another thing is that how to disable audit when running unit test,since I don't need to audit them but since base object has the code.
Changes to object (edit/add/del) and what field changes need to be audited | 2008/09/29 | [
"https://Stackoverflow.com/questions/148291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I've done this in Hibernate (another ORM) using an Interceptor for the Session. That way the audit code is seperate from your code. | We have a table that all audit trail entries are stored in. A database trigger is on every table (it's put there by a stored procedure, but that's not relevant to this answer). When a value is changed, the old value is stored in the audit trail. Ours is a little complex in that we also have a look-up table that contains a list of every table we have, and another table that contains every field for each table. This allows us to look up an entry in audit trail, based on what table it's in by ID of that table in the first column. Then we also know exactly what field we are looking for based on the 2nd table's ID. This keeps us from having to store strings for the table name and the field name. To display it, our grids have an "audit trail" button next to the delete button. This opens a popup-grid with the history of that record. We use kendo grids, but none of this implementation is necessary for that. The popup is a bootstrap popup. |
148,291 | I need to implement an audit trail for Add/Edit/Delete on my objects,I'm using an ORM (XPO) for defining my objects etc. I implemented an audit trail object that is triggered on
1. OnSaving
2. OnDeleting
Of the base object, and I store the changes in Audit-AuditTrail (Mast-Det) table, for field changes. etc. using some method services called.
How do you implement audit trail in you OOP code? Please share your insights? Any patterns etc? Best practices etc? Another thing is that how to disable audit when running unit test,since I don't need to audit them but since base object has the code.
Changes to object (edit/add/del) and what field changes need to be audited | 2008/09/29 | [
"https://Stackoverflow.com/questions/148291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Database triggers are the preferred way to go here, if you can.
However, recently I had to do this in client-side code and I ended up writing a class that created a deep (value) copy of the object when it was opened for editing, compared the two objects at save time (using ToString() only) and wrote any changes to an audit table.
Edit: I had an [Audit] attribute on each property I wanted to consider auditable and used reflection to find them, making the method non-specific to the objects being audited. | We've implemented a similar solution, using AOP (aspectJ implementation). Using this particular points can be captured and specific operations can be performed.
This can be plugged in and plugged off when we like.
If you really want to do it in the app layer, i would suggest this.
Hope it helps.. |
148,291 | I need to implement an audit trail for Add/Edit/Delete on my objects,I'm using an ORM (XPO) for defining my objects etc. I implemented an audit trail object that is triggered on
1. OnSaving
2. OnDeleting
Of the base object, and I store the changes in Audit-AuditTrail (Mast-Det) table, for field changes. etc. using some method services called.
How do you implement audit trail in you OOP code? Please share your insights? Any patterns etc? Best practices etc? Another thing is that how to disable audit when running unit test,since I don't need to audit them but since base object has the code.
Changes to object (edit/add/del) and what field changes need to be audited | 2008/09/29 | [
"https://Stackoverflow.com/questions/148291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I don't know if it will fit seamlessly with your ORM, but i used [Point-in-Time](http://www.simple-talk.com/sql/database-administration/database-design-a-point-in-time-architecture/) database design for an ERP application and really recommend it. You automatically get History and Audit from this architecture, as well as other benefits. | I come more from the SW side that the DB side, if you create a set of DAOs (Data access objects) that you use for your interaction with the database. I would then insert the audit functionality into the respective functions in the DAOs that need to be trailed.
The database trigger solution is also feasible, it depends where you like to put your functionality, in the DB or in the code
There are a lot of ORM (Object relational Mapping) tools out there that create the DAO layer for you. |
148,291 | I need to implement an audit trail for Add/Edit/Delete on my objects,I'm using an ORM (XPO) for defining my objects etc. I implemented an audit trail object that is triggered on
1. OnSaving
2. OnDeleting
Of the base object, and I store the changes in Audit-AuditTrail (Mast-Det) table, for field changes. etc. using some method services called.
How do you implement audit trail in you OOP code? Please share your insights? Any patterns etc? Best practices etc? Another thing is that how to disable audit when running unit test,since I don't need to audit them but since base object has the code.
Changes to object (edit/add/del) and what field changes need to be audited | 2008/09/29 | [
"https://Stackoverflow.com/questions/148291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | We've implemented a similar solution, using AOP (aspectJ implementation). Using this particular points can be captured and specific operations can be performed.
This can be plugged in and plugged off when we like.
If you really want to do it in the app layer, i would suggest this.
Hope it helps.. | We have a table that all audit trail entries are stored in. A database trigger is on every table (it's put there by a stored procedure, but that's not relevant to this answer). When a value is changed, the old value is stored in the audit trail. Ours is a little complex in that we also have a look-up table that contains a list of every table we have, and another table that contains every field for each table. This allows us to look up an entry in audit trail, based on what table it's in by ID of that table in the first column. Then we also know exactly what field we are looking for based on the 2nd table's ID. This keeps us from having to store strings for the table name and the field name. To display it, our grids have an "audit trail" button next to the delete button. This opens a popup-grid with the history of that record. We use kendo grids, but none of this implementation is necessary for that. The popup is a bootstrap popup. |
148,291 | I need to implement an audit trail for Add/Edit/Delete on my objects,I'm using an ORM (XPO) for defining my objects etc. I implemented an audit trail object that is triggered on
1. OnSaving
2. OnDeleting
Of the base object, and I store the changes in Audit-AuditTrail (Mast-Det) table, for field changes. etc. using some method services called.
How do you implement audit trail in you OOP code? Please share your insights? Any patterns etc? Best practices etc? Another thing is that how to disable audit when running unit test,since I don't need to audit them but since base object has the code.
Changes to object (edit/add/del) and what field changes need to be audited | 2008/09/29 | [
"https://Stackoverflow.com/questions/148291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I come more from the SW side that the DB side, if you create a set of DAOs (Data access objects) that you use for your interaction with the database. I would then insert the audit functionality into the respective functions in the DAOs that need to be trailed.
The database trigger solution is also feasible, it depends where you like to put your functionality, in the DB or in the code
There are a lot of ORM (Object relational Mapping) tools out there that create the DAO layer for you. | We have a table that all audit trail entries are stored in. A database trigger is on every table (it's put there by a stored procedure, but that's not relevant to this answer). When a value is changed, the old value is stored in the audit trail. Ours is a little complex in that we also have a look-up table that contains a list of every table we have, and another table that contains every field for each table. This allows us to look up an entry in audit trail, based on what table it's in by ID of that table in the first column. Then we also know exactly what field we are looking for based on the 2nd table's ID. This keeps us from having to store strings for the table name and the field name. To display it, our grids have an "audit trail" button next to the delete button. This opens a popup-grid with the history of that record. We use kendo grids, but none of this implementation is necessary for that. The popup is a bootstrap popup. |
148,291 | I need to implement an audit trail for Add/Edit/Delete on my objects,I'm using an ORM (XPO) for defining my objects etc. I implemented an audit trail object that is triggered on
1. OnSaving
2. OnDeleting
Of the base object, and I store the changes in Audit-AuditTrail (Mast-Det) table, for field changes. etc. using some method services called.
How do you implement audit trail in you OOP code? Please share your insights? Any patterns etc? Best practices etc? Another thing is that how to disable audit when running unit test,since I don't need to audit them but since base object has the code.
Changes to object (edit/add/del) and what field changes need to be audited | 2008/09/29 | [
"https://Stackoverflow.com/questions/148291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I don't know if it will fit seamlessly with your ORM, but i used [Point-in-Time](http://www.simple-talk.com/sql/database-administration/database-design-a-point-in-time-architecture/) database design for an ERP application and really recommend it. You automatically get History and Audit from this architecture, as well as other benefits. | We have a table that all audit trail entries are stored in. A database trigger is on every table (it's put there by a stored procedure, but that's not relevant to this answer). When a value is changed, the old value is stored in the audit trail. Ours is a little complex in that we also have a look-up table that contains a list of every table we have, and another table that contains every field for each table. This allows us to look up an entry in audit trail, based on what table it's in by ID of that table in the first column. Then we also know exactly what field we are looking for based on the 2nd table's ID. This keeps us from having to store strings for the table name and the field name. To display it, our grids have an "audit trail" button next to the delete button. This opens a popup-grid with the history of that record. We use kendo grids, but none of this implementation is necessary for that. The popup is a bootstrap popup. |
5,526,625 | I am trying to start from scratch a website that has similar functionality to grubhub.com. Fundamentally, a website where restaurant owners can come on to the website, post their menu and most importantly customers will be able to order instant delivery online which sends an email or something to the restaurant.
The problem is I have no idea where to start. I have been trying to figure out for a long time. I am familiar with HTML, CSS and somewhat familiar with PHP and MYSQL. So my question is how should I go about starting this project, how do I use the languages and where. Also, should I create a CMS from scratch or just use premade ones. If so, are there any recommendations? | 2011/04/02 | [
"https://Stackoverflow.com/questions/5526625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/689355/"
] | I would use a premade CMS, unless i had a very solid reason not to (they did not have the functionality that i wanted). This would save you LOTS of time.
If you are familiar with PHP, MySQL, CSS and the likes, starting should not be such a problem. You first design how you want your program to work, think of the database tables and how functionality applies to each.
Then, you would create the appropriate classes that handle database models and maybe even use a template system that handles the views. Since everything starts with an index page, you may want to start there and include more and more pages as you develop more and more things.
Now, just start :) | You should definitely not build yourself a CMS from scratch. This will take a very long time and will definitely lead HUGE security holes and total lack of scalability if you don't know what you are doing.
Take a look at this question:
<https://softwareengineering.stackexchange.com/questions/46716/what-should-a-developer-know-before-building-a-public-web-site>
Granted, you shouldn't need or can't know absolutely everything before building a website, but you should at least have a very solid basis.
Specially since there is so much free open source software that with little tweaking should cover your needs perfectly, it makes absolutely no sense re-inventing the wheel.
I would say go for an opensource project that suits you.
Good luck! |
5,526,625 | I am trying to start from scratch a website that has similar functionality to grubhub.com. Fundamentally, a website where restaurant owners can come on to the website, post their menu and most importantly customers will be able to order instant delivery online which sends an email or something to the restaurant.
The problem is I have no idea where to start. I have been trying to figure out for a long time. I am familiar with HTML, CSS and somewhat familiar with PHP and MYSQL. So my question is how should I go about starting this project, how do I use the languages and where. Also, should I create a CMS from scratch or just use premade ones. If so, are there any recommendations? | 2011/04/02 | [
"https://Stackoverflow.com/questions/5526625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/689355/"
] | You should consider that developing web applications without experience can lead to severe security issues.
I would recommend using a premade CMS if it provides the features that you need for your application (or makes it possible to script additional features). If that is not the case, maybe consider using a web application framework. | You should definitely not build yourself a CMS from scratch. This will take a very long time and will definitely lead HUGE security holes and total lack of scalability if you don't know what you are doing.
Take a look at this question:
<https://softwareengineering.stackexchange.com/questions/46716/what-should-a-developer-know-before-building-a-public-web-site>
Granted, you shouldn't need or can't know absolutely everything before building a website, but you should at least have a very solid basis.
Specially since there is so much free open source software that with little tweaking should cover your needs perfectly, it makes absolutely no sense re-inventing the wheel.
I would say go for an opensource project that suits you.
Good luck! |
3,232,098 | I am trying to understand a step in the following proof of completeness of $L^p$ in [Stein-Shakarchi's Functional Analysis](http://assets.press.princeton.edu/chapters/s9627.pdf). (See the proof on page 5 of the link or at the end of this post.)
At the beginning of the proof, it is said that
>
> Let $\{f\_n\}\_{n=1}^\infty$ be a Cauchy sequence in $L^p$, and consider a subsequence $\{f\_{n\_k}\}\_{k=1}^\infty$ of $\{f\_n\}\_{n=1}^\infty$ with the following property $\|f\_{n\_{k+1}}-f\_{n\_k}\|\le 2^{-k}$ for all $k\geq 1$.
>
>
>
**Question:** Why can the sequence be considered as it is?
On a [YouTube video](https://youtu.be/BWnV8fBlDQQ?t=870), it explains about a similar subsequence.
I still don't understand why for $n,m>n\_k$ $\Vert f\_{n}-f\_{m}\Vert\_p\implies \Vert f\_{n\_k}-f\_{n\_{k+1}}\Vert\_p$, thus an increasing subsequence. Why is it justified to make $n$ to depend on $k$, $n\_k$?
---
[](https://i.stack.imgur.com/D3NG2.png)
[](https://i.stack.imgur.com/t17lP.png)
[](https://i.stack.imgur.com/etwMx.png) | 2019/05/19 | [
"https://math.stackexchange.com/questions/3232098",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/459663/"
] | The authors mention at the beginning of the proof that
>
> The argument is essentially the same as for $L^1$ (or $L^2$); see Section 2, Chapter 2 and Section 1, Chapter 4 in [Book III](https://press.princeton.edu/titles/8008.html).
>
>
>
It is said clearly there (see also a snapshot at the end) that
>
> The existence of such subsequence is guaranteed by the fact that $\|f\_{n}-f\_{m}\|\leq \epsilon$ whenever $n,m\geq N(\epsilon)$, so that it suffices to take $n\_k=N(2^{-k})$.
>
>
>
[Added for elaboration.]
There exists an integer $N(2^{-1})>0$ such that **for all** $n,m\geq N(2^{-1})$,
$$
\|f\_{n}-f\_{m}\|\leq 2^{-1}\tag{1}.
$$
There exists an integer $N(2^{-2})>N(2^{-1})$ such that **for all** $n,m\geq N(2^{-2})$,
$$
\|f\_{n}-f\_{m}\|\leq 2^{-2}\tag{2}.
$$
There exists an integer $N(2^{-3})>N(2^{-2})$ such that **for all** $n,m\geq N(2^{-3})$,
$$
\|f\_{n}-f\_{m}\|\leq 2^{-3}\tag{2}.
$$
... so on and so forth.
Now, let $n\_1=N(2^{-1})$, $n\_2=N(2^{-2})$, $n\_3=N(2^{-3})$, $\cdots$.
Since $n\_1,n\_2\geq N(2^{-1})$, we have by (1)
$$
\|f\_{n\_2}-f\_{n\_1}\|\leq 2^{-1}.
$$
Since $n\_2,n\_3\geq N(2^{-2})$, we have by (2)
$$
\|f\_{n\_3}-f\_{n\_2}\|\leq 2^{-2}.
$$
Since $n\_3,n\_4\geq N(2^{-3})$, we have by (3)
$$
\|f\_{n\_4}-f\_{n\_3}\|\leq 2^{-3}.
$$
... so on and so forth.
---
The following is a snapshot of the beginning of the proof for completeness of $L^1$ in Stein-Shakarchi's Book III (page 70 Theorem 2.2).
>
> [](https://i.stack.imgur.com/cgCtg.png)
>
>
> | If $\{f\_n\}\_n$ is Cauchy, for each $k\in\Bbb N$ we can find an $N\_k$ (depending on the $k$ we just chose) such that
$$ \|f\_n - f\_m\| < 2^{-k} \quad\text{ whenever } n,m\geq N\_k.$$
For $k+1$, we likewise get
$$ \|f\_n - f\_m\| < 2^{-k-1} \quad\text{ whenever } n,m\geq N\_{k+1}.$$
Now, both inequalities will hold for $n,m \geq \max\{N\_k,N\_{k+1}\}$, so we can choose $N\_{k+1} > N\_k$, and similarly we can choose an $N\_{k+2} > N\_{k+1} > N\_{k}$ for $2^{-k-2}$ so that
$$\|f\_{N\_k} - f\_{N\_{k+1}}\| < 2^{-k}\quad\text{and}\quad \|f\_{N\_{k+1}} - f\_{N\_{k+2}}\| < 2^{-k-1}$$
by choosing $n = N\_k$ and $m = N\_{k+1}$, etc in the first inequalities above. |
10,564,722 | I'm new to PHP, I started about 3 weeks ago.
I have a string, which is used with $\_POST to pass it to another page, the second page uses $\_GET to get these url and split it as desired.
My problem is that, in my first page I use a String, and I want to encrypt it, so that I can pass it as a plan text. In the second page I must decrypt it and get it as an array.
So is there any encryption method or function I can use which is compatible with $\_POST ( so I can send it to another page ) and decrypt it as an array ?
I need this method, because the second page is actually connecting to website and is a payment method. So i don't want users to manually edit the url and lower the amount of $ for the product they get.
tnx for your help. | 2012/05/12 | [
"https://Stackoverflow.com/questions/10564722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1391170/"
] | You're thinking about this wrong. You NEVER trust information coming from the user's side.
For example, if your user sends a form that says what item they want, DO NOT include the price in the form. Instead, get the price from the server (database), where it can be trusted. | Despite not fully understanding what you're trying to achieve, you can use base64 encoding:
```
$encoded_string = base64_encode ($string);
$decoded_string = base64_decode ($encoded_string);
``` |
10,564,722 | I'm new to PHP, I started about 3 weeks ago.
I have a string, which is used with $\_POST to pass it to another page, the second page uses $\_GET to get these url and split it as desired.
My problem is that, in my first page I use a String, and I want to encrypt it, so that I can pass it as a plan text. In the second page I must decrypt it and get it as an array.
So is there any encryption method or function I can use which is compatible with $\_POST ( so I can send it to another page ) and decrypt it as an array ?
I need this method, because the second page is actually connecting to website and is a payment method. So i don't want users to manually edit the url and lower the amount of $ for the product they get.
tnx for your help. | 2012/05/12 | [
"https://Stackoverflow.com/questions/10564722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1391170/"
] | You're thinking about this wrong. You NEVER trust information coming from the user's side.
For example, if your user sends a form that says what item they want, DO NOT include the price in the form. Instead, get the price from the server (database), where it can be trusted. | What you probably want to do is pass the contents of the users cart (i.e. the items he'd like to order) to the payment site.
Therefore, you should create a form like:
```
<form action="URL/to/paymentPage.php" method="post">
<!-- Item 1 -->
<input type="hidden" name="items[0]" value="productID1"/>
<input type="hidden" name="quantity[0]" value="quantity1"/>
<!-- Item 2 -->
<input type="hidden" name="items[1]" value="productID2"/>
<input type="hidden" name="quantity[1]" value="quantity2"/>
<!-- ... -->
<!-- Item n -->
<input type="hidden" name="items[n]" value="productIDn"/>
<input type="hidden" name="quantity[n]" value="quantityn"/>
<input type="submit" value="Order"/>
</form>
```
On the server in the file "URL/to/paymentPage.php" you can access the items using the following code:
```
<?php
$items = $_POST['items']; // Array of items ..
$quantities = $_POST['quantity']; // The array of quantities for each item ..
// Calculate the total price ..
$totalPrice = 0;
foreach($items as $idx => $itemID) {
if($quantities[$idx]>0) {
totalPrice += getPriceFromDB($itemID) * $quantities[$idx];
}
}
echo 'Total Price to pay: '.$totalPrice;
?>
```
where the function getPriceFromDB actually retrieves the price for the item/product with the id $itemID from your database or elsewhere... :)
However, the user items are usually stored in the session, and, therefore, there is no need to submit the again.. ;) |
10,564,722 | I'm new to PHP, I started about 3 weeks ago.
I have a string, which is used with $\_POST to pass it to another page, the second page uses $\_GET to get these url and split it as desired.
My problem is that, in my first page I use a String, and I want to encrypt it, so that I can pass it as a plan text. In the second page I must decrypt it and get it as an array.
So is there any encryption method or function I can use which is compatible with $\_POST ( so I can send it to another page ) and decrypt it as an array ?
I need this method, because the second page is actually connecting to website and is a payment method. So i don't want users to manually edit the url and lower the amount of $ for the product they get.
tnx for your help. | 2012/05/12 | [
"https://Stackoverflow.com/questions/10564722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1391170/"
] | What you probably want to do is pass the contents of the users cart (i.e. the items he'd like to order) to the payment site.
Therefore, you should create a form like:
```
<form action="URL/to/paymentPage.php" method="post">
<!-- Item 1 -->
<input type="hidden" name="items[0]" value="productID1"/>
<input type="hidden" name="quantity[0]" value="quantity1"/>
<!-- Item 2 -->
<input type="hidden" name="items[1]" value="productID2"/>
<input type="hidden" name="quantity[1]" value="quantity2"/>
<!-- ... -->
<!-- Item n -->
<input type="hidden" name="items[n]" value="productIDn"/>
<input type="hidden" name="quantity[n]" value="quantityn"/>
<input type="submit" value="Order"/>
</form>
```
On the server in the file "URL/to/paymentPage.php" you can access the items using the following code:
```
<?php
$items = $_POST['items']; // Array of items ..
$quantities = $_POST['quantity']; // The array of quantities for each item ..
// Calculate the total price ..
$totalPrice = 0;
foreach($items as $idx => $itemID) {
if($quantities[$idx]>0) {
totalPrice += getPriceFromDB($itemID) * $quantities[$idx];
}
}
echo 'Total Price to pay: '.$totalPrice;
?>
```
where the function getPriceFromDB actually retrieves the price for the item/product with the id $itemID from your database or elsewhere... :)
However, the user items are usually stored in the session, and, therefore, there is no need to submit the again.. ;) | Despite not fully understanding what you're trying to achieve, you can use base64 encoding:
```
$encoded_string = base64_encode ($string);
$decoded_string = base64_decode ($encoded_string);
``` |
12,456,578 | Hi I have a table with name **test**. it got 7 columns **id , a , b , c , d , e , f.** All this columns contains either 1 or 0. Now i want make a query where i can choose only those columns whose value is 1.
Something like this:
```
select (condition) from test where id = 5;
```
because i have a hotel table with 50 columns out of which 11 columns contains either 1 or 0 representing the facilities of the hotel. I want to make a query which just tells what are the facilities of the hotel.
Any help would be great. | 2012/09/17 | [
"https://Stackoverflow.com/questions/12456578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1529342/"
] | Something like this perhaps? You may want to customize the behavior of the dropdown, but this shows the basic logic of handling the click events and preventing default behaviour (i.e. following links) if the menu isn't open:
```
$(function() {
$('#main-menu a').click(function(e) {
var listItem = $(this).closest('li');
if (!listItem.is('.open')) {
// Opening drop-down logic here. e.g. adding 'open' class to <li>
e.preventDefault();
listItem.addClass('open');
}
// Otherwise the default behaviour of the event (clicking the link) will be unaffected
});
});
``` | i have done complete bins for above issue also placed demo link here.
**Demo:** <http://codebins.com/bin/4ldqp72>
**HTML**
```
<ul id="main-menu">
<li>
<a href="#">
Link
</a>
</li>
<li>
<a href="#">
Link
</a>
</li>
<li>
<a href="#">
Link
</a>
<ul class="sub-menu">
<li>
<a href="#">
Sub Link
</a>
</li>
<li>
<a href="#">
Sub Link
</a>
</li>
<li>
<a href="#">
Sub Link
</a>
</li>
</ul>
</li>
<li>
<a href="#">
Link
</a>
</li>
<li>
<a href="#">
Link
</a>
</li>
</ul>
```
**JQuery**
```
$(function() {
$('ul a').click(function(e) {
$('#main-menu li').removeClass('open');
e.preventDefault();
$(this).closest('li').addClass("open");
var pos = $(this).closest('li.open').offset();
$(this).closest('li.open').find("ul.sub-menu").css('top', pos.top + 'px');
});
});
```
**CSS**
```
#main-menu{
list-style:none;
margin:2px;
padding:2px;
}
li{
border:1px solid #333;
background:#ebcdff;
text-align:center;
width:100px;
}
li:hover{
background:#abcdfd;
}
li:hover a{
color:#ff3322;
}
li a{
text-decoration:none;
color:#2466ff;
}
li.open {
background:#abcdfd;
}
li.open a{
text-decoration:none;
color:#ff3322;
}
ul.sub-menu{
list-style:none;
display:none;
}
li.open > ul{
position:absolute;
left:70px;
display:block;
}
```
**Demo:** <http://codebins.com/bin/4ldqp72> |
34,019,675 | As in earlier version of symfony we user to generate a CRUD with the following command
```
$ php app/console generate:doctrine:crud
```
But in symfony 3.0.0 i could not find the app/console, even I tried checking the documentation for the same but was not able to find anything.
Link to document <http://symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/generate_doctrine_crud.html> | 2015/12/01 | [
"https://Stackoverflow.com/questions/34019675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1278758/"
] | Use bin/console instead of app/console.
However, Symfony 3.0 was just released yesterday. <http://symfony.com/blog/symfony-3-0-0-released>. Most of the core concepts between S2 and S3 are the same but the implementations have changed significantly. For example, the form components work differently. Most of the current documentation is S2 specific and will not work under S3. Furthermore, many 3rd party bundles such as FOSUserBundle will not currently work under S3.
So, if want to use bleeding edge software then roll up your sleeves and start reading the upgrade files as well as the blog.
If you just want to make applications then start over with S2.8.
Something else that will be really fun. The 'current' documents now point to S3. So most of the S2 links will now point to incorrect information. | For Symfony 3 console is moved inside bin folder. So command should be
```
$ php bin/console generate:doctrine:crud
``` |
28,430,749 | I have a C++ classe in a .h file like this:
```
#ifndef __GLWidget_h__
#define __GLWidget_h__
class PivotShape
{
// This is allowed
void do_something() { std::cout << "Doing something\n"; }
// This is not allowed
void do_something_else();
}
// This is not allowed
void PivotShape::do_something_else()
{
std::cout << "Doing something else\n";
}
#endif
```
If I add methods inside the class declaration everything seems fine. But if I add methods outside of the class declaration, I get errors like this:
```
/usr/share/qt4/bin/moc GLWidget.h > GLWidget_moc.cpp
/programs/gcc-4.6.3/installation/bin/g++ -W -Wall -g -c -I./ -I/usr/include/qt4 GLWidget_moc.cpp
/programs/gcc-4.6.3/installation/bin/g++ main.o GLState.o GLWidget.o MainWindow_moc.o GLWidget_moc.o -L/usr/lib/x86_64-linux-gnu -lQtGui -lQtOpenGL -lQtCore -lGLU -lGL -lm -ldl -o main
GLWidget.o: In function `std::iterator_traits<float const*>::iterator_category std::__iterator_category<float const*>(float const* const&)':
/home/<user>/<dir>/<dir>/<dir>/<dir>/<dir>/GLWidget.h:141: multiple definition of `PivotShape::do_someting_else()'
main.o:/home/<user>/<dir>/<dir>/<dir>/<dir>/<dir>/GLWidget.h:141: first defined here
```
I think the duplication is being caused by this snippet in the Make file. I think the .h files are being converted to \_moc.cpp files and this is allowing the multiple inclusions:
```
# Define linker
LINKER = /programs/gcc-4.6.3/installation/bin/g++
MOCSRCS = $(QTHEADERS:.h=_moc.cpp)
# Define all object files to be the same as CPPSRCS but with all the .cpp
# suffixes replaced with .o
OBJ = $(CPPSRCS:.cpp=.o) $(MOCSRCS:.cpp=.o)
```
Is this the problem? If so, how can I fix it? If not, what's going on?
I thought it was illegal in C++ to include class methods inside the body of the class declaration. If this is legal, then it seems like an easy way to solve the problem. Is this legal?
Edit:
I forgot to mention that I had already discovered that declaring the methods as `inline` works, but I was wondering how to avoid the duplication. | 2015/02/10 | [
"https://Stackoverflow.com/questions/28430749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1993403/"
] | You're breaking the One Definition Rule; defining the function in the header means there's a definition in every translation unit that includes the header, and you're usually only allowed a single definition in the program.
Options:
* Move the function definition into a source file, so there's just one definition; or
* Add `inline` to the function definition, to relax the rule and allow multiple definitions; or
* Define the function inside the class, which makes it implicitly inline. (To answer your final question, yes that is legal.)
Also, don't use [reserved names](https://stackoverflow.com/questions/228783) like `__GLWidget_h__`. | Define the function in a source file or use `inline` to define it in the header file, outside the class definition.
Note that you can still define it inside the class definition without the `inline` keyword.
Related: [Member function definition](https://stackoverflow.com/questions/4837267/member-function-definition) |
5,939,578 | I would like to use shared memory between several processes, and would like to be able to keep using raw pointers (and stl containers).
For this purpose, I am using shared memory mapped at a *fixed address*:
```
segment = new boost::interprocess::managed_shared_memory(
boost::interprocess::open_or_create,
"MySegmentName",
1048576, // alloc size
(void *)0x400000000LL // fixed address
);
```
What is a good strategy for choosing this fixed address? For example, should I just use a pretty high number to reduce the chance that I run out of heap space? | 2011/05/09 | [
"https://Stackoverflow.com/questions/5939578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680410/"
] | This is a hard problem. If you are forking a single program to create children, and only the parent and the children will use the memory segment, just be sure to map it before you fork. The children will automatically inherit the mapping from their parent and there's no need to use a fixed address.
If you aren't, then the first thing to consider is whether you really need to use raw STL containers instead of the boost interprocess containers. That you're already using boost interprocess to allocate the shared memory segment suggests you don't have any problem using boost, so the only advantage I can think of to using STL containers would be so you don't have to port existing code. Keep in mind that for it to work with fixed addresses, the containers *and what they contain pointers to* (assuming you're working with containers of pointers) will need to be kept in the shared memory space.
If you're certain that it's what you want, you'll have to figure out some method for them to negotiate an address. Keep in mind that the **OS is allowed to reject your desired fixed memory address**. It will reject an address if the page at that address has already been mapped into memory or allocated. Because different programs will have allocated different amounts of memory at different times, which pages are available and which are unavailable will vary across your programs.
So you need for the programs to gain consensus on a memory address. This means that several addresses might have to be tried and rejected. If it's possible that sometime after startup a new program will become interested, **the search for consensus will have to start over again**. The algorithm would look something like this:
1. Program A proposes memory address X to all other programs.
2. The other programs respond with true or false to indicate whether the memory mapping at address X succeeded.
3. If program A receives any false responses, goto #1.
4. Program A sends a message to the other programs letting them know the address has been validated and maybe used.
5. If a new app becomes interested in the data, it must notify program A it would like an address.
6. Program A then has to tell all the other programs to stop using the data and goto #1.
To come up with what addresses A should propose, you could have A map a non-fixed memory segment, see what address it's mapped at, and propose that address. If it's unsatisfactory, map another segment and propose it instead. You will need to unmap the segments at some point, but you can't unmap them right away because if you unmap then remap a segment of the same size chances are the OS will give you the same address back over and over. **Keep in mind that you may never reach consensus**; there's no guarantee that there's a large enough segment at a common location across all the processes. This could happen if your programs all independently use almost all memory, say if they are backed up by a ton of swap (though if you care enough about performance to use shared memory hopefully you are avoiding swap).
All of the above assumes you're in a relatively constrained address space. **If you're on 64-bit, this could work**. Most computers' RAM + swap will be far less than what's allowed by 64-bits, so you could put map the memory at a very far out fixed address that all processes are unlikely to have mapped already. I suggest at least 2^48, since current 64-bit x86 processors don't each beyond that range (despite pointers being 64-bits, you can only plug in as much RAM as allowed by 48-bits, still a ton at the time of this writing). Although there's no reason a smart heap allocator couldn't take advantage of the vastness of the address space to reduce its bookkeeping work, so to be truly robust you would still need to build consensus. Keep in mind that you will at least want the address to be configurable -- even if we don't have that much memory anytime soon, between now and then someone else might have the same idea and pick your address.
To do the bidirectional communication you could use any of sockets, pipes, or another shared memory segment. Your OS may provide other forms of IPC. But strongly consider that you are probably now introducing more complexity than you would have to deal with if you just used the boost interprocess containers ;) | Read the address from a configuration file. That will allow easy experimentation, and make it easy to change the address as the circumstances change. |
5,939,578 | I would like to use shared memory between several processes, and would like to be able to keep using raw pointers (and stl containers).
For this purpose, I am using shared memory mapped at a *fixed address*:
```
segment = new boost::interprocess::managed_shared_memory(
boost::interprocess::open_or_create,
"MySegmentName",
1048576, // alloc size
(void *)0x400000000LL // fixed address
);
```
What is a good strategy for choosing this fixed address? For example, should I just use a pretty high number to reduce the chance that I run out of heap space? | 2011/05/09 | [
"https://Stackoverflow.com/questions/5939578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680410/"
] | Read the address from a configuration file. That will allow easy experimentation, and make it easy to change the address as the circumstances change. | Don't use hard-coded absolute addresses as shared memory area for security reasons, even when you don't uses forks or threads. This bypasses all ASLR protections. It enables any attacker predictable locations in the process' address space. It is pretty easy to search for such hard-coded pointers in a binary.
You've been choosen by <http://reversingonwindows.blogspot.sg/2013/12/hardcoded-pointers.html> as example how to make software less secure, bypassing ASLR.
The 2nd bad example is in the [boost library](http://www.boost.org/doc/libs/1_47_0/doc/html/interprocess/sharedmemorybetweenprocesses.html#interprocess.sharedmemorybetweenprocesses.mapped_region.mapped_region_fixed_address_mapping).
The address space needs to be negotiated between the communicating parties at run-time. |
5,939,578 | I would like to use shared memory between several processes, and would like to be able to keep using raw pointers (and stl containers).
For this purpose, I am using shared memory mapped at a *fixed address*:
```
segment = new boost::interprocess::managed_shared_memory(
boost::interprocess::open_or_create,
"MySegmentName",
1048576, // alloc size
(void *)0x400000000LL // fixed address
);
```
What is a good strategy for choosing this fixed address? For example, should I just use a pretty high number to reduce the chance that I run out of heap space? | 2011/05/09 | [
"https://Stackoverflow.com/questions/5939578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680410/"
] | Read the address from a configuration file. That will allow easy experimentation, and make it easy to change the address as the circumstances change. | My solution:
The initialising program allows the system to select an appropriate segment address. This address is written to disc and retrieved for use by subsequent programs as required.
Caveats:
I am using 64 bit fedora 21 with Kdevelop 4.7 and find that 'void\*' is 64 bits long. Writing to disc of the segment head address involves
sprintf(bu, "%p", pointer); and writing a text file:
Recovery reads this file and decodes the hex number as a 'long long' value. This is returned to the caller where it is cast as (void\*)
I have also found that grouping all the access routines into a single folder
above the level of the individual processes (each as a project in its own right) has helped save my sanity at the expense of a single aberrant '#include' in the process files
David N Laine |
5,939,578 | I would like to use shared memory between several processes, and would like to be able to keep using raw pointers (and stl containers).
For this purpose, I am using shared memory mapped at a *fixed address*:
```
segment = new boost::interprocess::managed_shared_memory(
boost::interprocess::open_or_create,
"MySegmentName",
1048576, // alloc size
(void *)0x400000000LL // fixed address
);
```
What is a good strategy for choosing this fixed address? For example, should I just use a pretty high number to reduce the chance that I run out of heap space? | 2011/05/09 | [
"https://Stackoverflow.com/questions/5939578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680410/"
] | This is a hard problem. If you are forking a single program to create children, and only the parent and the children will use the memory segment, just be sure to map it before you fork. The children will automatically inherit the mapping from their parent and there's no need to use a fixed address.
If you aren't, then the first thing to consider is whether you really need to use raw STL containers instead of the boost interprocess containers. That you're already using boost interprocess to allocate the shared memory segment suggests you don't have any problem using boost, so the only advantage I can think of to using STL containers would be so you don't have to port existing code. Keep in mind that for it to work with fixed addresses, the containers *and what they contain pointers to* (assuming you're working with containers of pointers) will need to be kept in the shared memory space.
If you're certain that it's what you want, you'll have to figure out some method for them to negotiate an address. Keep in mind that the **OS is allowed to reject your desired fixed memory address**. It will reject an address if the page at that address has already been mapped into memory or allocated. Because different programs will have allocated different amounts of memory at different times, which pages are available and which are unavailable will vary across your programs.
So you need for the programs to gain consensus on a memory address. This means that several addresses might have to be tried and rejected. If it's possible that sometime after startup a new program will become interested, **the search for consensus will have to start over again**. The algorithm would look something like this:
1. Program A proposes memory address X to all other programs.
2. The other programs respond with true or false to indicate whether the memory mapping at address X succeeded.
3. If program A receives any false responses, goto #1.
4. Program A sends a message to the other programs letting them know the address has been validated and maybe used.
5. If a new app becomes interested in the data, it must notify program A it would like an address.
6. Program A then has to tell all the other programs to stop using the data and goto #1.
To come up with what addresses A should propose, you could have A map a non-fixed memory segment, see what address it's mapped at, and propose that address. If it's unsatisfactory, map another segment and propose it instead. You will need to unmap the segments at some point, but you can't unmap them right away because if you unmap then remap a segment of the same size chances are the OS will give you the same address back over and over. **Keep in mind that you may never reach consensus**; there's no guarantee that there's a large enough segment at a common location across all the processes. This could happen if your programs all independently use almost all memory, say if they are backed up by a ton of swap (though if you care enough about performance to use shared memory hopefully you are avoiding swap).
All of the above assumes you're in a relatively constrained address space. **If you're on 64-bit, this could work**. Most computers' RAM + swap will be far less than what's allowed by 64-bits, so you could put map the memory at a very far out fixed address that all processes are unlikely to have mapped already. I suggest at least 2^48, since current 64-bit x86 processors don't each beyond that range (despite pointers being 64-bits, you can only plug in as much RAM as allowed by 48-bits, still a ton at the time of this writing). Although there's no reason a smart heap allocator couldn't take advantage of the vastness of the address space to reduce its bookkeeping work, so to be truly robust you would still need to build consensus. Keep in mind that you will at least want the address to be configurable -- even if we don't have that much memory anytime soon, between now and then someone else might have the same idea and pick your address.
To do the bidirectional communication you could use any of sockets, pipes, or another shared memory segment. Your OS may provide other forms of IPC. But strongly consider that you are probably now introducing more complexity than you would have to deal with if you just used the boost interprocess containers ;) | Don't use hard-coded absolute addresses as shared memory area for security reasons, even when you don't uses forks or threads. This bypasses all ASLR protections. It enables any attacker predictable locations in the process' address space. It is pretty easy to search for such hard-coded pointers in a binary.
You've been choosen by <http://reversingonwindows.blogspot.sg/2013/12/hardcoded-pointers.html> as example how to make software less secure, bypassing ASLR.
The 2nd bad example is in the [boost library](http://www.boost.org/doc/libs/1_47_0/doc/html/interprocess/sharedmemorybetweenprocesses.html#interprocess.sharedmemorybetweenprocesses.mapped_region.mapped_region_fixed_address_mapping).
The address space needs to be negotiated between the communicating parties at run-time. |
5,939,578 | I would like to use shared memory between several processes, and would like to be able to keep using raw pointers (and stl containers).
For this purpose, I am using shared memory mapped at a *fixed address*:
```
segment = new boost::interprocess::managed_shared_memory(
boost::interprocess::open_or_create,
"MySegmentName",
1048576, // alloc size
(void *)0x400000000LL // fixed address
);
```
What is a good strategy for choosing this fixed address? For example, should I just use a pretty high number to reduce the chance that I run out of heap space? | 2011/05/09 | [
"https://Stackoverflow.com/questions/5939578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680410/"
] | This is a hard problem. If you are forking a single program to create children, and only the parent and the children will use the memory segment, just be sure to map it before you fork. The children will automatically inherit the mapping from their parent and there's no need to use a fixed address.
If you aren't, then the first thing to consider is whether you really need to use raw STL containers instead of the boost interprocess containers. That you're already using boost interprocess to allocate the shared memory segment suggests you don't have any problem using boost, so the only advantage I can think of to using STL containers would be so you don't have to port existing code. Keep in mind that for it to work with fixed addresses, the containers *and what they contain pointers to* (assuming you're working with containers of pointers) will need to be kept in the shared memory space.
If you're certain that it's what you want, you'll have to figure out some method for them to negotiate an address. Keep in mind that the **OS is allowed to reject your desired fixed memory address**. It will reject an address if the page at that address has already been mapped into memory or allocated. Because different programs will have allocated different amounts of memory at different times, which pages are available and which are unavailable will vary across your programs.
So you need for the programs to gain consensus on a memory address. This means that several addresses might have to be tried and rejected. If it's possible that sometime after startup a new program will become interested, **the search for consensus will have to start over again**. The algorithm would look something like this:
1. Program A proposes memory address X to all other programs.
2. The other programs respond with true or false to indicate whether the memory mapping at address X succeeded.
3. If program A receives any false responses, goto #1.
4. Program A sends a message to the other programs letting them know the address has been validated and maybe used.
5. If a new app becomes interested in the data, it must notify program A it would like an address.
6. Program A then has to tell all the other programs to stop using the data and goto #1.
To come up with what addresses A should propose, you could have A map a non-fixed memory segment, see what address it's mapped at, and propose that address. If it's unsatisfactory, map another segment and propose it instead. You will need to unmap the segments at some point, but you can't unmap them right away because if you unmap then remap a segment of the same size chances are the OS will give you the same address back over and over. **Keep in mind that you may never reach consensus**; there's no guarantee that there's a large enough segment at a common location across all the processes. This could happen if your programs all independently use almost all memory, say if they are backed up by a ton of swap (though if you care enough about performance to use shared memory hopefully you are avoiding swap).
All of the above assumes you're in a relatively constrained address space. **If you're on 64-bit, this could work**. Most computers' RAM + swap will be far less than what's allowed by 64-bits, so you could put map the memory at a very far out fixed address that all processes are unlikely to have mapped already. I suggest at least 2^48, since current 64-bit x86 processors don't each beyond that range (despite pointers being 64-bits, you can only plug in as much RAM as allowed by 48-bits, still a ton at the time of this writing). Although there's no reason a smart heap allocator couldn't take advantage of the vastness of the address space to reduce its bookkeeping work, so to be truly robust you would still need to build consensus. Keep in mind that you will at least want the address to be configurable -- even if we don't have that much memory anytime soon, between now and then someone else might have the same idea and pick your address.
To do the bidirectional communication you could use any of sockets, pipes, or another shared memory segment. Your OS may provide other forms of IPC. But strongly consider that you are probably now introducing more complexity than you would have to deal with if you just used the boost interprocess containers ;) | My solution:
The initialising program allows the system to select an appropriate segment address. This address is written to disc and retrieved for use by subsequent programs as required.
Caveats:
I am using 64 bit fedora 21 with Kdevelop 4.7 and find that 'void\*' is 64 bits long. Writing to disc of the segment head address involves
sprintf(bu, "%p", pointer); and writing a text file:
Recovery reads this file and decodes the hex number as a 'long long' value. This is returned to the caller where it is cast as (void\*)
I have also found that grouping all the access routines into a single folder
above the level of the individual processes (each as a project in its own right) has helped save my sanity at the expense of a single aberrant '#include' in the process files
David N Laine |
49,007,767 | I'm trying to exchange messages using multiple covert channels.
So, basically, first i need to select the channel that i want to use for communication and then select the "destination\_ip" of the user that i want to chat with and after that the
>
> processMessage()
>
>
>
is called. Now, to move from one channel to another I have to close the existing connection and then open a new connection with the new channel that i want to use. My code below is modified to keep using the same channel after closing the connection and contain only the things that you need.
```
#include <channelmanager.hpp>
#include <thread>
#include <iostream>
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <openssl/hmac.h>
struct CommunicationFixture {
CommunicationFixture() {
channelmanager.setErrorStream(&cout);
channelmanager.setOutputStream(&cout);
destination_ip = "";
channel_id = channelmanager.getChannelIDs()[0];
}
library::ChannelManager channelmanager;
vector<string> last_adapters;
string destination_ip;
string channel_id = "";
int processMessage(string message) {
if (message.compare("exit") == 0) {
channelmanager.closeConnection(destination_ip);
return 1;
}
vector<string> arguments;
boost::split(arguments, message, boost::is_any_of(" "), boost::token_compress_on);
if (arguments[0].compare("argument") == 0) {
if (arguments.size() < 2) {
cout << "Not enough arguments" << endl;
return 0;
}
string argument_list = arguments[1];
for (unsigned int i = 2; i < arguments.size(); i++) {
argument_list += " " + arguments[i];
}
channelmanager.setChannelArguments(destination_ip, argument_list);
cout << "Set channel argument to '" << argument_list << "'." << endl;
return 0;
}
if (message.compare("help") == 0) {
cout << "Help not available in chat mode. Close chat first with 'exit'" << endl;
return 0;
}
channelmanager.openConnection(destination_ip, channel_id);
channelmanager.sendMessage(destination_ip, message);
return 0;
}
int close(string destination){
cout << "closing.." << endl;
channelmanager.closeConnection(destination); //I believe i have the error because of this!
return 0;
}
};
BOOST_FIXTURE_TEST_SUITE(communication, CommunicationFixture)
BOOST_AUTO_TEST_CASE(basic_communication) {
selectAdapterId(0);
cout << "Test" << endl << endl;
printCommands();
cout << "Enter your command:" << endl;
string command;
int code = 0;
while (code != 2) {
std::getline(cin, command);
code = processCommand(command);
if (code == 1) {
// chat
cout << "chat started.." << endl;
int chatCode = 0;
while (chatCode != 1) {
std::getline(cin, message);
close(destination_ip);
chatCode = processMessage(message);
channelmanager.setErrorStream(&cout);
}
cout << "chat ended." << endl;
}
}
}
BOOST_AUTO_TEST_SUITE_END()
```
Note that, i think that the error happens due to the
>
> function close()
>
>
>
because without it i don't get any errors. and the error doesn't happen immediately but after exchanging some messages. Here's the error:
>
> unknown location(0): fatal error: in
> "communication/basic\_communication": memory access violation at
> address: 0x00000024: no mapping at fault address
> communicationTest.cpp(325): last checkpoint: "basic\_communication"
> test entry
>
>
> | 2018/02/27 | [
"https://Stackoverflow.com/questions/49007767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5467365/"
] | Memory access violation happen when you are trying to access to an unitialized variable, in this case the `channelmanager`.
I can only see that you initialize `channelmanager` in the `processMessage()` method and you are closing the connection before initializing the `channelmanager` as it happen in:
```
close(destination_ip);
chatCode = processMessage(message);
```
Either you change the initialization or do not close it before the `processMessage()` method. | Memory access violation is also called a segmentation fault (or segfault), occurs when the program tries to access a memory location that doesn't exist, or is otherwise inaccessible. We call this trying to access an illegal memory location. That memory is either non-existent or we aren't aren't allowed to touch it.
If the first input from user is 'exit', which is going to call
```
if (message.compare("exit") == 0) {
channelmanager.closeConnection(destination_ip);
return 1;
}
```
In this case, destination\_ip isn't initialised. |
7,209,731 | I am writing a program that does some batch processing. The batch elements can be processed independently of each other and we want to minimize overall processing time. So, instead of looping through each element in the batch one at a time, I am using an ExecutorService and submitting Callable objects to it:
```
public void process(Batch batch)
{
ExecutorService execService = Executors.newCachedThreadPool();
CopyOnWriteArrayList<Future<BatchElementStatus>> futures = new CopyOnWriteArrayList<Future<BatchElementStatus>>();
for (BatchElement element : batch.getElement())
{
Future<MtaMigrationStatus> future = execService.submit(new ElementProcessor(batch.getID(),
element));
futures.add(future);
}
boolean done = false;
while (!done)
{
for (Future<BatchElementStatus> future : futures)
{
try
{
if (future.isDone())
{
futures.remove(future);
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
if (futures.size() == 0)
{
done = true;
}
}
}
}
```
We want to be able to allow the batch processing to be cancelled. Because I'm not using a loop, I can't just check at the top each loop if a cancel flag has been set.
We are using a JMS topic to which both the BatchProcessor and ElementProcessor will be listening to inform them the batch has been cancelled.
There are a number of steps in the ElementProcess call() after which some of them the processing can be safely stopped but there's a point of no return. The class has this basic design:
```
public class ElementProcessor implements Callable, MessageListener
{
private cancelled = false;
public void onMessage(Message msg)
{
// get message object
cancelled = true;
}
public BatchElementStatus call()
{
String status = SUCCESS;
if (!cancelled)
{
doSomehingOne();
}
else
{
doRollback();
status = CANCELLED;
}
if (!cancelled)
{
doSomehingTwo();
}
else
{
doRollback();
status = CANCELLED;
}
if (!cancelled)
{
doSomehingThree();
}
else
{
doRollback();
status = CANCELLED;
}
if (!cancelled)
{
doSomehingFour();
}
else
{
doRollback();
status = CANCELLED;
}
// After this point, we cannot cancel or pause the processing
doSomehingFive();
doSomehingSix();
return new BatchElementStatus("SUCCESS");
}
}
```
I'm wondering if there's a better way to check if the batch/element has been cancelled other than wrapping method calls/blocks of code in the call method in the `if(!cancelled)` statements.
Any suggestions? | 2011/08/26 | [
"https://Stackoverflow.com/questions/7209731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332893/"
] | I don't think you can do much better than what you are currently doing, but here is an alternative:
```
public BatchElementStatus call() {
return callMethod(1);
}
private callMethod(int methodCounter) {
if (cancelled) {
doRollback();
return new BatchElementStatus("FAIL");
}
switch (methodCounter) {
case 1 : doSomethingOne(); break;
case 2 : doSomethingTwo(); break;
...
case 5 : doSomethingFive();
doSomethingSix();
return new BatchElementStatus("SUCCESS");
}
return callMethod(methodCounter + 1);
}
```
Also, you want to make `cancelled` volatile, since `onMessage` will be called from another thread. But you probably don't want to use `onMessage` and `cancelled` anyway (see below).
Other minor points: 1) `CopyOnWriteArrayList<Future<BatchElementStatus>> futures` should just be an `ArrayList`. Using a concurrent collection mislead us into thinking that `futures` is on many thread. 2) `while (!done)` should be replaced by `while (!futures.isEmpty())` and `done` removed. 3) You probably should just call `future.cancel(true)` instead of "messaging" cancellation. You would then have to check `if (Thread.interrupted())` instead of `if (cancelled)`. If you want to kill all futures then just call `execService.shutdownNow()`; your tasks have to handle interrupts for this to work.
**EDIT**:
instead of your `while(!done) { for (... futures) { ... }}`, you should use an [ExecutorCompletionService](http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorCompletionService.html). It does what you are trying to do and it probably does it a lot better. There is a complete example in the API. | Future has a cancel(boolean) method that will interrupt the running thread if true is passed in
so replace the `if(!cancelled)` checks with `if(Thread.interrupted())` and return when you got a interrupt (you're not currently)
note that this will reset the interrupted flag to false (so `if(Thread.interrupted()&&Thread.interrupted())` will be false) if you don't want to reset it use `Thread.currentThread().isInterrupted()` this maintains the flag for subsequent checks
or you can reset the flag to interrupted with `Thread.currentThread().interrupt();`
besides that use this inside the waiting while
```
for(Iterator<Future<MtaMigrationStatus>> it = futures.iterator();it.hasNext();){
Future<MtaMigrationStatus> future = it.next();
try
{
if (future.isDone())
{
it.remove();//<<--this avoids concurrent modification exception in the loop
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
if (futures.size() == 0)//outside the inner for loop and inside the while (or make the condition this) for micro-optimizing this check
{
done = true;
}
``` |
7,209,731 | I am writing a program that does some batch processing. The batch elements can be processed independently of each other and we want to minimize overall processing time. So, instead of looping through each element in the batch one at a time, I am using an ExecutorService and submitting Callable objects to it:
```
public void process(Batch batch)
{
ExecutorService execService = Executors.newCachedThreadPool();
CopyOnWriteArrayList<Future<BatchElementStatus>> futures = new CopyOnWriteArrayList<Future<BatchElementStatus>>();
for (BatchElement element : batch.getElement())
{
Future<MtaMigrationStatus> future = execService.submit(new ElementProcessor(batch.getID(),
element));
futures.add(future);
}
boolean done = false;
while (!done)
{
for (Future<BatchElementStatus> future : futures)
{
try
{
if (future.isDone())
{
futures.remove(future);
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
if (futures.size() == 0)
{
done = true;
}
}
}
}
```
We want to be able to allow the batch processing to be cancelled. Because I'm not using a loop, I can't just check at the top each loop if a cancel flag has been set.
We are using a JMS topic to which both the BatchProcessor and ElementProcessor will be listening to inform them the batch has been cancelled.
There are a number of steps in the ElementProcess call() after which some of them the processing can be safely stopped but there's a point of no return. The class has this basic design:
```
public class ElementProcessor implements Callable, MessageListener
{
private cancelled = false;
public void onMessage(Message msg)
{
// get message object
cancelled = true;
}
public BatchElementStatus call()
{
String status = SUCCESS;
if (!cancelled)
{
doSomehingOne();
}
else
{
doRollback();
status = CANCELLED;
}
if (!cancelled)
{
doSomehingTwo();
}
else
{
doRollback();
status = CANCELLED;
}
if (!cancelled)
{
doSomehingThree();
}
else
{
doRollback();
status = CANCELLED;
}
if (!cancelled)
{
doSomehingFour();
}
else
{
doRollback();
status = CANCELLED;
}
// After this point, we cannot cancel or pause the processing
doSomehingFive();
doSomehingSix();
return new BatchElementStatus("SUCCESS");
}
}
```
I'm wondering if there's a better way to check if the batch/element has been cancelled other than wrapping method calls/blocks of code in the call method in the `if(!cancelled)` statements.
Any suggestions? | 2011/08/26 | [
"https://Stackoverflow.com/questions/7209731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332893/"
] | I don't think you can do much better than what you are currently doing, but here is an alternative:
```
public BatchElementStatus call() {
return callMethod(1);
}
private callMethod(int methodCounter) {
if (cancelled) {
doRollback();
return new BatchElementStatus("FAIL");
}
switch (methodCounter) {
case 1 : doSomethingOne(); break;
case 2 : doSomethingTwo(); break;
...
case 5 : doSomethingFive();
doSomethingSix();
return new BatchElementStatus("SUCCESS");
}
return callMethod(methodCounter + 1);
}
```
Also, you want to make `cancelled` volatile, since `onMessage` will be called from another thread. But you probably don't want to use `onMessage` and `cancelled` anyway (see below).
Other minor points: 1) `CopyOnWriteArrayList<Future<BatchElementStatus>> futures` should just be an `ArrayList`. Using a concurrent collection mislead us into thinking that `futures` is on many thread. 2) `while (!done)` should be replaced by `while (!futures.isEmpty())` and `done` removed. 3) You probably should just call `future.cancel(true)` instead of "messaging" cancellation. You would then have to check `if (Thread.interrupted())` instead of `if (cancelled)`. If you want to kill all futures then just call `execService.shutdownNow()`; your tasks have to handle interrupts for this to work.
**EDIT**:
instead of your `while(!done) { for (... futures) { ... }}`, you should use an [ExecutorCompletionService](http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorCompletionService.html). It does what you are trying to do and it probably does it a lot better. There is a complete example in the API. | Your `ElementProcessor` can extend from `java.util.concurrent.FutureTask` which is
>
> A cancellable asynchronous computation. This class provides a base
> implementation of Future, with methods to start and cancel a
> computation, query to see if the computation is complete, and retrieve
> the result of the computation.
>
>
> The FutureTask class is an implementation of Future that implements
> Runnable, and so may be executed by an Executor.
>
>
>
`FutureTask` has a `cancel` method which you can implement to do some cancel specific operations. Also, if `FutureTask` is canceled it will not be executed anymore, so you don't have to check always the status. |
31,111,914 | When we use GET method we use ambersand(`&`) sign to send the data to a particular script. I'm sending data to a php script called `myscript.php` by the GET method from a javascript like the following :
```
http.open('GET', 'Myscript.php'+ '?d=' + value1 + '&c=' + value2 + '&f=' + value3);
```
But if the value1 or value2 or value3 contains an `&` sign in their actual value (for example if somebody enter for the value1 `garth&ggg&kkk` then the `Myscript.php` can't handle the value1 properly because it contains an `&` sign in the actual data. It takes the value `garth` for value1.
My php code is as follows:
```
if (isset($_GET['d'])) { $a = $_GET['d'];}
``` | 2015/06/29 | [
"https://Stackoverflow.com/questions/31111914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2884663/"
] | You need to encode it properly before putting it into url to turn ampersand to `%26`:
* in PHP: `urlencode()`
* in javascript: `encodeURIComponent()`
You don't need to decode it in PHP, it will decode it for you to `&` character. | JS you can use
```
encodeURIComponent(str);
```
Example
```
str="garth&ggg&kkk";
str=encodeURIComponent(str);
```
It will replace & with %26 |
69,544,118 | I'm working on a solution where I have a SQS queue with Lambda trigger. My understanding is Lambda will receive messages in batches to be processed, and once Lambda function is successful, the messages in the SQS queue is automatically deleted. However, how do I only allow some of those messages to be deleted?
Let's assume this use case:
Lambda function receives a batch with 10 messages, and only 7 messages are valid and can be processed, and the other 3 messages needs to be reprocessed at later point.
My initial thought was I could update the visibility timeout via `boto3.sqs.change_visibility_timeout` for each of the 3 messages to have it reprocessed after the timeout, however, since overall lambda function execution is successful, all 10 messages are deleted from SQS queue.
Any suggestions? | 2021/10/12 | [
"https://Stackoverflow.com/questions/69544118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5186759/"
] | Yes, by default, the Lambda function deletes all the messages upon success. You would need to handle this in your code, but not by changing the visibility timeout of the messages.
Add DLQ (dead-letter queue) that will actually handle the failed messages (messages go to DLQ after a certain number of failed attempts to be processed, depending on how you set it up)
You have few options here:
1. You can handle each item yourself, and delete messages that are processed successfully. In case of a message that's not successful, you can throw an error and it won't be deleted automatically by the lambda function
2. If you use JavaScript you can try with [Middy](https://www.npmjs.com/package/@middy/core)
3. If you use Python, you can use [Lambda Powertools Python](https://awslabs.github.io/aws-lambda-powertools-python/1.12.0/utilities/batch/) | For AWS Lambdas with an SQS trigger, by default, when your function encounters an error processing one or more messages in a given batch, the entire batch is marked as a failure. All of the messages in the batch are made visible again in the queue. Depending on your redrive policy, you can end up repeatedly processing successful messages along with the failures.
Rather than change the visibility timeout, the simplest way to specify which messages should be retried later and which can safely be deleted from the queue is to change the function response type to `ReportBatchItemFailures`. This allows you to return a list of failed message ids, indicating that only those messages in the batch should be made visible again in the queue.
Here's what the reporting syntax looks like for a handler function in Node.js:
```
exports.handler = async (event) => {
// Process the event
const batchItemFailureResponse = {
batchItemFailures: [
{
itemIdentifier: "idFailedMessage1"
},
{
itemIdentifier: "idFailedMessage2"
},
{
itemIdentifier: "idFailedMessage3"
}
]
};
return batchItemFailureResponse;
};
```
There is more information to be found in the [official documentation](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html#services-sqs-batchfailurereporting).
This response type is configured when setting a queue as an event source for the Lambda. If you're configuring from the console, navigate to the Lambda function page, select the **Configuration** tab, and then choose **Triggers**. Then choose **Add Trigger** and choose the **SQS** trigger type. In addition to providing the standard parameters, be sure to check the box under **Report batch item failures** after expanding **Additional Settings**. It should look something like this:
[Add trigger with batch failure reporting](https://i.stack.imgur.com/e7tqR.png)
This parameter must be set when first creating the trigger.
This response type can also be defined if you use CloudFormation templates to provision your resources. See the [AWS documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html#cfn-lambda-eventsourcemapping-functionresponsetypes) for more information. Note that if you use AWS SAM event source mappings, the [documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-function-sqs.html) suggests that adding `FunctionResponseTypes` to the YAML with `ReportBatchItemFailures` in the type list isn't supported. That is incorrect, the documentation is simply outdated. There is an [open issue](https://github.com/aws/serverless-application-model/issues/2256) around addressing this oversight.
Finally, in addition to reporting batch item failures, you should provision a target DLQ (dead-letter queue) and determine a reasonable maximum receive count so that action can be taken on messages that fail repeatedly. |
1,542 | I have a problem similar in formulation to this post, with a few notable differences:
[What simple methods are there for adaptively sampling a 2D function?](https://scicomp.stackexchange.com/questions/923/what-simple-methods-are-there-for-adaptively-sampling-a-2d-function)
Like in that post:
* I have a $f(x,y)$ and evaluation of this function is somewhat expensive to compute
Unlike in that post:
* **I am interested not in the value of the function accurately everywhere, but only in finding a single isocontour of the function.**
* I can make significant assertions about the autocorrelation of the function, and consequently the scale of smoothness.
Is there an intelligent way to step along/sample this function and find this contour?
More Information
----------------
The function is the computation of [Haralick Features](http://murphylab.web.cmu.edu/publications/boland/boland_node26.html) over $N$ pixles surrounding the point, and soft classification by some sort of classifier/regressor. The output of this is a floating point number which indicates which texture/material the point belongs to. The scaling of this number can be estimated class probablities (SoftSVM or statistical methods etc) or something really simple like the output of a linear/logistic regression. Classification/regression is accurate and cheap compared to time taken for feature extraction from the image.
Statistics surrounding $N$ means that the window is typically sampling overlapping regions, and as such there is *significant* correlation between nearby samples. (Something I can even approach numerically/symbolically) Consequently, this can be thought of as a more complex function of $f(x, y, N)$ where larger $N$ will give an estimate more related to the neighborhood (highly correlated), and a smaller $N$ will give a more variable, but more local estimate.
Things I Have Tried:
--------------------
* Brute Computation - Works well. 95% correct segmentation with constant $N$. The results look fantastic when contoured using any standard method after that. This takes *forever*. I can simplify the features calculated on a per-sample basis, but ideally I want to avoid this to keep this code general to images with textures who's differences show up in different parts of the feature space.
* Dumb Stepping - Take a single pixel "step" in each direction and pick the direction to move based on closeness to iso-line value. Still pretty slow, and it will ignore bifurcation of an isoline. Also, in areas with a flat gradient it will "wander" or double back on itself.
I am thinking I want to do something like the subdivison proposed in the first link, but pruned for boxes which bound the isoline of interest. I feel like I should be able to leverage $N$ also, but I am not sure how to approach that. | 2012/03/06 | [
"https://scicomp.stackexchange.com/questions/1542",
"https://scicomp.stackexchange.com",
"https://scicomp.stackexchange.com/users/53/"
] | There is a paper in computer graphics called [Provably Good Sampling and Meshing of Surfaces](http://geometrica.saclay.inria.fr/team/Steve.Oudot/papers/bo-pgsms-05/bo-pgsms-05.pdf), which relies on you providing an oracle that determines all the intersections of an isoline with a given line segment. With that, it samples all the contours assuming you can provide a local feature scale (something like the maximum local curvature), and an initial set of line segments that intersects all the contours. It is not the simplest thing to implement, since it relies on computing Delaunay triangulations, but it is implemented in 3D in [CGAL](http://www.cgal.org). It is substantially simpler in 2D, since good triangulation software like [Triangle](http://www.cs.cmu.edu/~quake/triangle.html) exists. In some sense, this is pretty close to the best you can possibly do. | You might try applying the core features of the Efficient Global Reliability Analysis (EGRA) method. This method was derived for the efficient computation of a probability of failure, but the guts of it are focused on doing what you describe - creating a model that is accurate only near a specific contour of interest.
This might be an interesting starting point, but I'm not sure it will solve your problem. It depends very much on the shape of your function. If it is something that can be approximated well with a [kriging](http://en.wikipedia.org/wiki/Kriging) model, then it should perform well. These models are pretty flexible, but generally need a smooth underlying function. I have tried applying EGRA to an image segmentation application in the past, but had little success because it simply doesn't make sense to fit a surrogate model to something that isn't really defined by a functional relationship. Still, I mention it as something you might want to look into in case your application is different than I'm envisioning.
If I haven't talked you out of it, you can read more about EGRA [here](http://etd.library.vanderbilt.edu/available/etd-04052010-103718/unrestricted/BichonDissertation.pdf) (PDF link) and [here](http://www.mendeley.com/research/efficient-global-reliability-analysis-nonlinear-implicit-performance-functions/), and there is an existing implementation in Sandia's [DAKOTA](http://dakota.sandia.gov/) project - to my knowledge, the only open-source implementation of EGRA available. |
17,416,488 | What I want to implement is something like:
```
switch(flag)
{
case 1:
var query=from w in db.someTable
select w;
break;
case 2:
query=from w in db.someTable
where w.id==someID
select w;
break;
case default:
break;
}
```
But it cannot compile correctly. If I add a `var` before the second `query`, it prompts that query has been declared.
Do I have to change the variable name? Such like: `query1 in case1, query2 in case2`, etc.
---
EDITED 1
Thanks for your help. In fact my code is a little bit more complicated than what I posted above. Here is the complete code:
```
List<object> results=new List<object>();
switch (flag)
{
case 1:
var query = from w in db.RADIATION
where w.DATEDT.CompareTo(dateStr) == 0
&& w.LATITUDE.CompareTo(latitude) == 0
&& w.LONGITUDE.CompareTo(longitude) == 0
orderby w.TIMETM
select new { w.RADIATION, w.TIMETM };
break;
case 2:
var query = from w in db.TEMPRETURE
where w.DATEDT.CompareTo(dateStr) == 0
&& w.LATITUDE.CompareTo(latitude) == 0
&& w.LONGITUDE.CompareTo(longitude) == 0
orderby w.TIMETM
select new { w.TEMPRETURE, w.TIMETM };
foreach (var item in query)
{
var resultItem = new { TEMPRETURE = item.TEMPRETURE, TIME = item.TIMETM };
results.Add(resultItem);
}
break;
case default:
break;
}
```
The two queries are for two different tables. So I don't know how to determine the Type T in IQueryable. Also, what I `select` is an anonymous object using `new { PropertyName = propertyValue }`.
Is there anyway if I insist using the same name `query`? | 2013/07/02 | [
"https://Stackoverflow.com/questions/17416488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526662/"
] | Declaring with `var` lets you shorten the code, but the variable that you declare remains statically typed, and the scope of that variable does not change.
If you need to use a variable outside `switch`, declare it before the `switch` statement, like this:
```
IQueryable<SomeType> query = null;
switch (...) {
case 1: query = ...; break;
...
default: ...
}
```
Now you can use `query` outside the `switch`.
Note: There are cases where you must use `var` because the type that you assign to it has no name, but in your first case the type has a name, so you do not need to use `var`.
**EDIT :** Your second case, however, does require a `var`, because you are selecting an anonymous type. In situations like that there are several ways around this problem:
* You can declare a named type for the "superset" of columns that you select (i.e. `TIMETM`, `TEMPERATURE`, and `RADIATION`), or
* In .NET 4.0 you can use `IQueryable<dynamic>`. This shifts some of compile-time checking into runtime, but if you have to go this route, it is very convenient. | if it is same table , you can try this:
```
var query=from w in db.someTable select w;
switch(flag)
{
case 1:
break;
case 2:
query=query.Where(w.id==someID);
break;
default:
query=null; //since linq is Delay query, if you don't use the data in query, it will do nothing.
break;
}
``` |
17,416,488 | What I want to implement is something like:
```
switch(flag)
{
case 1:
var query=from w in db.someTable
select w;
break;
case 2:
query=from w in db.someTable
where w.id==someID
select w;
break;
case default:
break;
}
```
But it cannot compile correctly. If I add a `var` before the second `query`, it prompts that query has been declared.
Do I have to change the variable name? Such like: `query1 in case1, query2 in case2`, etc.
---
EDITED 1
Thanks for your help. In fact my code is a little bit more complicated than what I posted above. Here is the complete code:
```
List<object> results=new List<object>();
switch (flag)
{
case 1:
var query = from w in db.RADIATION
where w.DATEDT.CompareTo(dateStr) == 0
&& w.LATITUDE.CompareTo(latitude) == 0
&& w.LONGITUDE.CompareTo(longitude) == 0
orderby w.TIMETM
select new { w.RADIATION, w.TIMETM };
break;
case 2:
var query = from w in db.TEMPRETURE
where w.DATEDT.CompareTo(dateStr) == 0
&& w.LATITUDE.CompareTo(latitude) == 0
&& w.LONGITUDE.CompareTo(longitude) == 0
orderby w.TIMETM
select new { w.TEMPRETURE, w.TIMETM };
foreach (var item in query)
{
var resultItem = new { TEMPRETURE = item.TEMPRETURE, TIME = item.TIMETM };
results.Add(resultItem);
}
break;
case default:
break;
}
```
The two queries are for two different tables. So I don't know how to determine the Type T in IQueryable. Also, what I `select` is an anonymous object using `new { PropertyName = propertyValue }`.
Is there anyway if I insist using the same name `query`? | 2013/07/02 | [
"https://Stackoverflow.com/questions/17416488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526662/"
] | The `var` keyword is irrelevant. You can do it like this:
```
switch(flag)
{
case 1: {
var query=from w in db.someTable
select w;
}
break;
case 2: {
var query=from w in db.someTable
where w.id==someID
select w;
}
break;
default:
break;
}
```
It is correct syntax, but I would suggest you to extract each case to each method instead. | if it is same table , you can try this:
```
var query=from w in db.someTable select w;
switch(flag)
{
case 1:
break;
case 2:
query=query.Where(w.id==someID);
break;
default:
query=null; //since linq is Delay query, if you don't use the data in query, it will do nothing.
break;
}
``` |
12,332 | Почему в первом случае "к" будет приставкой,а во втором - "-юч" будет суффиксом?
**Ключ воды и ключ дверной** | 2012/11/15 | [
"https://rus.stackexchange.com/questions/12332",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/1038/"
] | Это по каким же эврикам?
Ключ - корень в обоих случаях.
Фасмер даже допускает общность происхождения.
I род. п. -а́ I., сюда же заключи́ть, укр. ключ, ст.-слав. ключь, болг. клю́чът, сербохорв. кљу̑ч, род. п. кљу́ча " крюк, ключ", словен. kljúč, чеш. klíč, слвц. kl᾽úč, польск. klucz, в.-луж. kluč, н.-луж. kluc. Родственно балт. словам, приведенным на клюка́, а также греч. κληΐς, дор. κλΒ̄ίς, κλάξ "ключ", κλείω "запираю", лат. clāvus " гвоздь", clāvis "ключ", claudō "запираю", ирл. cló, мн. clói " гвоздь"; см. Бернекер 1, 528 и сл.; Траутман ВSW 137 и сл.; Вальде–Гофм. 1, 229 и сл. Сюда же с и.-е. skl- относятся д.-в.-н. slioʒan "запирать", sluʒʒil "ключ", др.-сакс. slutil – то же. II род. п. -а́ II. "источник, родник", болг. ключ (водата ври с ключ) "о шуме воды", сербохорв. кљу̑ч, род. п. кљу́ча "клокотание, бурление воды", кљу̀чати " кипеть, бурлить, клохтать". Обычно сближается с клю́кать " шуметь" (см.); см. Бернекер 1, 529; Брюкнер 236, но имеет смысл поставить вопрос об одинаковом происхождении с ключ I. Ср. нем. выражение eine Quelle erschließen " открыть источник". | Версия в этом видео интересная, но она не общепринятая, а авторская. Некая гипотеза, проверить которую сейчас уже практически нереально. Но она не лишена здравого смысла, хотя может оказаться и за уши притянутой. То есть у дверного ключа якобы корень "кл-" (от "кол" - кругляш - самый примитивный ключ, которым открывают щеколду в деревенских домах - изогнутая проволока. Суффикс - "-юч-", возникший от "-ук-" (было сначала "клюка", или "клюк", потом "ключ"). А в слове ключ как водный источник корень "-люч" (луч, излучать, вода излучается - то есть изливается, разбрызгивается, луч - струя воды). "К-" - приставка, которая раньше была предлогом.
Так что ответ на Ваш вопрос - потому что есть такая альтернативная точка зрения, как в этом видео. |
20,279 | Suppose that a Tor client wants to access a certain hidden service. According to the protocol, instead of submitting a request directly to the server IP (which is hidden[1][2]), this client submit a request via a series of relays.
However, at some point, there will be a final relay in charge of delivering the client's message specifically to the server running the hidden service. In order to do so, this final relay must know the IP of this hidden server, otherwise the current internet infrastructure cannot deliver the message.
If the aforementioned steps are indeed correct, this means that in order to host a website using TOR Hidden Service you must reveal the IP address to a final relay. Therefore, Tor network does not hide the IP address of hidden services.
How to reconcile that? Am I missing something?
---
[1]: "TOR Hidden Service allows you to host a website, without revealing where the website is, and hence protects the identity of the publisher/webmaster.", [WikiBooks](https://en.wikibooks.org/wiki/How_to_Protect_your_Internet_Anonymity_and_Privacy/TOR_Hidden_Service_for_Anonymous_Websites)
[2]: "The Tor network hides the IP address of hidden services, instead using onion addresses and public keys to keep the real location hidden.", [Privay.net](https://privacy.net/make-site-visible-dark-web-tor-hidden-services/) | 2019/09/12 | [
"https://tor.stackexchange.com/questions/20279",
"https://tor.stackexchange.com",
"https://tor.stackexchange.com/users/27707/"
] | Tor uses TCP tunnels, so - regardless of the previous answer - no need to use it. The hidden service is reached from the Tor node that is hosting it, usually through a localhost. The scenario you've described about IP revealing - yes, it *can* be a privacy problem. The design doc states clear - the system is anonymizing mostly the client, not the server - it's only rudimentary in a *standard* setup. To conceal your server IP use bridges-only for your hosting server(s) - that will elevate the privacy, but if you want both client and server to be equally anonymized - use I2P, not Tor - it's designed for exactly that purpose | This is a bit of a simplistic explanation, but I hope it helps.
The Tor service, running on the machine where the onion service is being hosted, reaches out to the Tor Network and says, if you want to use onion abcxyz.onion or port 80, then you have to talk to me (the service) but not to the IP of the machine. Because the connection is originated from the machine being hosted and not from an external machine, no actual IP is needed to be shared.
To look at it another way.
I set up a web server on standard TCP port 80
I make sure that my firewall is closed on TCP port 80 so nobody can connect to that web server. (sounds pointless, right?)
I then tell the Tor service to advertise that web server on Tor so people can view it.
You say, "but wait you have a firewall up, they won't be able to see your web sserver!"
That would be true if I was expecting external users to connect to me.
Instead, the Tor service connected to the Tor Network via UDP (not TCP) and other people are able to use that connection to come in and view my web server even with the firewall turned on.
Nobody ever sees my IP because that UDP connection from my web server to the Tor network doesn't contain TCP/IP informatation. It just contains an address and a connection to get in. |
16,417,449 | I create my own class and I want to use it in my new component but I am getting an error...
The code is the following:
```
type
TMyClass = class
Name: string;
Number: double;
end;
TMyComponent = class(TCustomPanel)
private
FMyClass: TMyClass;
public
procedure SetMyClass(aName: string; aNumber: double);
published
property MyClass: TMyClass write SetMyClass;
end;
procedure SetMyClass(aName: string; aNumber: double);
begin
FMyClass.Name:= aName;
FMyClass.Number:= aNumber;
end;
```
it appears that the property has incompatible types, I don't know why.
Does anybody has a clue about that and how can I solve this problem.
Having a FName and FNumber as fields in TMyComponent is not an option, my code is more complex and this is a simple example to explain my goal.
thanks | 2013/05/07 | [
"https://Stackoverflow.com/questions/16417449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2338944/"
] | The things that I can see wrong with your code at present are:
1. The property setter must receive a single parameter of the same type as the property, namely `TMyClass`.
2. The property setter must be a member of the class, but you've implemented it as a standalone procedure.
3. A published property needs to have a getter.
So the code would become:
```
type
TMyClass = class
Name: string;
Number: double;
end;
TMyComponent = class(TCustomPanel)
private
FMyClass: TMyClass;
procedure SetMyClass(Value: TMyClass);
published
property MyClass: TMyClass read FMyClass write SetMyClass;
end;
procedure TMyComponent.SetMyClass(Value: TMyClass);
begin
FMyClass.Name:= Value.Name;
FMyClass.Number:= Value.Number;
end;
```
This code does not instantiate `FMyClass`. I'm guessing that the code that does instantiate `FMyClass` is part of the larger component code that has been excised for the sake of this question. But obviously you do need to instantiate `FMyClass`.
An alternative to instantiating `FMyClass` is to turn `TMyClass` into a record. Whether or not that would suit your needs I cannot tell.
---
It looks like you are having some problems instantiating this object. Do it like this:
```
type
TMyClass = class
Name: string;
Number: double;
end;
TMyComponent = class(TCustomPanel)
private
FMyClass: TMyClass;
procedure SetMyClass(Value: TMyClass);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property MyClass: TMyClass read FMyClass write SetMyClass;
end;
constructor TMyComponent.Create(AOwner: TComponent);
begin
inherited;
FMyClass:= TMyClass.Create;
end;
destructor TMyComponent.Destroy;
begin
FMyClass.Free;
inherited;
end;
procedure TMyComponent.SetMyClass(Value: TMyClass);
begin
FMyClass.Name:= Value.Name;
FMyClass.Number:= Value.Number;
end;
```
One final comment. Using `MyClass` for an object is a bad name. Use class for the type, and object for the instance. So, your property should be `MyObject` and the member field should be `FMyObject` etc. | Try this:
```
type
TMyClass = class
Name: string;
Number: double;
end;
TMyComponent = class(TCustomPanel)
private
FMyClass: TMyClass;
public
procedure SetMyClass(Value: TMyClass);
published
property MyClass: TMyClass write SetMyClass;
end;
procedure TMyComponent.SetMyClass(Value);
begin
FMyClass := Value;
end;
``` |
16,417,449 | I create my own class and I want to use it in my new component but I am getting an error...
The code is the following:
```
type
TMyClass = class
Name: string;
Number: double;
end;
TMyComponent = class(TCustomPanel)
private
FMyClass: TMyClass;
public
procedure SetMyClass(aName: string; aNumber: double);
published
property MyClass: TMyClass write SetMyClass;
end;
procedure SetMyClass(aName: string; aNumber: double);
begin
FMyClass.Name:= aName;
FMyClass.Number:= aNumber;
end;
```
it appears that the property has incompatible types, I don't know why.
Does anybody has a clue about that and how can I solve this problem.
Having a FName and FNumber as fields in TMyComponent is not an option, my code is more complex and this is a simple example to explain my goal.
thanks | 2013/05/07 | [
"https://Stackoverflow.com/questions/16417449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2338944/"
] | Try this:
```
type
TMyClass = class
Name: string;
Number: double;
end;
TMyComponent = class(TCustomPanel)
private
FMyClass: TMyClass;
public
procedure SetMyClass(Value: TMyClass);
published
property MyClass: TMyClass write SetMyClass;
end;
procedure TMyComponent.SetMyClass(Value);
begin
FMyClass := Value;
end;
``` | ```
unit MyComponentTest2;
interface
uses SysUtils, Classes, Controls, Forms, ExtCtrls, Messages, Dialogs;
type
TMyClass = class
Name: string;
Number: double;
end;
TMyComponentTest2 = class(TCustomPanel)
private
FMyClass: TMyClass;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetMyClass(Value: TMyClass);
published
property MyClass: TMyClass read FMyClass write SetMyClass;
end;
procedure Register;
implementation
constructor TMyComponentTest2.Create(AOwner: TComponent);
begin
Inherited Create(AOwner);
FMyClass:= TMyClass.Create;
end;
destructor TMyComponentTest2.Destroy;
begin
Inherited;
FMyClass.Free;
end;
procedure TMyComponentTest2.SetMyClass(Value: TMyClass);
begin
FMyClass.Name:= Value.Name;
FMyClass.Number:= Value.Number;
end;
procedure Register;
begin
RegisterComponents('MyComponents', [TMyComponentTest2]);
end;
end.
``` |
16,417,449 | I create my own class and I want to use it in my new component but I am getting an error...
The code is the following:
```
type
TMyClass = class
Name: string;
Number: double;
end;
TMyComponent = class(TCustomPanel)
private
FMyClass: TMyClass;
public
procedure SetMyClass(aName: string; aNumber: double);
published
property MyClass: TMyClass write SetMyClass;
end;
procedure SetMyClass(aName: string; aNumber: double);
begin
FMyClass.Name:= aName;
FMyClass.Number:= aNumber;
end;
```
it appears that the property has incompatible types, I don't know why.
Does anybody has a clue about that and how can I solve this problem.
Having a FName and FNumber as fields in TMyComponent is not an option, my code is more complex and this is a simple example to explain my goal.
thanks | 2013/05/07 | [
"https://Stackoverflow.com/questions/16417449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2338944/"
] | The things that I can see wrong with your code at present are:
1. The property setter must receive a single parameter of the same type as the property, namely `TMyClass`.
2. The property setter must be a member of the class, but you've implemented it as a standalone procedure.
3. A published property needs to have a getter.
So the code would become:
```
type
TMyClass = class
Name: string;
Number: double;
end;
TMyComponent = class(TCustomPanel)
private
FMyClass: TMyClass;
procedure SetMyClass(Value: TMyClass);
published
property MyClass: TMyClass read FMyClass write SetMyClass;
end;
procedure TMyComponent.SetMyClass(Value: TMyClass);
begin
FMyClass.Name:= Value.Name;
FMyClass.Number:= Value.Number;
end;
```
This code does not instantiate `FMyClass`. I'm guessing that the code that does instantiate `FMyClass` is part of the larger component code that has been excised for the sake of this question. But obviously you do need to instantiate `FMyClass`.
An alternative to instantiating `FMyClass` is to turn `TMyClass` into a record. Whether or not that would suit your needs I cannot tell.
---
It looks like you are having some problems instantiating this object. Do it like this:
```
type
TMyClass = class
Name: string;
Number: double;
end;
TMyComponent = class(TCustomPanel)
private
FMyClass: TMyClass;
procedure SetMyClass(Value: TMyClass);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property MyClass: TMyClass read FMyClass write SetMyClass;
end;
constructor TMyComponent.Create(AOwner: TComponent);
begin
inherited;
FMyClass:= TMyClass.Create;
end;
destructor TMyComponent.Destroy;
begin
FMyClass.Free;
inherited;
end;
procedure TMyComponent.SetMyClass(Value: TMyClass);
begin
FMyClass.Name:= Value.Name;
FMyClass.Number:= Value.Number;
end;
```
One final comment. Using `MyClass` for an object is a bad name. Use class for the type, and object for the instance. So, your property should be `MyObject` and the member field should be `FMyObject` etc. | ```
unit MyComponentTest2;
interface
uses SysUtils, Classes, Controls, Forms, ExtCtrls, Messages, Dialogs;
type
TMyClass = class
Name: string;
Number: double;
end;
TMyComponentTest2 = class(TCustomPanel)
private
FMyClass: TMyClass;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetMyClass(Value: TMyClass);
published
property MyClass: TMyClass read FMyClass write SetMyClass;
end;
procedure Register;
implementation
constructor TMyComponentTest2.Create(AOwner: TComponent);
begin
Inherited Create(AOwner);
FMyClass:= TMyClass.Create;
end;
destructor TMyComponentTest2.Destroy;
begin
Inherited;
FMyClass.Free;
end;
procedure TMyComponentTest2.SetMyClass(Value: TMyClass);
begin
FMyClass.Name:= Value.Name;
FMyClass.Number:= Value.Number;
end;
procedure Register;
begin
RegisterComponents('MyComponents', [TMyComponentTest2]);
end;
end.
``` |
43,016 | I use VMware Fusion created a VM(Linux) in my Mac, but I don't know how to delivery the data from my Mac to the VM.
If the VM is on the Windows I can use the WinSCP to load data to it, but how can I load data to VM from Mac?
Some friend can recommend me a software to load data to Linux? | 2017/06/16 | [
"https://softwarerecs.stackexchange.com/questions/43016",
"https://softwarerecs.stackexchange.com",
"https://softwarerecs.stackexchange.com/users/28348/"
] | I have been using something called [Alpha VNC Lite](https://play.google.com/store/apps/details?id=de.abr.android.avnc). Alpha VNC lite doesn't seem to work on the home screen but most other apps seem to work fine. The device doesn't need to be rooted but you do not to enable a special keyboard and accessibility options. It requires Android 5.0 and up. You can use it for free. VNC software never really works perfectly but it is still cool.
[](https://i.stack.imgur.com/X5BgR.png) | There also is [droidVNC-NG](https://github.com/bk138/droidVNC-NG) (which I authored). It does not require root and runs on Android 7+. It's open-source and available for free on Google Play and F-Droid. |
339,902 | Suppose you are implementing a publication database and creating migrations to represent different publications. Each publication has a "year" associated with it.
`t.column :year, ???`
Would this year be best represented as an integer, date, or datetime? | 2008/12/04 | [
"https://Stackoverflow.com/questions/339902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39584/"
] | I suggest using integer. Both `Date` and `DateTime` have more precision than you want, which could be misleading. Even if you initialize them w/only a year, they will store a default month and day (Jan, 1). For example, if you used `Date`, your output would look like this:
```
>> m = YourModel.create(:year => '2008')
>> m.year.to_s
=> "2008-01-01"
```
If you use integer you get what you'd expect:
```
>> m = YourModel.create(:year => '2008')
>> m.year.to_s
=> "2008"
``` | Well, if you only care about the **year**, an integer will do just right. If you're not certain that you will never, ever, need month and day, then date, and if you also may need the hour/minute/second, then datetime, but if you need a datetime, it should not be called year :-) |
339,902 | Suppose you are implementing a publication database and creating migrations to represent different publications. Each publication has a "year" associated with it.
`t.column :year, ???`
Would this year be best represented as an integer, date, or datetime? | 2008/12/04 | [
"https://Stackoverflow.com/questions/339902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39584/"
] | I would recommend just going with Rails conventions and doing a `Date` data type. This way, if you ever *do* need the month and day, you can retrieve it. Plus, it's simple to do:
```
YourModel.date.year # => "1999"
``` | Well, if you only care about the **year**, an integer will do just right. If you're not certain that you will never, ever, need month and day, then date, and if you also may need the hour/minute/second, then datetime, but if you need a datetime, it should not be called year :-) |
339,902 | Suppose you are implementing a publication database and creating migrations to represent different publications. Each publication has a "year" associated with it.
`t.column :year, ???`
Would this year be best represented as an integer, date, or datetime? | 2008/12/04 | [
"https://Stackoverflow.com/questions/339902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39584/"
] | I would recommend just going with Rails conventions and doing a `Date` data type. This way, if you ever *do* need the month and day, you can retrieve it. Plus, it's simple to do:
```
YourModel.date.year # => "1999"
``` | I suggest using integer. Both `Date` and `DateTime` have more precision than you want, which could be misleading. Even if you initialize them w/only a year, they will store a default month and day (Jan, 1). For example, if you used `Date`, your output would look like this:
```
>> m = YourModel.create(:year => '2008')
>> m.year.to_s
=> "2008-01-01"
```
If you use integer you get what you'd expect:
```
>> m = YourModel.create(:year => '2008')
>> m.year.to_s
=> "2008"
``` |
11,441,468 | New to Eclipse and Solr, I imported apache-solr-3.6.0.war into Eclipse and run Solr with tomcat plugin. Now i want to debug some existing code, however how do i import the Solr source code? | 2012/07/11 | [
"https://Stackoverflow.com/questions/11441468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962382/"
] | Without knowing how you imported it exactly: sounds like you are looking for [Source attachment](https://stackoverflow.com/questions/122160/is-there-an-easy-way-to-attach-source-in-eclipse).
It might be better if you use the [Solr source code](http://apache.mirror.clusters.cc/lucene/solr/3.6.0/) directly. Check the README file included in the release, there is an ant task to init eclipse:
>
> To setup your ide run [...] 'ant eclipse'.
>
>
>
Then all dependencies are loaded using [ivy](http://ant.apache.org/ivy/) and you can run it from within the IDE. | You can also check out the whole Lucene/Solr source:
1. install Subclipse add-in
2. choose `New...` > `Project...`
3. `SVN` > `Checkout projects from SVN...`
4. add [this link](http://svn.apache.org/repos/asf/lucene/dev) as new repository
5. select branch `/branches/lucene_solr_3_6` (if you want last stable version. Use trunk if you want to use cutting edge source)
6. choose `Check out as a project in a workspace` and leave everything else default
Then, after the checkout completes, to complete setup, you don't have to fiddle with JARs manually, simply:
1. right click on main `build.xml`, the one in your project's root
2. choose `Run As...` > `Ant build...` select (in this order)
3. `ivy-bootstrap` and `resolve` tasks (which will download all JAR dependencies)
4. then run in this order: `validate, clean-idea, eclipse, compile, get-maven-poms, generate-maven-artifacts` (the last two only if you plan to use Maven).
And that's it, you should now see no redness in your workspace and have Lucene and Solr JARs built. |
11,441,468 | New to Eclipse and Solr, I imported apache-solr-3.6.0.war into Eclipse and run Solr with tomcat plugin. Now i want to debug some existing code, however how do i import the Solr source code? | 2012/07/11 | [
"https://Stackoverflow.com/questions/11441468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962382/"
] | Without knowing how you imported it exactly: sounds like you are looking for [Source attachment](https://stackoverflow.com/questions/122160/is-there-an-easy-way-to-attach-source-in-eclipse).
It might be better if you use the [Solr source code](http://apache.mirror.clusters.cc/lucene/solr/3.6.0/) directly. Check the README file included in the release, there is an ant task to init eclipse:
>
> To setup your ide run [...] 'ant eclipse'.
>
>
>
Then all dependencies are loaded using [ivy](http://ant.apache.org/ivy/) and you can run it from within the IDE. | Run solr like this:
```
java -jar -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044 start.jar
```
Solr will start, but wait you to connect from Eclipse to continue.
Then in Eclipse, go to:
1. Run / Debug Configurations...
2. Select Remote Java Application
3. Press New button to create a new remote configuration
4. put 1044 on port
5. Click on Debug
This is the standard way to debug remote applications in Java |
11,441,468 | New to Eclipse and Solr, I imported apache-solr-3.6.0.war into Eclipse and run Solr with tomcat plugin. Now i want to debug some existing code, however how do i import the Solr source code? | 2012/07/11 | [
"https://Stackoverflow.com/questions/11441468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962382/"
] | Without knowing how you imported it exactly: sounds like you are looking for [Source attachment](https://stackoverflow.com/questions/122160/is-there-an-easy-way-to-attach-source-in-eclipse).
It might be better if you use the [Solr source code](http://apache.mirror.clusters.cc/lucene/solr/3.6.0/) directly. Check the README file included in the release, there is an ant task to init eclipse:
>
> To setup your ide run [...] 'ant eclipse'.
>
>
>
Then all dependencies are loaded using [ivy](http://ant.apache.org/ivy/) and you can run it from within the IDE. | ```
./solr start -p 8983 -f -a "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=0.0.0.0:8000"
```
Start solr with
1. provide app run on port 8983
2. provide Xrunjdwp:transport=dt\_socket
3. remote ip address 0.0.0.0:8000
and then go to eclipse
[](https://i.stack.imgur.com/vyGni.png) |
11,441,468 | New to Eclipse and Solr, I imported apache-solr-3.6.0.war into Eclipse and run Solr with tomcat plugin. Now i want to debug some existing code, however how do i import the Solr source code? | 2012/07/11 | [
"https://Stackoverflow.com/questions/11441468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962382/"
] | You can also check out the whole Lucene/Solr source:
1. install Subclipse add-in
2. choose `New...` > `Project...`
3. `SVN` > `Checkout projects from SVN...`
4. add [this link](http://svn.apache.org/repos/asf/lucene/dev) as new repository
5. select branch `/branches/lucene_solr_3_6` (if you want last stable version. Use trunk if you want to use cutting edge source)
6. choose `Check out as a project in a workspace` and leave everything else default
Then, after the checkout completes, to complete setup, you don't have to fiddle with JARs manually, simply:
1. right click on main `build.xml`, the one in your project's root
2. choose `Run As...` > `Ant build...` select (in this order)
3. `ivy-bootstrap` and `resolve` tasks (which will download all JAR dependencies)
4. then run in this order: `validate, clean-idea, eclipse, compile, get-maven-poms, generate-maven-artifacts` (the last two only if you plan to use Maven).
And that's it, you should now see no redness in your workspace and have Lucene and Solr JARs built. | ```
./solr start -p 8983 -f -a "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=0.0.0.0:8000"
```
Start solr with
1. provide app run on port 8983
2. provide Xrunjdwp:transport=dt\_socket
3. remote ip address 0.0.0.0:8000
and then go to eclipse
[](https://i.stack.imgur.com/vyGni.png) |
11,441,468 | New to Eclipse and Solr, I imported apache-solr-3.6.0.war into Eclipse and run Solr with tomcat plugin. Now i want to debug some existing code, however how do i import the Solr source code? | 2012/07/11 | [
"https://Stackoverflow.com/questions/11441468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962382/"
] | Run solr like this:
```
java -jar -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044 start.jar
```
Solr will start, but wait you to connect from Eclipse to continue.
Then in Eclipse, go to:
1. Run / Debug Configurations...
2. Select Remote Java Application
3. Press New button to create a new remote configuration
4. put 1044 on port
5. Click on Debug
This is the standard way to debug remote applications in Java | ```
./solr start -p 8983 -f -a "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=0.0.0.0:8000"
```
Start solr with
1. provide app run on port 8983
2. provide Xrunjdwp:transport=dt\_socket
3. remote ip address 0.0.0.0:8000
and then go to eclipse
[](https://i.stack.imgur.com/vyGni.png) |
10,323,548 | I am not using a coding language. This has to be straight regex.
I need to add a variable length of whitespace between two strings. The string I am passing to the regex has the number of whitespaces in the string itself and will need to be replaced:
```
string1 *27* string2
```
so I need to insert 27 whitespaces into this string between string1 and string 2
```
\*(\d+)\*
```
This is my capture and it appear to be working, but I was trying to setup my replace with this:
```
\s{$1}
```
or this:
```
$&\s{$1}
```
So how would you do it? I am using expresso for my validation, but not all the regex patterns are supported by the text engine I am using. | 2012/04/25 | [
"https://Stackoverflow.com/questions/10323548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183408/"
] | This is not possible with straight regex. Regex would need some sort of parsing capabilities to use the captured variable and translate it into repeating spaces.
The way you want replace to work is not possible, also. As the replace portion of a regex is a straight text replace, and not another regex evaluator....it would be kind of cool to have some sort of recursive regex though :) | One way using a `perl` flavour regexp:
```
perl -e '
$s = q[string1 *27* string2];
$s =~ s/\s+\*(\d+)\*\s+/" " x $1/e;
print $s
'
```
Output:
```
string1 string2
``` |
239,405 | As stated from the questions title:
**What does 'beta' state of a SE site actually imply?**
Could someone elaborate, which restrictions or drawbacks we should expect from a *'beta'* SE site?
I could have well been missing something, that's already been answered, or is an easy to find policies concept. | 2014/09/15 | [
"https://meta.stackexchange.com/questions/239405",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/186472/"
] | Beta sites aren't full sites. They're sites in a "trial" period, to see if they have the potential to become successful sites, or if interest in them wanes and the community dies out. From time to time, the site's community will be asked to [evaluate their site to ensure it is fulfilling its goal](https://meta.stackexchange.com/questions/161033/which-questions-need-community-evaluaton).
However, terms of functionality, beta sites behave like full sites, though with [reduced reputation requirements](https://meta.stackexchange.com/questions/58587/reputation-requirements-compared) for most of the tools, to make it easier for a brand new community to self-moderate.
The main difference between beta and full sites is the presentation. Beta sites all use the same generic theme and don't have a prominent link in the site footer (they're buried under "more"). | Also, in addition to [Troyen's great answer](https://meta.stackexchange.com/a/239406/184589), another significant difference is that on Beta sites there are no moderator elections.
The moderators are instead hand-picked by the Community Managers from the pool of members that contribute with valuable content and demonstrate constant participation. |
239,405 | As stated from the questions title:
**What does 'beta' state of a SE site actually imply?**
Could someone elaborate, which restrictions or drawbacks we should expect from a *'beta'* SE site?
I could have well been missing something, that's already been answered, or is an easy to find policies concept. | 2014/09/15 | [
"https://meta.stackexchange.com/questions/239405",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/186472/"
] | Beta sites aren't full sites. They're sites in a "trial" period, to see if they have the potential to become successful sites, or if interest in them wanes and the community dies out. From time to time, the site's community will be asked to [evaluate their site to ensure it is fulfilling its goal](https://meta.stackexchange.com/questions/161033/which-questions-need-community-evaluaton).
However, terms of functionality, beta sites behave like full sites, though with [reduced reputation requirements](https://meta.stackexchange.com/questions/58587/reputation-requirements-compared) for most of the tools, to make it easier for a brand new community to self-moderate.
The main difference between beta and full sites is the presentation. Beta sites all use the same generic theme and don't have a prominent link in the site footer (they're buried under "more"). | Although this doesn't answer your question specifically, you can glean a lot about how sites are created and grow in Area 51. Some die on the vine too.
[StackExchange Area 51](http://area51.stackexchange.com) |
239,405 | As stated from the questions title:
**What does 'beta' state of a SE site actually imply?**
Could someone elaborate, which restrictions or drawbacks we should expect from a *'beta'* SE site?
I could have well been missing something, that's already been answered, or is an easy to find policies concept. | 2014/09/15 | [
"https://meta.stackexchange.com/questions/239405",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/186472/"
] | Also, in addition to [Troyen's great answer](https://meta.stackexchange.com/a/239406/184589), another significant difference is that on Beta sites there are no moderator elections.
The moderators are instead hand-picked by the Community Managers from the pool of members that contribute with valuable content and demonstrate constant participation. | Although this doesn't answer your question specifically, you can glean a lot about how sites are created and grow in Area 51. Some die on the vine too.
[StackExchange Area 51](http://area51.stackexchange.com) |
47,374,425 | On my app, I'm trying to make it so that if a user has a certain condition, he will ALWAYS be redirected to a certain page, no matter which route he tries to access. In this case, it's if he doesn't have a username (long story).
**ComposerServiceProvider.php** :
```
public function boot() {
View::composer('templates.default', function ($view) {
if(Auth::user()) {
if (Auth::user()->username == null || Auth::user()->username == "") {
return redirect()->route('auth.chooseUsername');
}
```
So I figured the place to do this would be
`ComposerServiceProvider.php`.
However, I'm noticing that my redirect don't work in `ComposerServiceProvider.php`. And `laravel.log` doesn't give me an error or reason why.
The if condition is being met. If I replace `return redirect()->route('auth.chooseUsername');` with `dd('test');`, sure enough all my pages return 'test'.
Why is this happening? | 2017/11/19 | [
"https://Stackoverflow.com/questions/47374425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2280332/"
] | Try this steps:
You can use middleware for this scenario like below:
1. Create middleware `php artisan make:middleware CheckPoint`
Inside `App\Http\Middleware\CheckPoint.php` File
```
use Closure;
class CheckPoint
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if($request->user()) {
if ($request->user()->username == null || $request->user()->username == "") {
return redirect()->route('auth.chooseUsername');
}
}
return $next($request);
}
}
```
2. Add the middleware inside the `app\Http\kernel.php`
```
protected $routeMiddleware = [
'checkPoint' => \App\Http\Middleware\CheckPoint::class,
];
```
3. Then you can use it inside your route file and controller like below
`Route::get(...)->middleware('checkPoint');`
`Route::middleware('checkPoint')->group(function() {
//Group of routes
.....
});`
[More About Middleware](https://laravel.com/docs/5.5/middleware)
[controller middleware](https://laravel.com/docs/5.5/controllers#controller-middleware) | In `App\Http\Middleware` **create a new middleware**:
```
<?php
namespace App\Http\Middleware;
use Closure;
class CheckYourCondition
{
public function handle($request, Closure $next)
{
if (! $request->user()->yourCondition()) {
return redirect('your_target_routre');
}
return $next($request);
}
}
```
Register your middleware by adding it to protected `$routeMiddleware` in `App\Http\Kernel`.
and assing it to the 'web' middleware group in `protected $middlewareGroups`.
For details [see](https://laravel.com/docs/5.5/middleware)
**The ComposerServiceProvider** has a different purpose. It is used to register View Composers.
>
> View composers are callbacks or class methods that are called when a
> view is rendered. If you have data that you want to be bound to a view
> each time that view is rendered, a view composer can help you organize
> that logic into a single location.
>
>
>
[See View Composers](https://laravel.com/docs/5.5/views#view-composers). |
44,027,873 | Here is my problem:
I have a task running a Docker image on Amazon ECS but I would like to make a new Docker image from the running instance of the container.
I see the id of the instance on Amazon ECS; I have made an AMI but I would like to make a new docker image that I can pull from Amazon.
Any ideas?
Regards and thanks. | 2017/05/17 | [
"https://Stackoverflow.com/questions/44027873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462794/"
] | To create a image from container execute the command below:
>
> `docker commit container_id imagename`
>
>
> | You can run `docker commit` ([docs](https://docs.docker.com/engine/reference/commandline/commit/)) to save the container to an image, then push that image with a new tag to the registry. |
44,027,873 | Here is my problem:
I have a task running a Docker image on Amazon ECS but I would like to make a new Docker image from the running instance of the container.
I see the id of the instance on Amazon ECS; I have made an AMI but I would like to make a new docker image that I can pull from Amazon.
Any ideas?
Regards and thanks. | 2017/05/17 | [
"https://Stackoverflow.com/questions/44027873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462794/"
] | To create a image from container execute the command below:
>
> `docker commit container_id imagename`
>
>
> | Apart from the answer provided by @Ben Whaley, I personally suggest you to **make use of Docker APIs.** To use Docker APIs you need to **configure the docker daemon port and the procedure is explained here** [configuring docker daemon port](https://stackoverflow.com/questions/43699368/unable-to-start-docker-after-configuring-daemon-json/43713435#43713435)
**Lets run a container using an base Ubuntu Image and create a folder inside the container**:
```
#docker run -it ubuntu:14.04 /bin/bash
root@58246867493d:/#
root@58246867493d:/# cd /root
root@58246867493d:~# ls
root@58246867493d:~# mkdir TEST_DIR
root@58246867493d:~# exit
```
Status of the exited container:
```
# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
58246867493d ubuntu:14.04 "/bin/bash" 2 minutes ago Exited (127) 57 seconds ago hungry_turing
```
JSON file which is an input for committing a container:
```
#cat container_create.json
{
"AttachStdin": true,
"AttachStdout": true,
"AttachStderr": true,
"ExposedPorts": {
"property1": {},
"property2": {}
},
"Tty": true,
"OpenStdin": true,
"StdinOnce": true,
"Cmd": null,
"Image": "ubuntu:14.04",
"Volumes": {
"additionalProperties": {}
},
"Labels": {
"property1": "string",
"property2": "string"
}
}
```
**API to commit a container**
```
# curl -X POST http://127.0.0.1:6000/commit?container=58246867493d\&repo=ubuntu\&tag=15.0 -d @container_create.json --header "Content-Type: application/json" | jq .
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 593 100 81 100 512 175 1106 --:--:-- --:--:-- --:--:-- 1108
{
"Id": "sha256:acac1f3733b2240b01e335642d2867585e5933b18de2264315f9b07814de113a"
}
```
The Id that is generated is the new Image Id which is build from committing a container.
**Get docker Images**
```
# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
**ubuntu 15.0 acac1f3733b2 10 seconds ago 188MB**
ubuntu 14.04 132b7427a3b4 10 hours ago 188MB
```
Run the newly build Image to see the changes commited in the previous container.
```
# docker run -it ubuntu:15.0 /bin/bash
root@3a48af5eaec9:/# cd /root/
root@3a48af5eaec9:~# ls
TEST_DIR
root@3a48af5eaec9:~# exit
```
To build an image from Docker file, [how to build an image using docker API](https://stackoverflow.com/questions/43800339/how-to-build-an-image-using-docker-api)
For **more information on docker APIs**, refer [here.](https://docs.docker.com/engine/api/v1.28/#operation/ImageCommit) |
44,027,873 | Here is my problem:
I have a task running a Docker image on Amazon ECS but I would like to make a new Docker image from the running instance of the container.
I see the id of the instance on Amazon ECS; I have made an AMI but I would like to make a new docker image that I can pull from Amazon.
Any ideas?
Regards and thanks. | 2017/05/17 | [
"https://Stackoverflow.com/questions/44027873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462794/"
] | To create a image from container execute the command below:
>
> `docker commit container_id imagename`
>
>
> | This can be easily done by using "docker commit".
Let's say you need an image, based on the latest from NGINX, with PHP, build-essential, and nano installed. I'll walk you through the process of pulling the image, running the container, accessing the container, adding the software, and committing the changes to a new image that can then be easily used as a base for your dev containers.
Pulling the image and running the container:
```
sudo docker pull nginx
sudo docker run -it --name nginx-template-base -p 8080:80 nginx
```
Modifying the container:
```
apt-get install nano
apt-get install php5
```
Commit the changes:
```
sudo docker commit CONTAINER_ID nginx-template
```
The newly created template is ready and you can run using:
```
sudo docker run -it --name nginx-dev -p 8080:80 nginx-template
``` |
12,550,086 | I came across some threads on StackOverflow but none of them quite cleared my doubts.
So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code.
```
BST newNode(int x)
{
BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode));
node->Element = x;
node->Left = NULL;
node->Right = NULL;
return node;
}
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
However, when I'm finding the height of this tree I am always getting 0. The height code is
```
int Height(BST T)
{
if (T == NULL)
return 0;
return 1+(max(Height(T->Left), Height(T->Right)));
}
```
and this works perfectly fine when I do insertion recursively (using a function with the exact same signature)
What am I missing? | 2012/09/23 | [
"https://Stackoverflow.com/questions/12550086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123924/"
] | Couldn't solve the problem that way. This code, however, seems to work.
```
BST Insert(int x, BST T)
{
BST temp=T;
BST node=(BST)malloc(sizeof(struct TreeNode));
node->Element=x;
node->Left=NULL;
node->Right=NULL;
if (T==NULL)
{
T=node;
return(T);
//printf("%d\n",T->Element);
}
else
{
while(1)
{
if (temp->Element>=node->Element && temp->Left==NULL)
{
temp->Left=node;
break;
}
else if (temp->Element>=node->Element && temp->Left!=NULL)
{
temp=temp->Left;
}
else if (temp->Element<node->Element && temp->Right==NULL)
{
temp->Right=node;
break;
}
else
{
temp=temp->Right;
}
}
return(T);
}
}
``` | You have the bug in your insert function. As I may assume, initially your tree is empty. so the first time you insert a node, the second argument is NULL, right? Then this function always returns NULL to you as you always pass a NULL value. |
12,550,086 | I came across some threads on StackOverflow but none of them quite cleared my doubts.
So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code.
```
BST newNode(int x)
{
BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode));
node->Element = x;
node->Left = NULL;
node->Right = NULL;
return node;
}
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
However, when I'm finding the height of this tree I am always getting 0. The height code is
```
int Height(BST T)
{
if (T == NULL)
return 0;
return 1+(max(Height(T->Left), Height(T->Right)));
}
```
and this works perfectly fine when I do insertion recursively (using a function with the exact same signature)
What am I missing? | 2012/09/23 | [
"https://Stackoverflow.com/questions/12550086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123924/"
] | Couldn't solve the problem that way. This code, however, seems to work.
```
BST Insert(int x, BST T)
{
BST temp=T;
BST node=(BST)malloc(sizeof(struct TreeNode));
node->Element=x;
node->Left=NULL;
node->Right=NULL;
if (T==NULL)
{
T=node;
return(T);
//printf("%d\n",T->Element);
}
else
{
while(1)
{
if (temp->Element>=node->Element && temp->Left==NULL)
{
temp->Left=node;
break;
}
else if (temp->Element>=node->Element && temp->Left!=NULL)
{
temp=temp->Left;
}
else if (temp->Element<node->Element && temp->Right==NULL)
{
temp->Right=node;
break;
}
else
{
temp=temp->Right;
}
}
return(T);
}
}
``` | ```
template <class T>
class TreeNode{
private:
T data;
TreeNode<T>* right,*left;
public:
void setData(T d){
this->data =d;
}
T getData(){
return this->data;
}
void setRight(TreeNode<T>* r){
this->right =r;
}
TreeNode<T>* getRight(){
return this->right;
}
void setLeft(TreeNode<T>* r){
this->left =r;
}
TreeNode<T>* getLeft(){
return this->left;
}
static TreeNode<T>* newNode(T data){
TreeNode<T>* n = new TreeNode<T>();
n->setData(data);
n->setRight(NULL);
n->setLeft(NULL);
return n;
}
};
template <class T>
class BinaryTree{
private:
TreeNode<T>* root;
public:
void insert(T data){
TreeNode<T>* n = TreeNode<T>::newNode(data);
if(root==NULL)
root = n;
else{
TreeNode<T>* t = root;
while(t!=NULL){
if(n->getData() >= t->getData()){
if(t->getRight()==NULL){
t->setRight(n); //newnode attached as right child in tree
t = NULL;
}
else
t = t->getRight();
}
else{
if(t->getLeft()==NULL){
t->setLeft(n); //newnode attached as left child in tree
t=NULL;
}
else
t = t->getLeft();
}
}
}
}
void preorder(){
TreeNode<T>* t = root;
preorderUtil(t);
}
void preorderUtil(TreeNode<T>* node){
if(node==NULL)
return;
preorderUtil(node->getLeft());
cout<<node->getData()<<" ";
preorderUtil(node->getRight());
}
};
```
**Your changes are not reflected in the tree**. I followed this way to insert data iteratively and it works fine. The point is making a node inside your binarytree to point the newly created node such that it gets attached to the tree. |
12,550,086 | I came across some threads on StackOverflow but none of them quite cleared my doubts.
So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code.
```
BST newNode(int x)
{
BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode));
node->Element = x;
node->Left = NULL;
node->Right = NULL;
return node;
}
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
However, when I'm finding the height of this tree I am always getting 0. The height code is
```
int Height(BST T)
{
if (T == NULL)
return 0;
return 1+(max(Height(T->Left), Height(T->Right)));
}
```
and this works perfectly fine when I do insertion recursively (using a function with the exact same signature)
What am I missing? | 2012/09/23 | [
"https://Stackoverflow.com/questions/12550086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123924/"
] | Couldn't solve the problem that way. This code, however, seems to work.
```
BST Insert(int x, BST T)
{
BST temp=T;
BST node=(BST)malloc(sizeof(struct TreeNode));
node->Element=x;
node->Left=NULL;
node->Right=NULL;
if (T==NULL)
{
T=node;
return(T);
//printf("%d\n",T->Element);
}
else
{
while(1)
{
if (temp->Element>=node->Element && temp->Left==NULL)
{
temp->Left=node;
break;
}
else if (temp->Element>=node->Element && temp->Left!=NULL)
{
temp=temp->Left;
}
else if (temp->Element<node->Element && temp->Right==NULL)
{
temp->Right=node;
break;
}
else
{
temp=temp->Right;
}
}
return(T);
}
}
``` | Here is my version , it seems to be working.
```
struct tree{
tree *left;
tree *right;
int key;
};
void insertBst(int k,tree *t)
{
tree *newK = new tree[sizeof(tree)];
newK->key = k;
newK->left = NULL;
newK->right = NULL;
if((t)->key == NULL)
{
t=newK;
return;
}
else{
bool found = false;
tree *root = t;
tree *parent = NULL;
while(root != NULL)
{
parent = root;
if(root->key < newK->key)
{
root=root->right;
}
else if(root->key > newK->key)
{
root=root->left;
}
else{
//Here we have duplicates!! so do nothing
root = root;
}
}
if(parent->key > newK->key) parent->left = newK;
else parent->right = newK;
}
}
``` |
12,550,086 | I came across some threads on StackOverflow but none of them quite cleared my doubts.
So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code.
```
BST newNode(int x)
{
BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode));
node->Element = x;
node->Left = NULL;
node->Right = NULL;
return node;
}
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
However, when I'm finding the height of this tree I am always getting 0. The height code is
```
int Height(BST T)
{
if (T == NULL)
return 0;
return 1+(max(Height(T->Left), Height(T->Right)));
}
```
and this works perfectly fine when I do insertion recursively (using a function with the exact same signature)
What am I missing? | 2012/09/23 | [
"https://Stackoverflow.com/questions/12550086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123924/"
] | Here:
```
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
You navigate the tree until you hit `T == NULL`. Then you create a node and assign the pointer to it to `T`. Then you return the original value of `T`. You don't modify your tree at all. No node in it is made to point to the newly created node. `T` is just a local variable. | Here is my version , it seems to be working.
```
struct tree{
tree *left;
tree *right;
int key;
};
void insertBst(int k,tree *t)
{
tree *newK = new tree[sizeof(tree)];
newK->key = k;
newK->left = NULL;
newK->right = NULL;
if((t)->key == NULL)
{
t=newK;
return;
}
else{
bool found = false;
tree *root = t;
tree *parent = NULL;
while(root != NULL)
{
parent = root;
if(root->key < newK->key)
{
root=root->right;
}
else if(root->key > newK->key)
{
root=root->left;
}
else{
//Here we have duplicates!! so do nothing
root = root;
}
}
if(parent->key > newK->key) parent->left = newK;
else parent->right = newK;
}
}
``` |
12,550,086 | I came across some threads on StackOverflow but none of them quite cleared my doubts.
So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code.
```
BST newNode(int x)
{
BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode));
node->Element = x;
node->Left = NULL;
node->Right = NULL;
return node;
}
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
However, when I'm finding the height of this tree I am always getting 0. The height code is
```
int Height(BST T)
{
if (T == NULL)
return 0;
return 1+(max(Height(T->Left), Height(T->Right)));
}
```
and this works perfectly fine when I do insertion recursively (using a function with the exact same signature)
What am I missing? | 2012/09/23 | [
"https://Stackoverflow.com/questions/12550086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123924/"
] | Couldn't solve the problem that way. This code, however, seems to work.
```
BST Insert(int x, BST T)
{
BST temp=T;
BST node=(BST)malloc(sizeof(struct TreeNode));
node->Element=x;
node->Left=NULL;
node->Right=NULL;
if (T==NULL)
{
T=node;
return(T);
//printf("%d\n",T->Element);
}
else
{
while(1)
{
if (temp->Element>=node->Element && temp->Left==NULL)
{
temp->Left=node;
break;
}
else if (temp->Element>=node->Element && temp->Left!=NULL)
{
temp=temp->Left;
}
else if (temp->Element<node->Element && temp->Right==NULL)
{
temp->Right=node;
break;
}
else
{
temp=temp->Right;
}
}
return(T);
}
}
``` | Here's My implementation of the aforementioned problem:
```
bst* newNode(int x)
{
bst* T = new bst;
T->value = x;
T->left_child = T->right_child = NULL;
return T;
}
bst* bst_insert_iter(bst* T,int val)
{
if (T == NULL)
T = newNode(val);
else
{
bst *temp_node = T;
bool flag = true;
while(flag)
{
if (val <= temp_node->value)
{
if (temp_node->left_child == NULL)
{
temp_node->left_child=newNode(val);
flag = false;
}
else
temp_node = temp_node->left_child;
}
else
{
if (temp_node->right_child == NULL)
{
temp_node->right_child=newNode(val);
flag = false;
}
else
temp_node = temp_node->right_child;
}
}
}
return T;
}
``` |
12,550,086 | I came across some threads on StackOverflow but none of them quite cleared my doubts.
So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code.
```
BST newNode(int x)
{
BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode));
node->Element = x;
node->Left = NULL;
node->Right = NULL;
return node;
}
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
However, when I'm finding the height of this tree I am always getting 0. The height code is
```
int Height(BST T)
{
if (T == NULL)
return 0;
return 1+(max(Height(T->Left), Height(T->Right)));
}
```
and this works perfectly fine when I do insertion recursively (using a function with the exact same signature)
What am I missing? | 2012/09/23 | [
"https://Stackoverflow.com/questions/12550086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123924/"
] | Couldn't solve the problem that way. This code, however, seems to work.
```
BST Insert(int x, BST T)
{
BST temp=T;
BST node=(BST)malloc(sizeof(struct TreeNode));
node->Element=x;
node->Left=NULL;
node->Right=NULL;
if (T==NULL)
{
T=node;
return(T);
//printf("%d\n",T->Element);
}
else
{
while(1)
{
if (temp->Element>=node->Element && temp->Left==NULL)
{
temp->Left=node;
break;
}
else if (temp->Element>=node->Element && temp->Left!=NULL)
{
temp=temp->Left;
}
else if (temp->Element<node->Element && temp->Right==NULL)
{
temp->Right=node;
break;
}
else
{
temp=temp->Right;
}
}
return(T);
}
}
``` | Here:
```
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
You navigate the tree until you hit `T == NULL`. Then you create a node and assign the pointer to it to `T`. Then you return the original value of `T`. You don't modify your tree at all. No node in it is made to point to the newly created node. `T` is just a local variable. |
12,550,086 | I came across some threads on StackOverflow but none of them quite cleared my doubts.
So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code.
```
BST newNode(int x)
{
BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode));
node->Element = x;
node->Left = NULL;
node->Right = NULL;
return node;
}
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
However, when I'm finding the height of this tree I am always getting 0. The height code is
```
int Height(BST T)
{
if (T == NULL)
return 0;
return 1+(max(Height(T->Left), Height(T->Right)));
}
```
and this works perfectly fine when I do insertion recursively (using a function with the exact same signature)
What am I missing? | 2012/09/23 | [
"https://Stackoverflow.com/questions/12550086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123924/"
] | Here's My implementation of the aforementioned problem:
```
bst* newNode(int x)
{
bst* T = new bst;
T->value = x;
T->left_child = T->right_child = NULL;
return T;
}
bst* bst_insert_iter(bst* T,int val)
{
if (T == NULL)
T = newNode(val);
else
{
bst *temp_node = T;
bool flag = true;
while(flag)
{
if (val <= temp_node->value)
{
if (temp_node->left_child == NULL)
{
temp_node->left_child=newNode(val);
flag = false;
}
else
temp_node = temp_node->left_child;
}
else
{
if (temp_node->right_child == NULL)
{
temp_node->right_child=newNode(val);
flag = false;
}
else
temp_node = temp_node->right_child;
}
}
}
return T;
}
``` | You have the bug in your insert function. As I may assume, initially your tree is empty. so the first time you insert a node, the second argument is NULL, right? Then this function always returns NULL to you as you always pass a NULL value. |
12,550,086 | I came across some threads on StackOverflow but none of them quite cleared my doubts.
So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code.
```
BST newNode(int x)
{
BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode));
node->Element = x;
node->Left = NULL;
node->Right = NULL;
return node;
}
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
However, when I'm finding the height of this tree I am always getting 0. The height code is
```
int Height(BST T)
{
if (T == NULL)
return 0;
return 1+(max(Height(T->Left), Height(T->Right)));
}
```
and this works perfectly fine when I do insertion recursively (using a function with the exact same signature)
What am I missing? | 2012/09/23 | [
"https://Stackoverflow.com/questions/12550086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123924/"
] | Here:
```
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
You navigate the tree until you hit `T == NULL`. Then you create a node and assign the pointer to it to `T`. Then you return the original value of `T`. You don't modify your tree at all. No node in it is made to point to the newly created node. `T` is just a local variable. | ```
template <class T>
class TreeNode{
private:
T data;
TreeNode<T>* right,*left;
public:
void setData(T d){
this->data =d;
}
T getData(){
return this->data;
}
void setRight(TreeNode<T>* r){
this->right =r;
}
TreeNode<T>* getRight(){
return this->right;
}
void setLeft(TreeNode<T>* r){
this->left =r;
}
TreeNode<T>* getLeft(){
return this->left;
}
static TreeNode<T>* newNode(T data){
TreeNode<T>* n = new TreeNode<T>();
n->setData(data);
n->setRight(NULL);
n->setLeft(NULL);
return n;
}
};
template <class T>
class BinaryTree{
private:
TreeNode<T>* root;
public:
void insert(T data){
TreeNode<T>* n = TreeNode<T>::newNode(data);
if(root==NULL)
root = n;
else{
TreeNode<T>* t = root;
while(t!=NULL){
if(n->getData() >= t->getData()){
if(t->getRight()==NULL){
t->setRight(n); //newnode attached as right child in tree
t = NULL;
}
else
t = t->getRight();
}
else{
if(t->getLeft()==NULL){
t->setLeft(n); //newnode attached as left child in tree
t=NULL;
}
else
t = t->getLeft();
}
}
}
}
void preorder(){
TreeNode<T>* t = root;
preorderUtil(t);
}
void preorderUtil(TreeNode<T>* node){
if(node==NULL)
return;
preorderUtil(node->getLeft());
cout<<node->getData()<<" ";
preorderUtil(node->getRight());
}
};
```
**Your changes are not reflected in the tree**. I followed this way to insert data iteratively and it works fine. The point is making a node inside your binarytree to point the newly created node such that it gets attached to the tree. |
12,550,086 | I came across some threads on StackOverflow but none of them quite cleared my doubts.
So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code.
```
BST newNode(int x)
{
BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode));
node->Element = x;
node->Left = NULL;
node->Right = NULL;
return node;
}
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
However, when I'm finding the height of this tree I am always getting 0. The height code is
```
int Height(BST T)
{
if (T == NULL)
return 0;
return 1+(max(Height(T->Left), Height(T->Right)));
}
```
and this works perfectly fine when I do insertion recursively (using a function with the exact same signature)
What am I missing? | 2012/09/23 | [
"https://Stackoverflow.com/questions/12550086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123924/"
] | Here:
```
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
You navigate the tree until you hit `T == NULL`. Then you create a node and assign the pointer to it to `T`. Then you return the original value of `T`. You don't modify your tree at all. No node in it is made to point to the newly created node. `T` is just a local variable. | You have the bug in your insert function. As I may assume, initially your tree is empty. so the first time you insert a node, the second argument is NULL, right? Then this function always returns NULL to you as you always pass a NULL value. |
12,550,086 | I came across some threads on StackOverflow but none of them quite cleared my doubts.
So the problem is simple. I need to iteratively insert elements into a binary tree. And this is my code.
```
BST newNode(int x)
{
BSTNodePtr node = (BSTNodePtr) malloc(sizeof(struct TreeNode));
node->Element = x;
node->Left = NULL;
node->Right = NULL;
return node;
}
BST Insert(int x, BST T)
{
BST temp_node = T;
while( T != NULL) {
if (x < T->Element)
T = T->Left;
else if (x >= T->Element)
T = T->Right;
}
T = newNode(x);
return temp_node;
}
```
However, when I'm finding the height of this tree I am always getting 0. The height code is
```
int Height(BST T)
{
if (T == NULL)
return 0;
return 1+(max(Height(T->Left), Height(T->Right)));
}
```
and this works perfectly fine when I do insertion recursively (using a function with the exact same signature)
What am I missing? | 2012/09/23 | [
"https://Stackoverflow.com/questions/12550086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123924/"
] | Here's My implementation of the aforementioned problem:
```
bst* newNode(int x)
{
bst* T = new bst;
T->value = x;
T->left_child = T->right_child = NULL;
return T;
}
bst* bst_insert_iter(bst* T,int val)
{
if (T == NULL)
T = newNode(val);
else
{
bst *temp_node = T;
bool flag = true;
while(flag)
{
if (val <= temp_node->value)
{
if (temp_node->left_child == NULL)
{
temp_node->left_child=newNode(val);
flag = false;
}
else
temp_node = temp_node->left_child;
}
else
{
if (temp_node->right_child == NULL)
{
temp_node->right_child=newNode(val);
flag = false;
}
else
temp_node = temp_node->right_child;
}
}
}
return T;
}
``` | Here is my version , it seems to be working.
```
struct tree{
tree *left;
tree *right;
int key;
};
void insertBst(int k,tree *t)
{
tree *newK = new tree[sizeof(tree)];
newK->key = k;
newK->left = NULL;
newK->right = NULL;
if((t)->key == NULL)
{
t=newK;
return;
}
else{
bool found = false;
tree *root = t;
tree *parent = NULL;
while(root != NULL)
{
parent = root;
if(root->key < newK->key)
{
root=root->right;
}
else if(root->key > newK->key)
{
root=root->left;
}
else{
//Here we have duplicates!! so do nothing
root = root;
}
}
if(parent->key > newK->key) parent->left = newK;
else parent->right = newK;
}
}
``` |
2,289,518 | >
> How to calculate $5^{2003}$ mod $13$
>
>
>
using fermats little theorem
5^13-1 1 mod 13
(5^12)^166+11 mod 13
a+b modn=(a modn + b modn) modn
(1+11mod13)mod13
12 mod 13 = 12
why answer is 8 ?
how do we calculate this
thanks | 2017/05/20 | [
"https://math.stackexchange.com/questions/2289518",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/437586/"
] | All modulo 13,
$$5^{2003} \equiv (5^{2})^{1001} (5)$$
$$\equiv (-1)^{1001}(5)$$
$$\equiv -5$$
$$\equiv 8$$ | $5^{13-1}= 5^{12} \equiv 1 \mod 13$
$5^{2003} = 5^{12\*166 +11} = (5^{12})^{166}\*5^{11} \equiv 5^{11} \mod 13$
$5^{11}\*5 = 5^{12}\equiv 1 \mod 13$
So if $5^{11} \equiv x \mod 13$ then $5^{11}$ is a solution to $5x \equiv 1 \mod 13$.
....
$5x \equiv 1,14,27,40 \mod 13$ so $5^{11} \equiv x\equiv 8 \equiv -5 \mod 13$.
.....
Or we could do $5^2 = 25 \equiv -1 \mod 13$ so $5^4 \equiv 1 \mod 13$ so $5^{11} \equiv 5^3 \equiv -5 \equiv 8 \mod 13$.
......
Those were trial and error. If we *had* to, we could use Euclid's algorithm to solve
$5x = 13k + 1$.
$5x = 10k + 3k + 1$
$5(x - 2k) = 3k + 1$. Let $v = x - 2k$
$5v = 3k + 1$
$3v + 2v = 3k + 1$
$3(v - k) + 2v = 1$ Let $w = v -k$
$3w + 2v = 1$
$w + 2(w+v) = 1$. Let $z = w+v$
$w + 2z = 1$. Let $z = 0; w = 1$
$z = w+v \implies 0 = 1 + v\implies v = -1$
$w = v-k\implies 1= - 1 -k\implies k = -2$
$v = x - 2k \implies -1 = x + 4 \implies x = -5$.
So $5^{11} \equiv x \equiv- 5 \equiv 8 \mod 13$. |
54,736,145 | -How can I scale the Y- and X- axis to 0,30 and 0,50 respectively and plot the data point according to the scale?
-How do I change the color of groups 1, 2 and 3 to purple, orange and yellow?
```
library(ggplot2)
library(plotly)
ID <- c("Group 1", "Group 1", "Group 1", "Group 2", "Group 2", "Group 2", "Group 3", "Group 3", "Group 3", "Group 4", "Group 4", "Group 4")
area <- c("Area 1", "Area 1", "Area 1","Area 2", "Area 2", "Area 2", "Area 3", "Area 3", "Area 3", "Area 4", "Area 4", "Area 4")
x <- c(1.0, 10.25, 50.0, 2.0, 5.0, 30.0, 5.0, 9.0, 10.0, 11.0, 23.0, 40.0)
y <- c(1.0, 3.0, 5.0, 20.0, 10.0, 23.0, 25.0, 19.1, 5.0, 15.0, 8.0, 4.0)
df <- cbind(ID, area, x, y)
df <- as.data.frame(df)
df
p <- ggplot(df, aes(x=x, y=y)) + geom_polygon(aes(fill=factor(ID), group=area))
p <- ggplotly(p)
p
```
[](https://i.stack.imgur.com/qY4eh.png)
I have tried to play around with scale\_x\_continuous, scale\_fill\_manual, and scale\_fill\_identity but it doesn`t seem to do anything. | 2019/02/17 | [
"https://Stackoverflow.com/questions/54736145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9710121/"
] | First, convert the x and y columns to number (they are factors in the data). Then, set the scale limits using scale\_x\_continuous and scale\_y\_continuous. Finally, use scale\_fill\_manual to change the colors (since you have a fourth group, I gave it another color).
```
library(tidyverse)
df <- df %>% mutate(x = parse_number(x),
y = parse_number(y))
p <- ggplot(df, aes(x=x, y=y)) + geom_polygon(aes(fill=factor(ID), group=area)) +
scale_x_continuous(limits = c(0,50)) +
scale_y_continuous(limits = c(0,30)) +
scale_fill_manual(values = c("purple", "orange", "yellow", "gray40"))
ggplotly(p)
``` | From the above comments I could solve it like this.
```
library(ggplot2)
library(plotly)
ID <- c("Group 1", "Group 1", "Group 1", "Group 2", "Group 2", "Group 2", "Group 3", "Group 3", "Group 3", "Group 1", "Group 1", "Group 1")
area <- c("Area 1", "Area 1", "Area 1","Area 2", "Area 2", "Area 2", "Area 3", "Area 3", "Area 3", "Area 4", "Area 4", "Area 4")
colours <- c("Purple", "Purple", "Purple", "Green", "Green", "Green", "yellow", "yellow", "yellow", "Purple", "Purple", "Purple")
x <- c(1.0, 10.25, 50.0, 2.0, 5.0, 30.0, 5.0, 9.0, 10.0, 11.0, 23.0, 40.0)
y <- c(1.0, 3.0, 5.0, 20.0, 10.0, 23.0, 25.0, 19.1, 5.0, 15.0, 8.0, 4.0)
df <- data.frame(ID, area, colours, x, y, stringsAsFactors = FALSE )
###Get colours
colours_poly <- setNames(df$colours, df$ID)
colours_poly
p <- ggplot(df, aes(x=x, y=y)) + geom_polygon(aes(fill=factor(ID), group=area)) +
scale_x_continuous(limits = c(0,50)) +
scale_y_continuous(limits = c(0,30)) +
scale_fill_manual(values = colours_poly)
p <- ggplotly(p)
p
```
Thanks a lot!
[](https://i.stack.imgur.com/dOYfY.png) |
29,226,198 | I'm looking for function that **Open window explorer in C language**. I have found this [answer]**([How can I open Windows Explorer to a certain directory from within a WPF app?](https://stackoverflow.com/questions/1746079/how-can-i-open-windows-explorer-to-a-certain-directory-from-within-a-wpf-app))**, but this is C# language. **C can't have these features**? I use VS 2010.
I'm a beginner of C. So my question may seem ridiculously easy. But if you give me the answer I really appreciate it. Thanks :) | 2015/03/24 | [
"https://Stackoverflow.com/questions/29226198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4427613/"
] | Try using SHOpenFolderAndSelectItems() function, which can open files in windows explorer.
<https://msdn.microsoft.com/en-us/library/windows/desktop/bb762232(v=vs.85).aspx> | Given the stslib.h library contains the system() function that let's you run shell commands, you should be able to run the command to open a new windows explorer window using the same command you would use in the terminal window.
A guideline: <http://www.programmingsimplified.com/c-program-shutdown-computer> |
29,226,198 | I'm looking for function that **Open window explorer in C language**. I have found this [answer]**([How can I open Windows Explorer to a certain directory from within a WPF app?](https://stackoverflow.com/questions/1746079/how-can-i-open-windows-explorer-to-a-certain-directory-from-within-a-wpf-app))**, but this is C# language. **C can't have these features**? I use VS 2010.
I'm a beginner of C. So my question may seem ridiculously easy. But if you give me the answer I really appreciate it. Thanks :) | 2015/03/24 | [
"https://Stackoverflow.com/questions/29226198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4427613/"
] | The simplest way to open a certain directory in an explorer (here c:\program files) may be:
```
system("start \"\" \"c:\\program files\"");
``` | Try using SHOpenFolderAndSelectItems() function, which can open files in windows explorer.
<https://msdn.microsoft.com/en-us/library/windows/desktop/bb762232(v=vs.85).aspx> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.