qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
58,539,906
I have widget with following info: ``` <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="328dp" android:minHeight="56dp" android:updatePeriodMillis="1000000" android:initialLayout="@layout/home_widget" android:previewImage="@drawable/widget_preview" android:resizeMode="horizontal" android:widgetCategory="home_screen"> </appwidget-provider> ``` The layout (not necessary to put it here) looks good on my device, but I found out that the widget is not applicable for smaller screen. Can somebody help me solve this issue? Instead of not displaying this widget on smaller devices, I would like to alter the layout (maybe create another xml layout for it). I tried putting `minWidth` to dimens, but as I have all the widget elements positioned and sized precisely, this approach would cut the widget. Thanks for any help.
2019/10/24
[ "https://Stackoverflow.com/questions/58539906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1619036/" ]
Screen density is not same for all devices, hence a best solution is to introduce `ssp` and `sdp` instead of `dp` which is fixed for all devices `ssp` is used for setting size to text and [sdp](https://github.com/intuit/sdp) is used for layouts. <https://github.com/intuit/sdp>
becuase of we use diffrent screen size and diffrent density of the screen to solve this dont use dp or sp rather than use sdp or ssp which is provide in this library <https://github.com/intuit/sdp> And this make your space preamter screen responsive
58,539,906
I have widget with following info: ``` <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="328dp" android:minHeight="56dp" android:updatePeriodMillis="1000000" android:initialLayout="@layout/home_widget" android:previewImage="@drawable/widget_preview" android:resizeMode="horizontal" android:widgetCategory="home_screen"> </appwidget-provider> ``` The layout (not necessary to put it here) looks good on my device, but I found out that the widget is not applicable for smaller screen. Can somebody help me solve this issue? Instead of not displaying this widget on smaller devices, I would like to alter the layout (maybe create another xml layout for it). I tried putting `minWidth` to dimens, but as I have all the widget elements positioned and sized precisely, this approach would cut the widget. Thanks for any help.
2019/10/24
[ "https://Stackoverflow.com/questions/58539906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1619036/" ]
becuase of we use diffrent screen size and diffrent density of the screen to solve this dont use dp or sp rather than use sdp or ssp which is provide in this library <https://github.com/intuit/sdp> And this make your space preamter screen responsive
As mentioned above, **different phones got different screen sizes** so when using a fixed size value (`328dp` for example) your layout may not be responsive to all devices. --- *Naman's* answer will work for you, you can use something like this: ``` <view android:layout_height="@dimen/_100sdp" android:width="@dimen/_100sdp" /> ``` But you can also use [ConstraintLayout](https://developer.android.com/training/constraint-layout) to tell your views how to spread on your screen with percents, like this: ``` <view android:layout_height="0dp" android:layout_width="0dp" app:layout_constraintHeight_percent="0.2" app:layout_constraintWidth_percent="0.3" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> ``` With this solution, your view will be equal to `30%` of the screen width, `20%` of its height and will remain responsive to all screen sizes.
58,539,906
I have widget with following info: ``` <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="328dp" android:minHeight="56dp" android:updatePeriodMillis="1000000" android:initialLayout="@layout/home_widget" android:previewImage="@drawable/widget_preview" android:resizeMode="horizontal" android:widgetCategory="home_screen"> </appwidget-provider> ``` The layout (not necessary to put it here) looks good on my device, but I found out that the widget is not applicable for smaller screen. Can somebody help me solve this issue? Instead of not displaying this widget on smaller devices, I would like to alter the layout (maybe create another xml layout for it). I tried putting `minWidth` to dimens, but as I have all the widget elements positioned and sized precisely, this approach would cut the widget. Thanks for any help.
2019/10/24
[ "https://Stackoverflow.com/questions/58539906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1619036/" ]
Screen density is not same for all devices, hence a best solution is to introduce `ssp` and `sdp` instead of `dp` which is fixed for all devices `ssp` is used for setting size to text and [sdp](https://github.com/intuit/sdp) is used for layouts. <https://github.com/intuit/sdp>
If you want widget width match as parent then you can use the `android:layout_width="match_parent"` `match_parent` defines the width/height as match of parent, there is not any need to define the static dimen. It is adjust the width according to parent's width. I hope its work for you.
58,539,906
I have widget with following info: ``` <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="328dp" android:minHeight="56dp" android:updatePeriodMillis="1000000" android:initialLayout="@layout/home_widget" android:previewImage="@drawable/widget_preview" android:resizeMode="horizontal" android:widgetCategory="home_screen"> </appwidget-provider> ``` The layout (not necessary to put it here) looks good on my device, but I found out that the widget is not applicable for smaller screen. Can somebody help me solve this issue? Instead of not displaying this widget on smaller devices, I would like to alter the layout (maybe create another xml layout for it). I tried putting `minWidth` to dimens, but as I have all the widget elements positioned and sized precisely, this approach would cut the widget. Thanks for any help.
2019/10/24
[ "https://Stackoverflow.com/questions/58539906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1619036/" ]
As mentioned above, **different phones got different screen sizes** so when using a fixed size value (`328dp` for example) your layout may not be responsive to all devices. --- *Naman's* answer will work for you, you can use something like this: ``` <view android:layout_height="@dimen/_100sdp" android:width="@dimen/_100sdp" /> ``` But you can also use [ConstraintLayout](https://developer.android.com/training/constraint-layout) to tell your views how to spread on your screen with percents, like this: ``` <view android:layout_height="0dp" android:layout_width="0dp" app:layout_constraintHeight_percent="0.2" app:layout_constraintWidth_percent="0.3" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> ``` With this solution, your view will be equal to `30%` of the screen width, `20%` of its height and will remain responsive to all screen sizes.
If you want widget width match as parent then you can use the `android:layout_width="match_parent"` `match_parent` defines the width/height as match of parent, there is not any need to define the static dimen. It is adjust the width according to parent's width. I hope its work for you.
58,539,906
I have widget with following info: ``` <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="328dp" android:minHeight="56dp" android:updatePeriodMillis="1000000" android:initialLayout="@layout/home_widget" android:previewImage="@drawable/widget_preview" android:resizeMode="horizontal" android:widgetCategory="home_screen"> </appwidget-provider> ``` The layout (not necessary to put it here) looks good on my device, but I found out that the widget is not applicable for smaller screen. Can somebody help me solve this issue? Instead of not displaying this widget on smaller devices, I would like to alter the layout (maybe create another xml layout for it). I tried putting `minWidth` to dimens, but as I have all the widget elements positioned and sized precisely, this approach would cut the widget. Thanks for any help.
2019/10/24
[ "https://Stackoverflow.com/questions/58539906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1619036/" ]
Screen density is not same for all devices, hence a best solution is to introduce `ssp` and `sdp` instead of `dp` which is fixed for all devices `ssp` is used for setting size to text and [sdp](https://github.com/intuit/sdp) is used for layouts. <https://github.com/intuit/sdp>
As mentioned above, **different phones got different screen sizes** so when using a fixed size value (`328dp` for example) your layout may not be responsive to all devices. --- *Naman's* answer will work for you, you can use something like this: ``` <view android:layout_height="@dimen/_100sdp" android:width="@dimen/_100sdp" /> ``` But you can also use [ConstraintLayout](https://developer.android.com/training/constraint-layout) to tell your views how to spread on your screen with percents, like this: ``` <view android:layout_height="0dp" android:layout_width="0dp" app:layout_constraintHeight_percent="0.2" app:layout_constraintWidth_percent="0.3" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> ``` With this solution, your view will be equal to `30%` of the screen width, `20%` of its height and will remain responsive to all screen sizes.
30,210,685
I am very new to android app development. I am designing the layout of an Activity of an Android project in android studio. I am noticing a strange behavior and I am not able to find a solution. In the design view I am seeing the following view being generated for the following code. View generated: ![View generated](https://i.stack.imgur.com/gTRnY.png) Code: ```html <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".RegistrationActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:orientation="vertical"> <LinearLayout android:gravity="center" android:layout_width="match_parent" android:layout_height="200dp" android:orientation="horizontal"> <ImageView android:id="@+id/imageView" android:layout_width="200dp" android:layout_height="200dp" android:src="@drawable/test" /> <LinearLayout android:layout_width="200dp" android:layout_height="match_parent" android:layout_marginLeft="20dp" android:orientation="vertical"> <Button android:id="@+id/button" android:layout_marginTop="20dp" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/GalleryImagePicker" /> <TextView android:layout_marginTop="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:id="@+id/ORTextView" android:text="OR" android:layout_marginLeft="10dp" /> <Button android:layout_marginTop="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" style="?android:attr/buttonStyleSmall" android:text="@string/FacebookImagePicker" android:id="@+id/button2" android:layout_gravity="right"/> </LinearLayout> </LinearLayout> </LinearLayout> </RelativeLayout> ``` As you can see in the view the device I have selected is Nexus 5, which has a 1080p display. The view generated is also exactly the same in Genymotion emulator running Nexus 5 android 5.1 Now if I deploy the same application to Sony Xperia Z Ultra device (running android 5.0) which also has a 1080p display the view I get is: ![Xperia Z Ultra rendered view](https://i.stack.imgur.com/euCQf.png) What is the reason behind these two different behaviors?
2015/05/13
[ "https://Stackoverflow.com/questions/30210685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797372/" ]
The reason for the seemingly odd behaviour in your question is because the width of Nexus 5 and Xperia Z Ultra are different in dps (density independent pixels) You need to prepare different layout files based on size qualifiers to give the same look across multiple devices. Take a look [here](http://developer.android.com/training/multiscreen/screensizes.html). If you use smallest width(sw) as a size qualifier, Nexus 5 will use layout from sw320dp and Xperia Z ultra will use layout from sw480dp proving the fact that they have different widths in dps.
You should use the relative positions for the layout parameters, do not use hard coded (fixed) values. Relative positions will be rendered accordingly on different screen size and density devices. You can refer [this link](http://developer.android.com/training/multiscreen/screensizes.html)
97,927
If we have a rewrite system for primitive recursive functions, which simplifies each term according to how the function was defined, then what is the computational complexity of this calculation? That is, what is the coplexity of the normalization procedure? I have heard a claim that for a closed term calculating the value of the function requires transfinte induction up to $\epsilon\_0$. Is this true and where can I find a proof of this? For example in (Schwichtenberg & Wainer 2012) there is a lemma which says that a primitive recursive function is computable in $F\_{\alpha}$-bounded time, for some $\alpha<\omega$, where the set of all $F\_{\alpha}$ for $\alpha<\epsilon\_0$ is the Fast Growing Hierarchy. Is the measure of transfinite induction related to this way of bounding the complexity?
2012/05/25
[ "https://mathoverflow.net/questions/97927", "https://mathoverflow.net", "https://mathoverflow.net/users/23947/" ]
I find some aspects of this question difficult to understand. For example, the part about "calculating the value of the function requires transfinite induction up to $\varepsilon\_0$" seems to conflate methods of proof (like transfinite induction) with methods of computation. Also, much (if not all) of the question appears to be about primitive recursive functionals of higher type (as in Gödel's Dialectica interpretation) rather than mere primitive recursive functions. So, the following may not be what the OP was looking for, but here goes anyway: Not much can be said about the time complexity of computing primitive recursive functions (from natural numbers to natural numbers) except that it's primitive recursive and thus bounded by a finite level $F\_n$ of the Grzegorczyk hierarchy (essentially equivalent to the fast-growing hierarchy, I believe). On the other hand, for primitive recursive functionals of finite type, you can consider the problem of evaluating terms of type 0 (i.e., terms that denote natural numbers). Here, the only bound I can see for the time-complexity is level $\varepsilon\_0$ of the Grzegorczyk hierarchy. For any fixed primitive recursive functional, evaluation of its numerical values would take time bounded by $F\_\alpha$ for some $\alpha<\varepsilon\_0$, but different functionals would need different $\alpha$'s, with no uniform bound below $\varepsilon\_0$. The relevance of the proof principle of transfinite induction up to $\varepsilon\_0$ (for open formulas) is that this is what is needed, on top of primitive recursive arithmetic, to prove that every closed term of type 0, built from primitive recursive functionals of higher type, can be reduced to a numerical value.
Actually there is no need for any transfinite induction. A monotone interpretation yields that the derivation lengths for any fixed term will be primitive recursive in the values of the numerals plugged in. I have a paper in APAL with Cichon on the topic and, in addition, a paper in JSL regarding Goedel's T showing that for T one needs epsilon\_0 recursion for proving strong normalization by a monotone interpretation. Best, Andreas
97,927
If we have a rewrite system for primitive recursive functions, which simplifies each term according to how the function was defined, then what is the computational complexity of this calculation? That is, what is the coplexity of the normalization procedure? I have heard a claim that for a closed term calculating the value of the function requires transfinte induction up to $\epsilon\_0$. Is this true and where can I find a proof of this? For example in (Schwichtenberg & Wainer 2012) there is a lemma which says that a primitive recursive function is computable in $F\_{\alpha}$-bounded time, for some $\alpha<\omega$, where the set of all $F\_{\alpha}$ for $\alpha<\epsilon\_0$ is the Fast Growing Hierarchy. Is the measure of transfinite induction related to this way of bounding the complexity?
2012/05/25
[ "https://mathoverflow.net/questions/97927", "https://mathoverflow.net", "https://mathoverflow.net/users/23947/" ]
I find some aspects of this question difficult to understand. For example, the part about "calculating the value of the function requires transfinite induction up to $\varepsilon\_0$" seems to conflate methods of proof (like transfinite induction) with methods of computation. Also, much (if not all) of the question appears to be about primitive recursive functionals of higher type (as in Gödel's Dialectica interpretation) rather than mere primitive recursive functions. So, the following may not be what the OP was looking for, but here goes anyway: Not much can be said about the time complexity of computing primitive recursive functions (from natural numbers to natural numbers) except that it's primitive recursive and thus bounded by a finite level $F\_n$ of the Grzegorczyk hierarchy (essentially equivalent to the fast-growing hierarchy, I believe). On the other hand, for primitive recursive functionals of finite type, you can consider the problem of evaluating terms of type 0 (i.e., terms that denote natural numbers). Here, the only bound I can see for the time-complexity is level $\varepsilon\_0$ of the Grzegorczyk hierarchy. For any fixed primitive recursive functional, evaluation of its numerical values would take time bounded by $F\_\alpha$ for some $\alpha<\varepsilon\_0$, but different functionals would need different $\alpha$'s, with no uniform bound below $\varepsilon\_0$. The relevance of the proof principle of transfinite induction up to $\varepsilon\_0$ (for open formulas) is that this is what is needed, on top of primitive recursive arithmetic, to prove that every closed term of type 0, built from primitive recursive functionals of higher type, can be reduced to a numerical value.
Dear Andreas, yes indeed. We have the follwing (not too difficult) fact: Let S^m(0) be the numeral for $m$. For any PRA term $t(x\_1,\ldots,x\_n)$ The derivation length of $t(S^{m\_1}(0),\ldots,S^{m\_n}(0))$ will be bounded by a primitive recursive function (depending on $t$) with arguments $m\_1,\ldots,m\_n$. (Here I assume standard rewrite systems for modelling primitive recursion.) For terms from Gödel's T the derivation lengths become more complex depending on the typelevel of the terms in question. My general conjecture is that for typical (not too small) subrecursive classes C the derivation lengths functions for terms in C will not leave C. The result for primitive recursion is not difficult whereas the result for Gödel's T is somewhat involved. For PRA there is also a tradeoff in terms of termination orderings. Termination for rewrite systems for prim rec functions can be shown by the multiset path ordering. And termation proofs for the multiset path ordering lead to prim rec derivation lengths (result by Dieter Hofbauer). The corresponding result for multiple recursion is one of my earliest results in term rewriting theory. Wilfried Buchholz gave a nice prooftheoretic proof for these results in APAL. There is also some nice application of term rewriting to more involved schemes of primitive recursive functions. For example it can be used to show that prim rec functions are closed under parameter recursion, or simple nested recursion, or even unnested multiple recursion. Best, Andreas
97,927
If we have a rewrite system for primitive recursive functions, which simplifies each term according to how the function was defined, then what is the computational complexity of this calculation? That is, what is the coplexity of the normalization procedure? I have heard a claim that for a closed term calculating the value of the function requires transfinte induction up to $\epsilon\_0$. Is this true and where can I find a proof of this? For example in (Schwichtenberg & Wainer 2012) there is a lemma which says that a primitive recursive function is computable in $F\_{\alpha}$-bounded time, for some $\alpha<\omega$, where the set of all $F\_{\alpha}$ for $\alpha<\epsilon\_0$ is the Fast Growing Hierarchy. Is the measure of transfinite induction related to this way of bounding the complexity?
2012/05/25
[ "https://mathoverflow.net/questions/97927", "https://mathoverflow.net", "https://mathoverflow.net/users/23947/" ]
Actually there is no need for any transfinite induction. A monotone interpretation yields that the derivation lengths for any fixed term will be primitive recursive in the values of the numerals plugged in. I have a paper in APAL with Cichon on the topic and, in addition, a paper in JSL regarding Goedel's T showing that for T one needs epsilon\_0 recursion for proving strong normalization by a monotone interpretation. Best, Andreas
Dear Andreas, yes indeed. We have the follwing (not too difficult) fact: Let S^m(0) be the numeral for $m$. For any PRA term $t(x\_1,\ldots,x\_n)$ The derivation length of $t(S^{m\_1}(0),\ldots,S^{m\_n}(0))$ will be bounded by a primitive recursive function (depending on $t$) with arguments $m\_1,\ldots,m\_n$. (Here I assume standard rewrite systems for modelling primitive recursion.) For terms from Gödel's T the derivation lengths become more complex depending on the typelevel of the terms in question. My general conjecture is that for typical (not too small) subrecursive classes C the derivation lengths functions for terms in C will not leave C. The result for primitive recursion is not difficult whereas the result for Gödel's T is somewhat involved. For PRA there is also a tradeoff in terms of termination orderings. Termination for rewrite systems for prim rec functions can be shown by the multiset path ordering. And termation proofs for the multiset path ordering lead to prim rec derivation lengths (result by Dieter Hofbauer). The corresponding result for multiple recursion is one of my earliest results in term rewriting theory. Wilfried Buchholz gave a nice prooftheoretic proof for these results in APAL. There is also some nice application of term rewriting to more involved schemes of primitive recursive functions. For example it can be used to show that prim rec functions are closed under parameter recursion, or simple nested recursion, or even unnested multiple recursion. Best, Andreas
17,223,945
I am using a WAMP server, and I want to upload images in the database using CI.The image variable in database is of blob datatype. My question's as follows: 1) How to store the image instead of the file name and what datatypes should I use? 2) How to retrieve images from the DB? My controller's code: ``` <?php class Image_control extends CI_Controller{ function index() { //$this->load->view('image_view'); //$this->Image_model->do_upload(); $data['images']=$this->Image_model->get_images(); $this->load->view('image_view',$data); } function do_upload() { $config = array( 'allowed_types' => 'jpg|png|bmp', 'upload_path'=>'./images1/', 'max_size'=>2000 ); $this->load->library('upload',$config); if (!$this->upload->do_upload()) { $errors[]=array('error'=>$this->upload->display_errors()); $this->load->view('image_view',$errors); } $image_path=$this->upload->data(); $file_name=$image_path['file_name']; $config = array( 'a_name' => $this->input->post('a_name'), 'a_details'=>$this->input->post('a_info'), 'a_photo'=>$file_name ); $insert=$this->db->insert('animalstore',$config); return $insert; } } ?> ``` My model's code: ``` <?php class Image_model extends CI_Model { function get_images() { $query = $this->db->get('animalstore'); if($query->num_rows > 0 ) { foreach($query->result() as $rows) { $data[] = $rows; } return $data; } } } ?> ``` And finally here's the code for my view: ``` <?php echo form_open_multipart('image_control/do_upload'); echo form_input('a_name','Animal Name'); echo form_input('a_info','Animal Information'); echo form_upload('userfile'); echo form_submit('upload','Upload'); echo form_close(); ?> <?php foreach ($images as $image):?> <h1><?php echo $image->a_name;?></h1> <h1><?php echo $image->a_details;?></h1> <img src = "/<?php// echo ltrim($image->a_photo, '/'); ?>" > <img src="http://localhost/ci_test/images1/<?php echo $image->a_photo;?>"/> <img src="<?php //echo sprintf("images/%s", $image['screenshot']);?>" /> <h1><?php// echo $image->a_photo;?></h1> <?php endforeach; ?> ``` I tried solving it in different ways and searched for my problem but I didn't find any appropriate answer.
2013/06/20
[ "https://Stackoverflow.com/questions/17223945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506856/" ]
DO NOT STORE FILES INSIDE THE DATABASE!!! This is always a bad design idea. Store the files in the file system and simply store the file names and point to the file, it will save you a lot of headaches in the future.
try this code models code ``` function do_upload() { $config = array( 'allowed_types' => 'jpg|png|bmp', 'upload_path'=>'./images1/', //make sure you have this folder 'max_size'=>2000 ); $this->load->library('upload',$config); if ($this->upload->do_upload()) { echo "Upload success!"; } else { echo "Upload failed!"; } $image_data = $this->upload->data(); } function get_images() { $query = $this->db->get('animalstore'); return $query; } function Save_gallery($in) { $save=$this->db->insert('animalstore',$in); return $save; } ``` controller code ``` function index() { $this->load->model('Image_control'); //call a models if ($this->input->post('upload')) { $in=array(); $in['a_name'] = $this->input->post('a_name'), $in['a_details'] = $this->input->post('a_info'), $in['a_photo']=$_FILES['userfile']['name']; if($this->Image_model->do_upload()) { echo $this->upload->display_errors(); }else { $this->Image_model->Save_gallery($in); header('location:index'); } $data['images']=$this->Image_model->get_images(); $this->load->view('image_view',$data); } ``` view ``` <?php echo form_open_multipart('image_control/index'); echo form_input('a_name','Animal Name'); echo form_input('a_info','Animal Information'); echo form_upload('userfile'); echo form_submit('upload','Upload'); echo form_close(); ?> <?php foreach ($images as $image):?> <h1><?php echo $image['a_name'];?></h1> <h1><?php echo $image['a_details'];?></h1> <?php echo '<img src ="'. base_url().'images1/'.$image['a_photo'].'" >"; endforeach; ?> ```
17,223,945
I am using a WAMP server, and I want to upload images in the database using CI.The image variable in database is of blob datatype. My question's as follows: 1) How to store the image instead of the file name and what datatypes should I use? 2) How to retrieve images from the DB? My controller's code: ``` <?php class Image_control extends CI_Controller{ function index() { //$this->load->view('image_view'); //$this->Image_model->do_upload(); $data['images']=$this->Image_model->get_images(); $this->load->view('image_view',$data); } function do_upload() { $config = array( 'allowed_types' => 'jpg|png|bmp', 'upload_path'=>'./images1/', 'max_size'=>2000 ); $this->load->library('upload',$config); if (!$this->upload->do_upload()) { $errors[]=array('error'=>$this->upload->display_errors()); $this->load->view('image_view',$errors); } $image_path=$this->upload->data(); $file_name=$image_path['file_name']; $config = array( 'a_name' => $this->input->post('a_name'), 'a_details'=>$this->input->post('a_info'), 'a_photo'=>$file_name ); $insert=$this->db->insert('animalstore',$config); return $insert; } } ?> ``` My model's code: ``` <?php class Image_model extends CI_Model { function get_images() { $query = $this->db->get('animalstore'); if($query->num_rows > 0 ) { foreach($query->result() as $rows) { $data[] = $rows; } return $data; } } } ?> ``` And finally here's the code for my view: ``` <?php echo form_open_multipart('image_control/do_upload'); echo form_input('a_name','Animal Name'); echo form_input('a_info','Animal Information'); echo form_upload('userfile'); echo form_submit('upload','Upload'); echo form_close(); ?> <?php foreach ($images as $image):?> <h1><?php echo $image->a_name;?></h1> <h1><?php echo $image->a_details;?></h1> <img src = "/<?php// echo ltrim($image->a_photo, '/'); ?>" > <img src="http://localhost/ci_test/images1/<?php echo $image->a_photo;?>"/> <img src="<?php //echo sprintf("images/%s", $image['screenshot']);?>" /> <h1><?php// echo $image->a_photo;?></h1> <?php endforeach; ?> ``` I tried solving it in different ways and searched for my problem but I didn't find any appropriate answer.
2013/06/20
[ "https://Stackoverflow.com/questions/17223945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506856/" ]
DO NOT STORE FILES INSIDE THE DATABASE!!! This is always a bad design idea. Store the files in the file system and simply store the file names and point to the file, it will save you a lot of headaches in the future.
Here's a quick something I use for small PNG thumbnails. These are stored in a table called "coreg" in a field named "IMAGE". The field-type is LONGBLOB. Every upload overwrites the previous image. In the actual app the view-file is displayed as an iframe: VIEW FILE FOR UPLOADING (better to use the CI specific form tags of course, but you get the idea) add\_image.php: ``` Current image: <img src='/media/png/coreg/<?=$coregID?>' /> <? if(isset($error)){ echo $error; }?> <form method='post' enctype="multipart/form-data" action='add_image/<?=$coregID?>'> <input name="userfile" type="file" class='vLink' /> <input name="submitbtn" type="submit" value=" upload &amp; overwrite " class='eLink' /> </form> ``` CONTROLLER TO SHOW THE IMAGE More elegant would be to use a view instead of the echo and to move the DB logic into the model, but this shows the functionality better IMHO: media.php ``` require_once dirname(__FILE__) . "/base.php"; class Media extends BaseController { function __construct() { parent::__construct(); } function png($table,$id) { $this->db->where('ID',$id); $r = $this->db->get($table); if($r->num_rows){ $r = $r->result_array(); header("Content-Type: image/png"); echo $r[0]['IMAGE']; } } } ``` CONTROLLER TO UPLOAD THE IMAGE: ``` function add_image($coregID){ $data['coregID'] = $coregID; $data['error'] = ''; if(isset($_POST['submitbtn'])){ $config['upload_path'] = './assets/img/coreg/'; $config['allowed_types'] = 'png'; $config['max_size'] = '100'; $config['max_width'] = '350'; $config['max_height'] = '350'; $config['file_name'] = $coregID.".png"; if(file_exists($config['upload_path'].$config['file_name'])){ unlink($config['upload_path'].$config['file_name']); } $this->load->library('upload', $config); if ( ! $this->upload->do_upload()){ $data['error'] = $this->upload->display_errors(); } else { $this->upload->data(); // now move the image into the DB $fp = fopen($config['upload_path'].$config['file_name'], 'r'); $data = fread($fp, filesize($config['upload_path'].$config['file_name'])); $this->db->where('ID',$coregID); $this->db->update('COREG',array('IMAGE' =>$data)); fclose($fp); // optionally delete the file from the HD after this step //unlink($config['upload_path'].$config['file_name']); } } $this->load->view("add_image", $data); } ```
17,223,945
I am using a WAMP server, and I want to upload images in the database using CI.The image variable in database is of blob datatype. My question's as follows: 1) How to store the image instead of the file name and what datatypes should I use? 2) How to retrieve images from the DB? My controller's code: ``` <?php class Image_control extends CI_Controller{ function index() { //$this->load->view('image_view'); //$this->Image_model->do_upload(); $data['images']=$this->Image_model->get_images(); $this->load->view('image_view',$data); } function do_upload() { $config = array( 'allowed_types' => 'jpg|png|bmp', 'upload_path'=>'./images1/', 'max_size'=>2000 ); $this->load->library('upload',$config); if (!$this->upload->do_upload()) { $errors[]=array('error'=>$this->upload->display_errors()); $this->load->view('image_view',$errors); } $image_path=$this->upload->data(); $file_name=$image_path['file_name']; $config = array( 'a_name' => $this->input->post('a_name'), 'a_details'=>$this->input->post('a_info'), 'a_photo'=>$file_name ); $insert=$this->db->insert('animalstore',$config); return $insert; } } ?> ``` My model's code: ``` <?php class Image_model extends CI_Model { function get_images() { $query = $this->db->get('animalstore'); if($query->num_rows > 0 ) { foreach($query->result() as $rows) { $data[] = $rows; } return $data; } } } ?> ``` And finally here's the code for my view: ``` <?php echo form_open_multipart('image_control/do_upload'); echo form_input('a_name','Animal Name'); echo form_input('a_info','Animal Information'); echo form_upload('userfile'); echo form_submit('upload','Upload'); echo form_close(); ?> <?php foreach ($images as $image):?> <h1><?php echo $image->a_name;?></h1> <h1><?php echo $image->a_details;?></h1> <img src = "/<?php// echo ltrim($image->a_photo, '/'); ?>" > <img src="http://localhost/ci_test/images1/<?php echo $image->a_photo;?>"/> <img src="<?php //echo sprintf("images/%s", $image['screenshot']);?>" /> <h1><?php// echo $image->a_photo;?></h1> <?php endforeach; ?> ``` I tried solving it in different ways and searched for my problem but I didn't find any appropriate answer.
2013/06/20
[ "https://Stackoverflow.com/questions/17223945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506856/" ]
DO NOT STORE FILES INSIDE THE DATABASE!!! This is always a bad design idea. Store the files in the file system and simply store the file names and point to the file, it will save you a lot of headaches in the future.
try this code controller:- ``` <?php class Profile extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper(array('form', 'url')); } public function index() { $this->load->view('profile', array('error' => ' ' )); } function do_upload(){ $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $this->load->library('upload', $config); if ( ! $this->upload->do_upload()) { $error = array('error' => $this->upload->display_errors()); $this->load->view('profile', $error); } else { $data = $this->upload->data(); $data['img']=base_url().'./uploads/'.$data['file_name']; $image['profile_pic'] = $data['file_name']; $this->db->insert('user_profile_pic', $image); $this->load->view('profile', $data); } } } ```
17,223,945
I am using a WAMP server, and I want to upload images in the database using CI.The image variable in database is of blob datatype. My question's as follows: 1) How to store the image instead of the file name and what datatypes should I use? 2) How to retrieve images from the DB? My controller's code: ``` <?php class Image_control extends CI_Controller{ function index() { //$this->load->view('image_view'); //$this->Image_model->do_upload(); $data['images']=$this->Image_model->get_images(); $this->load->view('image_view',$data); } function do_upload() { $config = array( 'allowed_types' => 'jpg|png|bmp', 'upload_path'=>'./images1/', 'max_size'=>2000 ); $this->load->library('upload',$config); if (!$this->upload->do_upload()) { $errors[]=array('error'=>$this->upload->display_errors()); $this->load->view('image_view',$errors); } $image_path=$this->upload->data(); $file_name=$image_path['file_name']; $config = array( 'a_name' => $this->input->post('a_name'), 'a_details'=>$this->input->post('a_info'), 'a_photo'=>$file_name ); $insert=$this->db->insert('animalstore',$config); return $insert; } } ?> ``` My model's code: ``` <?php class Image_model extends CI_Model { function get_images() { $query = $this->db->get('animalstore'); if($query->num_rows > 0 ) { foreach($query->result() as $rows) { $data[] = $rows; } return $data; } } } ?> ``` And finally here's the code for my view: ``` <?php echo form_open_multipart('image_control/do_upload'); echo form_input('a_name','Animal Name'); echo form_input('a_info','Animal Information'); echo form_upload('userfile'); echo form_submit('upload','Upload'); echo form_close(); ?> <?php foreach ($images as $image):?> <h1><?php echo $image->a_name;?></h1> <h1><?php echo $image->a_details;?></h1> <img src = "/<?php// echo ltrim($image->a_photo, '/'); ?>" > <img src="http://localhost/ci_test/images1/<?php echo $image->a_photo;?>"/> <img src="<?php //echo sprintf("images/%s", $image['screenshot']);?>" /> <h1><?php// echo $image->a_photo;?></h1> <?php endforeach; ?> ``` I tried solving it in different ways and searched for my problem but I didn't find any appropriate answer.
2013/06/20
[ "https://Stackoverflow.com/questions/17223945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506856/" ]
DO NOT STORE FILES INSIDE THE DATABASE!!! This is always a bad design idea. Store the files in the file system and simply store the file names and point to the file, it will save you a lot of headaches in the future.
view: ``` <?php echo form_open_multipart('profile/do_upload');?> <input type="file" name="userfile" size="20" /> <br /><br /> <input type="submit" value="upload" /> <img src="<?php echo $img ?>" width="300px" height="300px"> </form> ?> ```
17,223,945
I am using a WAMP server, and I want to upload images in the database using CI.The image variable in database is of blob datatype. My question's as follows: 1) How to store the image instead of the file name and what datatypes should I use? 2) How to retrieve images from the DB? My controller's code: ``` <?php class Image_control extends CI_Controller{ function index() { //$this->load->view('image_view'); //$this->Image_model->do_upload(); $data['images']=$this->Image_model->get_images(); $this->load->view('image_view',$data); } function do_upload() { $config = array( 'allowed_types' => 'jpg|png|bmp', 'upload_path'=>'./images1/', 'max_size'=>2000 ); $this->load->library('upload',$config); if (!$this->upload->do_upload()) { $errors[]=array('error'=>$this->upload->display_errors()); $this->load->view('image_view',$errors); } $image_path=$this->upload->data(); $file_name=$image_path['file_name']; $config = array( 'a_name' => $this->input->post('a_name'), 'a_details'=>$this->input->post('a_info'), 'a_photo'=>$file_name ); $insert=$this->db->insert('animalstore',$config); return $insert; } } ?> ``` My model's code: ``` <?php class Image_model extends CI_Model { function get_images() { $query = $this->db->get('animalstore'); if($query->num_rows > 0 ) { foreach($query->result() as $rows) { $data[] = $rows; } return $data; } } } ?> ``` And finally here's the code for my view: ``` <?php echo form_open_multipart('image_control/do_upload'); echo form_input('a_name','Animal Name'); echo form_input('a_info','Animal Information'); echo form_upload('userfile'); echo form_submit('upload','Upload'); echo form_close(); ?> <?php foreach ($images as $image):?> <h1><?php echo $image->a_name;?></h1> <h1><?php echo $image->a_details;?></h1> <img src = "/<?php// echo ltrim($image->a_photo, '/'); ?>" > <img src="http://localhost/ci_test/images1/<?php echo $image->a_photo;?>"/> <img src="<?php //echo sprintf("images/%s", $image['screenshot']);?>" /> <h1><?php// echo $image->a_photo;?></h1> <?php endforeach; ?> ``` I tried solving it in different ways and searched for my problem but I didn't find any appropriate answer.
2013/06/20
[ "https://Stackoverflow.com/questions/17223945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506856/" ]
``` // uploading public function do_upload(){ ... $image_path=$this->upload->data(); $uploaded_image = $image_path['full_path']; // Read the file $fp = fopen($uploaded_image, 'r'); $data = fread($fp, filesize($uploaded_image)); $data = addslashes($data); fclose($fp); // here you can easy insert $data to 'a_photo' column. } // Viewing, $image_id is row id public function getImage($image_id){ // select $row from database as usual and then $content = $row['a_photo']; echo '<img src="data:image/jpeg;base64,'.base64_encode($content).'">'; } ``` In your template: ``` <?php getImage(12); ?> ``` where 12 is row id.
try this code models code ``` function do_upload() { $config = array( 'allowed_types' => 'jpg|png|bmp', 'upload_path'=>'./images1/', //make sure you have this folder 'max_size'=>2000 ); $this->load->library('upload',$config); if ($this->upload->do_upload()) { echo "Upload success!"; } else { echo "Upload failed!"; } $image_data = $this->upload->data(); } function get_images() { $query = $this->db->get('animalstore'); return $query; } function Save_gallery($in) { $save=$this->db->insert('animalstore',$in); return $save; } ``` controller code ``` function index() { $this->load->model('Image_control'); //call a models if ($this->input->post('upload')) { $in=array(); $in['a_name'] = $this->input->post('a_name'), $in['a_details'] = $this->input->post('a_info'), $in['a_photo']=$_FILES['userfile']['name']; if($this->Image_model->do_upload()) { echo $this->upload->display_errors(); }else { $this->Image_model->Save_gallery($in); header('location:index'); } $data['images']=$this->Image_model->get_images(); $this->load->view('image_view',$data); } ``` view ``` <?php echo form_open_multipart('image_control/index'); echo form_input('a_name','Animal Name'); echo form_input('a_info','Animal Information'); echo form_upload('userfile'); echo form_submit('upload','Upload'); echo form_close(); ?> <?php foreach ($images as $image):?> <h1><?php echo $image['a_name'];?></h1> <h1><?php echo $image['a_details'];?></h1> <?php echo '<img src ="'. base_url().'images1/'.$image['a_photo'].'" >"; endforeach; ?> ```
17,223,945
I am using a WAMP server, and I want to upload images in the database using CI.The image variable in database is of blob datatype. My question's as follows: 1) How to store the image instead of the file name and what datatypes should I use? 2) How to retrieve images from the DB? My controller's code: ``` <?php class Image_control extends CI_Controller{ function index() { //$this->load->view('image_view'); //$this->Image_model->do_upload(); $data['images']=$this->Image_model->get_images(); $this->load->view('image_view',$data); } function do_upload() { $config = array( 'allowed_types' => 'jpg|png|bmp', 'upload_path'=>'./images1/', 'max_size'=>2000 ); $this->load->library('upload',$config); if (!$this->upload->do_upload()) { $errors[]=array('error'=>$this->upload->display_errors()); $this->load->view('image_view',$errors); } $image_path=$this->upload->data(); $file_name=$image_path['file_name']; $config = array( 'a_name' => $this->input->post('a_name'), 'a_details'=>$this->input->post('a_info'), 'a_photo'=>$file_name ); $insert=$this->db->insert('animalstore',$config); return $insert; } } ?> ``` My model's code: ``` <?php class Image_model extends CI_Model { function get_images() { $query = $this->db->get('animalstore'); if($query->num_rows > 0 ) { foreach($query->result() as $rows) { $data[] = $rows; } return $data; } } } ?> ``` And finally here's the code for my view: ``` <?php echo form_open_multipart('image_control/do_upload'); echo form_input('a_name','Animal Name'); echo form_input('a_info','Animal Information'); echo form_upload('userfile'); echo form_submit('upload','Upload'); echo form_close(); ?> <?php foreach ($images as $image):?> <h1><?php echo $image->a_name;?></h1> <h1><?php echo $image->a_details;?></h1> <img src = "/<?php// echo ltrim($image->a_photo, '/'); ?>" > <img src="http://localhost/ci_test/images1/<?php echo $image->a_photo;?>"/> <img src="<?php //echo sprintf("images/%s", $image['screenshot']);?>" /> <h1><?php// echo $image->a_photo;?></h1> <?php endforeach; ?> ``` I tried solving it in different ways and searched for my problem but I didn't find any appropriate answer.
2013/06/20
[ "https://Stackoverflow.com/questions/17223945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506856/" ]
``` // uploading public function do_upload(){ ... $image_path=$this->upload->data(); $uploaded_image = $image_path['full_path']; // Read the file $fp = fopen($uploaded_image, 'r'); $data = fread($fp, filesize($uploaded_image)); $data = addslashes($data); fclose($fp); // here you can easy insert $data to 'a_photo' column. } // Viewing, $image_id is row id public function getImage($image_id){ // select $row from database as usual and then $content = $row['a_photo']; echo '<img src="data:image/jpeg;base64,'.base64_encode($content).'">'; } ``` In your template: ``` <?php getImage(12); ?> ``` where 12 is row id.
Here's a quick something I use for small PNG thumbnails. These are stored in a table called "coreg" in a field named "IMAGE". The field-type is LONGBLOB. Every upload overwrites the previous image. In the actual app the view-file is displayed as an iframe: VIEW FILE FOR UPLOADING (better to use the CI specific form tags of course, but you get the idea) add\_image.php: ``` Current image: <img src='/media/png/coreg/<?=$coregID?>' /> <? if(isset($error)){ echo $error; }?> <form method='post' enctype="multipart/form-data" action='add_image/<?=$coregID?>'> <input name="userfile" type="file" class='vLink' /> <input name="submitbtn" type="submit" value=" upload &amp; overwrite " class='eLink' /> </form> ``` CONTROLLER TO SHOW THE IMAGE More elegant would be to use a view instead of the echo and to move the DB logic into the model, but this shows the functionality better IMHO: media.php ``` require_once dirname(__FILE__) . "/base.php"; class Media extends BaseController { function __construct() { parent::__construct(); } function png($table,$id) { $this->db->where('ID',$id); $r = $this->db->get($table); if($r->num_rows){ $r = $r->result_array(); header("Content-Type: image/png"); echo $r[0]['IMAGE']; } } } ``` CONTROLLER TO UPLOAD THE IMAGE: ``` function add_image($coregID){ $data['coregID'] = $coregID; $data['error'] = ''; if(isset($_POST['submitbtn'])){ $config['upload_path'] = './assets/img/coreg/'; $config['allowed_types'] = 'png'; $config['max_size'] = '100'; $config['max_width'] = '350'; $config['max_height'] = '350'; $config['file_name'] = $coregID.".png"; if(file_exists($config['upload_path'].$config['file_name'])){ unlink($config['upload_path'].$config['file_name']); } $this->load->library('upload', $config); if ( ! $this->upload->do_upload()){ $data['error'] = $this->upload->display_errors(); } else { $this->upload->data(); // now move the image into the DB $fp = fopen($config['upload_path'].$config['file_name'], 'r'); $data = fread($fp, filesize($config['upload_path'].$config['file_name'])); $this->db->where('ID',$coregID); $this->db->update('COREG',array('IMAGE' =>$data)); fclose($fp); // optionally delete the file from the HD after this step //unlink($config['upload_path'].$config['file_name']); } } $this->load->view("add_image", $data); } ```
17,223,945
I am using a WAMP server, and I want to upload images in the database using CI.The image variable in database is of blob datatype. My question's as follows: 1) How to store the image instead of the file name and what datatypes should I use? 2) How to retrieve images from the DB? My controller's code: ``` <?php class Image_control extends CI_Controller{ function index() { //$this->load->view('image_view'); //$this->Image_model->do_upload(); $data['images']=$this->Image_model->get_images(); $this->load->view('image_view',$data); } function do_upload() { $config = array( 'allowed_types' => 'jpg|png|bmp', 'upload_path'=>'./images1/', 'max_size'=>2000 ); $this->load->library('upload',$config); if (!$this->upload->do_upload()) { $errors[]=array('error'=>$this->upload->display_errors()); $this->load->view('image_view',$errors); } $image_path=$this->upload->data(); $file_name=$image_path['file_name']; $config = array( 'a_name' => $this->input->post('a_name'), 'a_details'=>$this->input->post('a_info'), 'a_photo'=>$file_name ); $insert=$this->db->insert('animalstore',$config); return $insert; } } ?> ``` My model's code: ``` <?php class Image_model extends CI_Model { function get_images() { $query = $this->db->get('animalstore'); if($query->num_rows > 0 ) { foreach($query->result() as $rows) { $data[] = $rows; } return $data; } } } ?> ``` And finally here's the code for my view: ``` <?php echo form_open_multipart('image_control/do_upload'); echo form_input('a_name','Animal Name'); echo form_input('a_info','Animal Information'); echo form_upload('userfile'); echo form_submit('upload','Upload'); echo form_close(); ?> <?php foreach ($images as $image):?> <h1><?php echo $image->a_name;?></h1> <h1><?php echo $image->a_details;?></h1> <img src = "/<?php// echo ltrim($image->a_photo, '/'); ?>" > <img src="http://localhost/ci_test/images1/<?php echo $image->a_photo;?>"/> <img src="<?php //echo sprintf("images/%s", $image['screenshot']);?>" /> <h1><?php// echo $image->a_photo;?></h1> <?php endforeach; ?> ``` I tried solving it in different ways and searched for my problem but I didn't find any appropriate answer.
2013/06/20
[ "https://Stackoverflow.com/questions/17223945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506856/" ]
``` // uploading public function do_upload(){ ... $image_path=$this->upload->data(); $uploaded_image = $image_path['full_path']; // Read the file $fp = fopen($uploaded_image, 'r'); $data = fread($fp, filesize($uploaded_image)); $data = addslashes($data); fclose($fp); // here you can easy insert $data to 'a_photo' column. } // Viewing, $image_id is row id public function getImage($image_id){ // select $row from database as usual and then $content = $row['a_photo']; echo '<img src="data:image/jpeg;base64,'.base64_encode($content).'">'; } ``` In your template: ``` <?php getImage(12); ?> ``` where 12 is row id.
try this code controller:- ``` <?php class Profile extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper(array('form', 'url')); } public function index() { $this->load->view('profile', array('error' => ' ' )); } function do_upload(){ $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $this->load->library('upload', $config); if ( ! $this->upload->do_upload()) { $error = array('error' => $this->upload->display_errors()); $this->load->view('profile', $error); } else { $data = $this->upload->data(); $data['img']=base_url().'./uploads/'.$data['file_name']; $image['profile_pic'] = $data['file_name']; $this->db->insert('user_profile_pic', $image); $this->load->view('profile', $data); } } } ```
17,223,945
I am using a WAMP server, and I want to upload images in the database using CI.The image variable in database is of blob datatype. My question's as follows: 1) How to store the image instead of the file name and what datatypes should I use? 2) How to retrieve images from the DB? My controller's code: ``` <?php class Image_control extends CI_Controller{ function index() { //$this->load->view('image_view'); //$this->Image_model->do_upload(); $data['images']=$this->Image_model->get_images(); $this->load->view('image_view',$data); } function do_upload() { $config = array( 'allowed_types' => 'jpg|png|bmp', 'upload_path'=>'./images1/', 'max_size'=>2000 ); $this->load->library('upload',$config); if (!$this->upload->do_upload()) { $errors[]=array('error'=>$this->upload->display_errors()); $this->load->view('image_view',$errors); } $image_path=$this->upload->data(); $file_name=$image_path['file_name']; $config = array( 'a_name' => $this->input->post('a_name'), 'a_details'=>$this->input->post('a_info'), 'a_photo'=>$file_name ); $insert=$this->db->insert('animalstore',$config); return $insert; } } ?> ``` My model's code: ``` <?php class Image_model extends CI_Model { function get_images() { $query = $this->db->get('animalstore'); if($query->num_rows > 0 ) { foreach($query->result() as $rows) { $data[] = $rows; } return $data; } } } ?> ``` And finally here's the code for my view: ``` <?php echo form_open_multipart('image_control/do_upload'); echo form_input('a_name','Animal Name'); echo form_input('a_info','Animal Information'); echo form_upload('userfile'); echo form_submit('upload','Upload'); echo form_close(); ?> <?php foreach ($images as $image):?> <h1><?php echo $image->a_name;?></h1> <h1><?php echo $image->a_details;?></h1> <img src = "/<?php// echo ltrim($image->a_photo, '/'); ?>" > <img src="http://localhost/ci_test/images1/<?php echo $image->a_photo;?>"/> <img src="<?php //echo sprintf("images/%s", $image['screenshot']);?>" /> <h1><?php// echo $image->a_photo;?></h1> <?php endforeach; ?> ``` I tried solving it in different ways and searched for my problem but I didn't find any appropriate answer.
2013/06/20
[ "https://Stackoverflow.com/questions/17223945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506856/" ]
``` // uploading public function do_upload(){ ... $image_path=$this->upload->data(); $uploaded_image = $image_path['full_path']; // Read the file $fp = fopen($uploaded_image, 'r'); $data = fread($fp, filesize($uploaded_image)); $data = addslashes($data); fclose($fp); // here you can easy insert $data to 'a_photo' column. } // Viewing, $image_id is row id public function getImage($image_id){ // select $row from database as usual and then $content = $row['a_photo']; echo '<img src="data:image/jpeg;base64,'.base64_encode($content).'">'; } ``` In your template: ``` <?php getImage(12); ?> ``` where 12 is row id.
view: ``` <?php echo form_open_multipart('profile/do_upload');?> <input type="file" name="userfile" size="20" /> <br /><br /> <input type="submit" value="upload" /> <img src="<?php echo $img ?>" width="300px" height="300px"> </form> ?> ```
281,433
``` selection= until [ "$selection" = "0" ]; do echo "" echo "PROGRAM MENU" echo "1 - display free disk space" echo "2 - display free memory" echo "" echo "0 - exit program" echo "" echo -n "Enter selection: " read selection echo "" case $selection in 1 ) df ;; 2 ) free ;; 0 ) exit ;; * ) echo "Please enter 1, 2, or 0" esac echo $selection done ``` If I press 2 it's showing free space and echo is showing 2, but I need echo is "free".
2016/05/06
[ "https://unix.stackexchange.com/questions/281433", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/169164/" ]
You can't. The selection is used by the case statement to decide what to do. It is not set by the case statement. You might want to try something like this instead: ``` selection= until [ "$selection" = "0" ]; do cmd='' echo "" echo "PROGRAM MENU" echo "1 - display free disk space" echo "2 - display free memory" echo "" echo "0 - exit program" echo "" echo -n "Enter selection: " read selection echo "" case "$selection" in 1) cmd='df' ;; 2) cmd='free' ;; 0) cmd='exit' ;; *) echo "Please enter 1, 2, or 0" esac if [ -n "$cmd" ] ; then echo "selection $selection is '$cmd'" $cmd fi done ``` Note that it runs the `echo "selection $selection is '$cmd'` before executing `$cmd`, otherwise it will exit before the `echo` when `$selection` is 0.
> > if i press 2 its showing free space and echo is showing 2 > but i need echo is "free" > > > So, currently `echo $selection` prints `2` for free and you want it to print `free`. In that case, replace: ``` 2 ) free ;; ``` With: ``` 2 ) free; selection=free ;; ``` With the variable `selection` set to the string `free`, this cause the `echo` command to print what you want. ### Alternative As another option, but *not* an exact replacement, the bash command `select` can be used to accomplish something similar with a much shorter code: ``` PS3="Please enter 1, 2, or 3: " select selection in "display free disk space" "display free memory" "exit program" do case "$selection" in "display free disk space") df ;; "display free memory") free; selection=free ;; "exit program") exit ;; esac echo $selection done ```
281,433
``` selection= until [ "$selection" = "0" ]; do echo "" echo "PROGRAM MENU" echo "1 - display free disk space" echo "2 - display free memory" echo "" echo "0 - exit program" echo "" echo -n "Enter selection: " read selection echo "" case $selection in 1 ) df ;; 2 ) free ;; 0 ) exit ;; * ) echo "Please enter 1, 2, or 0" esac echo $selection done ``` If I press 2 it's showing free space and echo is showing 2, but I need echo is "free".
2016/05/06
[ "https://unix.stackexchange.com/questions/281433", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/169164/" ]
You can't. The selection is used by the case statement to decide what to do. It is not set by the case statement. You might want to try something like this instead: ``` selection= until [ "$selection" = "0" ]; do cmd='' echo "" echo "PROGRAM MENU" echo "1 - display free disk space" echo "2 - display free memory" echo "" echo "0 - exit program" echo "" echo -n "Enter selection: " read selection echo "" case "$selection" in 1) cmd='df' ;; 2) cmd='free' ;; 0) cmd='exit' ;; *) echo "Please enter 1, 2, or 0" esac if [ -n "$cmd" ] ; then echo "selection $selection is '$cmd'" $cmd fi done ``` Note that it runs the `echo "selection $selection is '$cmd'` before executing `$cmd`, otherwise it will exit before the `echo` when `$selection` is 0.
Here is how I would do this. Might be helpful/instructive. ``` #!/bin/bash menu() { cat >&2 <<EOF PROGRAM MENU 1 - display free disk space 2 - display free memory 0 - exit program EOF } while true; do menu read -p "Enter selection: " selection case "$selection" in 1) echo df df ;; 2) echo free free ;; 0) echo exit exit ;; *) echo "Please enter 1, 2 or 0" >&2 ;; esac done ```
1,057,853
After some automatic updates (or being hacked?) I have many things broken and a huge problem to resolve them since **I can't login as root anymore**. * ssh admin: login success * su root: permission denied (probably not the same password) What I have tried: * read log: but permission denied * use 'synopass' and empty password: failed * use synouser: permission denied * change password of admin hoping it will update the root password: failed. * check the root user in /etc/passwd: he is ok (with ash) * restart all the server: failed I have no idea what is going on. Any advice?
2016/03/27
[ "https://superuser.com/questions/1057853", "https://superuser.com", "https://superuser.com/users/244725/" ]
Your Synology probably upgraded to DSM6, in which security has been hardened... In DSM6 you can no longer use root for SSH, but you can use any other member account of the administrators group. Mind that you now need to sudo when logged in using SSH. See the DSM6 release notes!
You can also just SSH using rsa keys, then you can SSH as root, even after installing DSM6, without making any additional changes.
1,057,853
After some automatic updates (or being hacked?) I have many things broken and a huge problem to resolve them since **I can't login as root anymore**. * ssh admin: login success * su root: permission denied (probably not the same password) What I have tried: * read log: but permission denied * use 'synopass' and empty password: failed * use synouser: permission denied * change password of admin hoping it will update the root password: failed. * check the root user in /etc/passwd: he is ok (with ash) * restart all the server: failed I have no idea what is going on. Any advice?
2016/03/27
[ "https://superuser.com/questions/1057853", "https://superuser.com", "https://superuser.com/users/244725/" ]
Your Synology probably upgraded to DSM6, in which security has been hardened... In DSM6 you can no longer use root for SSH, but you can use any other member account of the administrators group. Mind that you now need to sudo when logged in using SSH. See the DSM6 release notes!
If you're still with DSM Version 5, you might have logged in as admin instead of root. This makes a difference, even though root and admin share the same password. To solve, do ``` ssh [email protected] ``` with using the admin password. This will log you in as root, with root access.
1,057,853
After some automatic updates (or being hacked?) I have many things broken and a huge problem to resolve them since **I can't login as root anymore**. * ssh admin: login success * su root: permission denied (probably not the same password) What I have tried: * read log: but permission denied * use 'synopass' and empty password: failed * use synouser: permission denied * change password of admin hoping it will update the root password: failed. * check the root user in /etc/passwd: he is ok (with ash) * restart all the server: failed I have no idea what is going on. Any advice?
2016/03/27
[ "https://superuser.com/questions/1057853", "https://superuser.com", "https://superuser.com/users/244725/" ]
Your Synology probably upgraded to DSM6, in which security has been hardened... In DSM6 you can no longer use root for SSH, but you can use any other member account of the administrators group. Mind that you now need to sudo when logged in using SSH. See the DSM6 release notes!
In DSM Version 6 you can still login as root when using RSA keys. Therefore just copy your public key as admin to your Synolgy: ``` $ cat ~/.ssh/id_rsa.pub | ssh [email protected] 'umask 077; cat >>/tmp/authorized_keys' ``` After that login to your Synology as admin and become root: ``` $ ssh [email protected] [email protected]'s password: admin@My-Synology:/$ sudo -i Password: ``` No create the .ssh directory for root, move your key and change the owner of that file: ``` root@My-Synology:~# mkdir -m0700 /root/.ssh root@My-Synology:~# mv /tmp/authorized_keys /root/.ssh/ root@My-Synology:~# chown root:root /root/.ssh/authorized_keys ``` After that you can login to your Synology as root without having to enter the password.
1,057,853
After some automatic updates (or being hacked?) I have many things broken and a huge problem to resolve them since **I can't login as root anymore**. * ssh admin: login success * su root: permission denied (probably not the same password) What I have tried: * read log: but permission denied * use 'synopass' and empty password: failed * use synouser: permission denied * change password of admin hoping it will update the root password: failed. * check the root user in /etc/passwd: he is ok (with ash) * restart all the server: failed I have no idea what is going on. Any advice?
2016/03/27
[ "https://superuser.com/questions/1057853", "https://superuser.com", "https://superuser.com/users/244725/" ]
If your synology is in DSM6 and you're logged with a user part of administrator group, you can do : **sudo -i** enter your root/admin password or even **sudo su -** (it works to) now you're root tadaaa
You can also just SSH using rsa keys, then you can SSH as root, even after installing DSM6, without making any additional changes.
1,057,853
After some automatic updates (or being hacked?) I have many things broken and a huge problem to resolve them since **I can't login as root anymore**. * ssh admin: login success * su root: permission denied (probably not the same password) What I have tried: * read log: but permission denied * use 'synopass' and empty password: failed * use synouser: permission denied * change password of admin hoping it will update the root password: failed. * check the root user in /etc/passwd: he is ok (with ash) * restart all the server: failed I have no idea what is going on. Any advice?
2016/03/27
[ "https://superuser.com/questions/1057853", "https://superuser.com", "https://superuser.com/users/244725/" ]
If your synology is in DSM6 and you're logged with a user part of administrator group, you can do : **sudo -i** enter your root/admin password or even **sudo su -** (it works to) now you're root tadaaa
If you're still with DSM Version 5, you might have logged in as admin instead of root. This makes a difference, even though root and admin share the same password. To solve, do ``` ssh [email protected] ``` with using the admin password. This will log you in as root, with root access.
1,057,853
After some automatic updates (or being hacked?) I have many things broken and a huge problem to resolve them since **I can't login as root anymore**. * ssh admin: login success * su root: permission denied (probably not the same password) What I have tried: * read log: but permission denied * use 'synopass' and empty password: failed * use synouser: permission denied * change password of admin hoping it will update the root password: failed. * check the root user in /etc/passwd: he is ok (with ash) * restart all the server: failed I have no idea what is going on. Any advice?
2016/03/27
[ "https://superuser.com/questions/1057853", "https://superuser.com", "https://superuser.com/users/244725/" ]
If your synology is in DSM6 and you're logged with a user part of administrator group, you can do : **sudo -i** enter your root/admin password or even **sudo su -** (it works to) now you're root tadaaa
In DSM Version 6 you can still login as root when using RSA keys. Therefore just copy your public key as admin to your Synolgy: ``` $ cat ~/.ssh/id_rsa.pub | ssh [email protected] 'umask 077; cat >>/tmp/authorized_keys' ``` After that login to your Synology as admin and become root: ``` $ ssh [email protected] [email protected]'s password: admin@My-Synology:/$ sudo -i Password: ``` No create the .ssh directory for root, move your key and change the owner of that file: ``` root@My-Synology:~# mkdir -m0700 /root/.ssh root@My-Synology:~# mv /tmp/authorized_keys /root/.ssh/ root@My-Synology:~# chown root:root /root/.ssh/authorized_keys ``` After that you can login to your Synology as root without having to enter the password.
1,057,853
After some automatic updates (or being hacked?) I have many things broken and a huge problem to resolve them since **I can't login as root anymore**. * ssh admin: login success * su root: permission denied (probably not the same password) What I have tried: * read log: but permission denied * use 'synopass' and empty password: failed * use synouser: permission denied * change password of admin hoping it will update the root password: failed. * check the root user in /etc/passwd: he is ok (with ash) * restart all the server: failed I have no idea what is going on. Any advice?
2016/03/27
[ "https://superuser.com/questions/1057853", "https://superuser.com", "https://superuser.com/users/244725/" ]
In DSM Version 6 you can still login as root when using RSA keys. Therefore just copy your public key as admin to your Synolgy: ``` $ cat ~/.ssh/id_rsa.pub | ssh [email protected] 'umask 077; cat >>/tmp/authorized_keys' ``` After that login to your Synology as admin and become root: ``` $ ssh [email protected] [email protected]'s password: admin@My-Synology:/$ sudo -i Password: ``` No create the .ssh directory for root, move your key and change the owner of that file: ``` root@My-Synology:~# mkdir -m0700 /root/.ssh root@My-Synology:~# mv /tmp/authorized_keys /root/.ssh/ root@My-Synology:~# chown root:root /root/.ssh/authorized_keys ``` After that you can login to your Synology as root without having to enter the password.
You can also just SSH using rsa keys, then you can SSH as root, even after installing DSM6, without making any additional changes.
1,057,853
After some automatic updates (or being hacked?) I have many things broken and a huge problem to resolve them since **I can't login as root anymore**. * ssh admin: login success * su root: permission denied (probably not the same password) What I have tried: * read log: but permission denied * use 'synopass' and empty password: failed * use synouser: permission denied * change password of admin hoping it will update the root password: failed. * check the root user in /etc/passwd: he is ok (with ash) * restart all the server: failed I have no idea what is going on. Any advice?
2016/03/27
[ "https://superuser.com/questions/1057853", "https://superuser.com", "https://superuser.com/users/244725/" ]
In DSM Version 6 you can still login as root when using RSA keys. Therefore just copy your public key as admin to your Synolgy: ``` $ cat ~/.ssh/id_rsa.pub | ssh [email protected] 'umask 077; cat >>/tmp/authorized_keys' ``` After that login to your Synology as admin and become root: ``` $ ssh [email protected] [email protected]'s password: admin@My-Synology:/$ sudo -i Password: ``` No create the .ssh directory for root, move your key and change the owner of that file: ``` root@My-Synology:~# mkdir -m0700 /root/.ssh root@My-Synology:~# mv /tmp/authorized_keys /root/.ssh/ root@My-Synology:~# chown root:root /root/.ssh/authorized_keys ``` After that you can login to your Synology as root without having to enter the password.
If you're still with DSM Version 5, you might have logged in as admin instead of root. This makes a difference, even though root and admin share the same password. To solve, do ``` ssh [email protected] ``` with using the admin password. This will log you in as root, with root access.
130,727
I know this has been attempted many times before: Here [Transfer points between sites](https://meta.stackexchange.com/questions/34860/transfer-points-between-sites), here [Should SO rep be considered in SU and SF?](https://meta.stackexchange.com/questions/15117/should-so-rep-be-considered-in-su-and-sf), here too [Why not merge reputation across Stack Overflow, Server Fault, and Super User?](https://meta.stackexchange.com/questions/6336/why-not-merge-reputation-across-so-sf-and-su), here [Can I use my rep from one site to give a bounty on another](https://meta.stackexchange.com/questions/93172/can-i-use-my-rep-from-one-site-to-give-a-bounty-on-another), here [Allow bounty to be set with reputation from another site?](https://meta.stackexchange.com/questions/7193/allow-bounty-to-be-set-with-reputation-from-another-site), and here [Sharing the reputation among all the Stack Exchange sites](https://meta.stackexchange.com/questions/99658/sharing-the-reputation-among-all-the-stack-exchange-sites), here as well [How about a shared reputation?](https://meta.stackexchange.com/questions/79409/how-about-a-shared-reputation) and there are many many more posts about this.... The fact that there are so many posts about it shows that there is a true desire for a transferring reputation from site to site. The main initiative is that everybody is specializes in something, but might have a difficult questions in a subject that (s)hes not so good in and therefore cannot get sufficient reputation to offer bounty to get his/her question answered. Well I am in that kind of situation. I've some reputation on SO, but am struggling to have enough reputation on SF and Ask Ubuntu to get some of my tough questions answered. Many concerns have been posted about the idea of transferring reputation from on site to another: * Reputation is a measure of trust and experience: Somebody with a high reputation on SO should be able to have the same in Mathematics (without earning it there). * Reputation on one site doesn't have the same value as reputation on another site. This is the issue Shog9 has posted in his comment: > > Imagine a site where getting to 10K reputation points requires a near-herculean effort - it's easy if you try - and now imagine that some schmuck like me, with 50K on SO, wanders in, accumulates 200 points, and then starts handing out 500 point bounties left and right. Within a disturbingly short time, I could eclipse the influence of users who've labored to shape that site from day one, with minimal effort. That ain't right. > > > * Giving out bounties requires the op to be able to judge who is most worthy of receiving bounty if more than one answer is given. I think I have come up with an easy solution that fulfills the goal without affecting any of the concerns: My idea is to setup another "token" lets call it "bounty credit" or just "credit" that has the following rules applied: 1. Reputation can be converted into credit at a 1:1 ratio. 2. Credit cannot be converted back into reputation. 3. Credit cannot be directly transferred from one site to another. 4. Users can exchange credit with another user from another site at any ratio that both users agree to. 5. Trading bounties is a privilege that only comes after 200 reputation. 6. The amount of credit that user has on each site is not made public. 7. Credit can only be used to post bounties or for exchanging credit with other sites. 8. Users cannot trade credit with themselves. A simple trading system can be set up on which users can easily exchange credit with other users, just like on a stock market. The community will thus define how much the credit is worth on each site, simply depending on demand and availability. **Credit on SO will be least valuable, because reputation there is most abundant (means that it probably requires less effort). People exchanging SO credits will be more willing to trade more for less than on other sites. This will make sure that nobody will be able to spend more bounty on another site than (s)he really deserves to. After all the bounty that (s)he spends must have been earned by somebody in the normal way on that same site and somebody will not give it out for nothing.** The extra benefit that comes here is that people harvest their reputation is on the subject that they are best at and not where they have the most pressing question and therefore the time will be best spent. The fact that nobody can exchange credit without having more than 200 reputation ensures that everybody using this system has at least got some idea on the topic and is thus well able to decide which answer most worthy of a bounty. Perhaps the exchange should also be taxed at say 10% to prevent some people gaining a lot of credit, just by trading it around. I think this idea would become very useful to many users, without affecting the ecosystem in any negative way. What do you think?
2012/04/29
[ "https://meta.stackexchange.com/questions/130727", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/180987/" ]
> > The fact that there are so many posts about it shows that there is a true desire for a transferring reputation from site to site. > > > Yup. Coupled with, > > My idea is to setup another "currency" lets call it "bounty credit" > > > ...the mistaken idea that reputation is in any significant way *a currency*. Granted, the very *existence* of a bounty system does go a long way toward encouraging that impression. *Hopefully,* the severe restrictions placed on it do *something* to counteract that. Nevertheless... * Reputation is not a currency. The reputation system is [a token economy](http://en.wikipedia.org/wiki/Token_economy). * It doesn't "cost" anything to ask a question, or get an answer, on any Stack Exchange site. If you think you *have* to offer a bounty in order to get an answer to your question, you should probably think about ways of writing a better question instead. * Reputation on one site doesn't necessarily mean *anything* in the context of *any other site.* * Awarding a bounty is simply a way to vouch for another user's expertise, with the deduction from your own reputation serving to both limit the frequency of such things and demand that you have at least some small amount of experience yourself. Think of it as a ["super up-vote"](https://meta.stackexchange.com/questions/8098/should-we-have-a-small-number-of-supervotes-per-day). * **Reputation is not a currency.** Any attempt to make it into one will be met with severe opposition. ### Related: [What exactly is "artificial inflation of reputation", and where is the line?](https://meta.stackoverflow.com/questions/318497/what-exactly-is-artificial-inflation-of-reputation-and-where-is-the-line/318499#318499)
Once upon a time there was a site called experts exchange. They started out offering Q&A for free. Then they started charging. So to get help, to get that knowledge out of people's heads, required cold hard cash. Jeff and Joel when they started SO did so [with the express intention of not being experts exchange.](http://www.codinghorror.com/blog/2008/04/introducing-stackoverflow-com.html) As you can see, therefore, the idea of trading "credit" or "paying" for help here, on these sites, is pretty much directly opposed with the original reason for starting SO. I can't comment on the idea of trading reputation between sites, or bountying rep from one site to users on another. Aside from its technical complexity, I've no real opinions either way. But inter-site credit - I don't think that'll happen. There's another good reason it won't happen - there is *already* a kind of credit you can offer - money! Simply [hire someone with the skillset you need](http://careers.stackoverflow.com/) (you may need to persuade Mr Shog above to get careers implemented for your site of choice, but never mind).
130,727
I know this has been attempted many times before: Here [Transfer points between sites](https://meta.stackexchange.com/questions/34860/transfer-points-between-sites), here [Should SO rep be considered in SU and SF?](https://meta.stackexchange.com/questions/15117/should-so-rep-be-considered-in-su-and-sf), here too [Why not merge reputation across Stack Overflow, Server Fault, and Super User?](https://meta.stackexchange.com/questions/6336/why-not-merge-reputation-across-so-sf-and-su), here [Can I use my rep from one site to give a bounty on another](https://meta.stackexchange.com/questions/93172/can-i-use-my-rep-from-one-site-to-give-a-bounty-on-another), here [Allow bounty to be set with reputation from another site?](https://meta.stackexchange.com/questions/7193/allow-bounty-to-be-set-with-reputation-from-another-site), and here [Sharing the reputation among all the Stack Exchange sites](https://meta.stackexchange.com/questions/99658/sharing-the-reputation-among-all-the-stack-exchange-sites), here as well [How about a shared reputation?](https://meta.stackexchange.com/questions/79409/how-about-a-shared-reputation) and there are many many more posts about this.... The fact that there are so many posts about it shows that there is a true desire for a transferring reputation from site to site. The main initiative is that everybody is specializes in something, but might have a difficult questions in a subject that (s)hes not so good in and therefore cannot get sufficient reputation to offer bounty to get his/her question answered. Well I am in that kind of situation. I've some reputation on SO, but am struggling to have enough reputation on SF and Ask Ubuntu to get some of my tough questions answered. Many concerns have been posted about the idea of transferring reputation from on site to another: * Reputation is a measure of trust and experience: Somebody with a high reputation on SO should be able to have the same in Mathematics (without earning it there). * Reputation on one site doesn't have the same value as reputation on another site. This is the issue Shog9 has posted in his comment: > > Imagine a site where getting to 10K reputation points requires a near-herculean effort - it's easy if you try - and now imagine that some schmuck like me, with 50K on SO, wanders in, accumulates 200 points, and then starts handing out 500 point bounties left and right. Within a disturbingly short time, I could eclipse the influence of users who've labored to shape that site from day one, with minimal effort. That ain't right. > > > * Giving out bounties requires the op to be able to judge who is most worthy of receiving bounty if more than one answer is given. I think I have come up with an easy solution that fulfills the goal without affecting any of the concerns: My idea is to setup another "token" lets call it "bounty credit" or just "credit" that has the following rules applied: 1. Reputation can be converted into credit at a 1:1 ratio. 2. Credit cannot be converted back into reputation. 3. Credit cannot be directly transferred from one site to another. 4. Users can exchange credit with another user from another site at any ratio that both users agree to. 5. Trading bounties is a privilege that only comes after 200 reputation. 6. The amount of credit that user has on each site is not made public. 7. Credit can only be used to post bounties or for exchanging credit with other sites. 8. Users cannot trade credit with themselves. A simple trading system can be set up on which users can easily exchange credit with other users, just like on a stock market. The community will thus define how much the credit is worth on each site, simply depending on demand and availability. **Credit on SO will be least valuable, because reputation there is most abundant (means that it probably requires less effort). People exchanging SO credits will be more willing to trade more for less than on other sites. This will make sure that nobody will be able to spend more bounty on another site than (s)he really deserves to. After all the bounty that (s)he spends must have been earned by somebody in the normal way on that same site and somebody will not give it out for nothing.** The extra benefit that comes here is that people harvest their reputation is on the subject that they are best at and not where they have the most pressing question and therefore the time will be best spent. The fact that nobody can exchange credit without having more than 200 reputation ensures that everybody using this system has at least got some idea on the topic and is thus well able to decide which answer most worthy of a bounty. Perhaps the exchange should also be taxed at say 10% to prevent some people gaining a lot of credit, just by trading it around. I think this idea would become very useful to many users, without affecting the ecosystem in any negative way. What do you think?
2012/04/29
[ "https://meta.stackexchange.com/questions/130727", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/180987/" ]
> > The fact that there are so many posts about it shows that there is a true desire for a transferring reputation from site to site. > > > Yup. Coupled with, > > My idea is to setup another "currency" lets call it "bounty credit" > > > ...the mistaken idea that reputation is in any significant way *a currency*. Granted, the very *existence* of a bounty system does go a long way toward encouraging that impression. *Hopefully,* the severe restrictions placed on it do *something* to counteract that. Nevertheless... * Reputation is not a currency. The reputation system is [a token economy](http://en.wikipedia.org/wiki/Token_economy). * It doesn't "cost" anything to ask a question, or get an answer, on any Stack Exchange site. If you think you *have* to offer a bounty in order to get an answer to your question, you should probably think about ways of writing a better question instead. * Reputation on one site doesn't necessarily mean *anything* in the context of *any other site.* * Awarding a bounty is simply a way to vouch for another user's expertise, with the deduction from your own reputation serving to both limit the frequency of such things and demand that you have at least some small amount of experience yourself. Think of it as a ["super up-vote"](https://meta.stackexchange.com/questions/8098/should-we-have-a-small-number-of-supervotes-per-day). * **Reputation is not a currency.** Any attempt to make it into one will be met with severe opposition. ### Related: [What exactly is "artificial inflation of reputation", and where is the line?](https://meta.stackoverflow.com/questions/318497/what-exactly-is-artificial-inflation-of-reputation-and-where-is-the-line/318499#318499)
I started a bounty today on Skeptics, on a [question](https://skeptics.stackexchange.com/q/7750/5142) that I really want to know the answer to. The 50 rep bounty may seem quite insignificant, but it did lose me three privileges on the site (create chat rooms, edit community wiki, and ironically set bounties) and it could have been far larger if I could dip into my 20K network rep for it. So, I really do get where you are coming from. But, I am not a contributing member on Skeptics. Sure, I read through it almost every day, I even edited a question once (I'm that awesome), but I haven't asked or answered a single question, all my reputation on the site is from the 101 association bonus and from edits. That's important because bounties naturally attract people to the question, and I already feel like I cheated a bit here by exploiting the rep from the association bonus, as although I really want the question answered, I also happen to know the OP in real life (Hi Liza ;). I have absolutely no idea if the question is a good one for the site, heh, I'm not even sure it's on topic, but the bounty will definitely bring some attention to it. No big deal when it's one question, but think about it, with a network wide rep bounty thingy in place I could place bounties on crap questions all over the network, on sites that are about things I have little (if any) idea about. It may sound like a good idea when you think of sites like Programmers, Stack Overflow, and Code Review, but it starts sounding like a very bad idea when you add Biblical Hermeneutics, Poker and Musical Practice and Performance in the mix. In short, setting bounties is a privilege, it's better to only have it where you earned it.
130,727
I know this has been attempted many times before: Here [Transfer points between sites](https://meta.stackexchange.com/questions/34860/transfer-points-between-sites), here [Should SO rep be considered in SU and SF?](https://meta.stackexchange.com/questions/15117/should-so-rep-be-considered-in-su-and-sf), here too [Why not merge reputation across Stack Overflow, Server Fault, and Super User?](https://meta.stackexchange.com/questions/6336/why-not-merge-reputation-across-so-sf-and-su), here [Can I use my rep from one site to give a bounty on another](https://meta.stackexchange.com/questions/93172/can-i-use-my-rep-from-one-site-to-give-a-bounty-on-another), here [Allow bounty to be set with reputation from another site?](https://meta.stackexchange.com/questions/7193/allow-bounty-to-be-set-with-reputation-from-another-site), and here [Sharing the reputation among all the Stack Exchange sites](https://meta.stackexchange.com/questions/99658/sharing-the-reputation-among-all-the-stack-exchange-sites), here as well [How about a shared reputation?](https://meta.stackexchange.com/questions/79409/how-about-a-shared-reputation) and there are many many more posts about this.... The fact that there are so many posts about it shows that there is a true desire for a transferring reputation from site to site. The main initiative is that everybody is specializes in something, but might have a difficult questions in a subject that (s)hes not so good in and therefore cannot get sufficient reputation to offer bounty to get his/her question answered. Well I am in that kind of situation. I've some reputation on SO, but am struggling to have enough reputation on SF and Ask Ubuntu to get some of my tough questions answered. Many concerns have been posted about the idea of transferring reputation from on site to another: * Reputation is a measure of trust and experience: Somebody with a high reputation on SO should be able to have the same in Mathematics (without earning it there). * Reputation on one site doesn't have the same value as reputation on another site. This is the issue Shog9 has posted in his comment: > > Imagine a site where getting to 10K reputation points requires a near-herculean effort - it's easy if you try - and now imagine that some schmuck like me, with 50K on SO, wanders in, accumulates 200 points, and then starts handing out 500 point bounties left and right. Within a disturbingly short time, I could eclipse the influence of users who've labored to shape that site from day one, with minimal effort. That ain't right. > > > * Giving out bounties requires the op to be able to judge who is most worthy of receiving bounty if more than one answer is given. I think I have come up with an easy solution that fulfills the goal without affecting any of the concerns: My idea is to setup another "token" lets call it "bounty credit" or just "credit" that has the following rules applied: 1. Reputation can be converted into credit at a 1:1 ratio. 2. Credit cannot be converted back into reputation. 3. Credit cannot be directly transferred from one site to another. 4. Users can exchange credit with another user from another site at any ratio that both users agree to. 5. Trading bounties is a privilege that only comes after 200 reputation. 6. The amount of credit that user has on each site is not made public. 7. Credit can only be used to post bounties or for exchanging credit with other sites. 8. Users cannot trade credit with themselves. A simple trading system can be set up on which users can easily exchange credit with other users, just like on a stock market. The community will thus define how much the credit is worth on each site, simply depending on demand and availability. **Credit on SO will be least valuable, because reputation there is most abundant (means that it probably requires less effort). People exchanging SO credits will be more willing to trade more for less than on other sites. This will make sure that nobody will be able to spend more bounty on another site than (s)he really deserves to. After all the bounty that (s)he spends must have been earned by somebody in the normal way on that same site and somebody will not give it out for nothing.** The extra benefit that comes here is that people harvest their reputation is on the subject that they are best at and not where they have the most pressing question and therefore the time will be best spent. The fact that nobody can exchange credit without having more than 200 reputation ensures that everybody using this system has at least got some idea on the topic and is thus well able to decide which answer most worthy of a bounty. Perhaps the exchange should also be taxed at say 10% to prevent some people gaining a lot of credit, just by trading it around. I think this idea would become very useful to many users, without affecting the ecosystem in any negative way. What do you think?
2012/04/29
[ "https://meta.stackexchange.com/questions/130727", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/180987/" ]
I started a bounty today on Skeptics, on a [question](https://skeptics.stackexchange.com/q/7750/5142) that I really want to know the answer to. The 50 rep bounty may seem quite insignificant, but it did lose me three privileges on the site (create chat rooms, edit community wiki, and ironically set bounties) and it could have been far larger if I could dip into my 20K network rep for it. So, I really do get where you are coming from. But, I am not a contributing member on Skeptics. Sure, I read through it almost every day, I even edited a question once (I'm that awesome), but I haven't asked or answered a single question, all my reputation on the site is from the 101 association bonus and from edits. That's important because bounties naturally attract people to the question, and I already feel like I cheated a bit here by exploiting the rep from the association bonus, as although I really want the question answered, I also happen to know the OP in real life (Hi Liza ;). I have absolutely no idea if the question is a good one for the site, heh, I'm not even sure it's on topic, but the bounty will definitely bring some attention to it. No big deal when it's one question, but think about it, with a network wide rep bounty thingy in place I could place bounties on crap questions all over the network, on sites that are about things I have little (if any) idea about. It may sound like a good idea when you think of sites like Programmers, Stack Overflow, and Code Review, but it starts sounding like a very bad idea when you add Biblical Hermeneutics, Poker and Musical Practice and Performance in the mix. In short, setting bounties is a privilege, it's better to only have it where you earned it.
Once upon a time there was a site called experts exchange. They started out offering Q&A for free. Then they started charging. So to get help, to get that knowledge out of people's heads, required cold hard cash. Jeff and Joel when they started SO did so [with the express intention of not being experts exchange.](http://www.codinghorror.com/blog/2008/04/introducing-stackoverflow-com.html) As you can see, therefore, the idea of trading "credit" or "paying" for help here, on these sites, is pretty much directly opposed with the original reason for starting SO. I can't comment on the idea of trading reputation between sites, or bountying rep from one site to users on another. Aside from its technical complexity, I've no real opinions either way. But inter-site credit - I don't think that'll happen. There's another good reason it won't happen - there is *already* a kind of credit you can offer - money! Simply [hire someone with the skillset you need](http://careers.stackoverflow.com/) (you may need to persuade Mr Shog above to get careers implemented for your site of choice, but never mind).
59,241,490
Here is my spreadsheet for testing purposes: <https://docs.google.com/spreadsheets/d/1m8_ck9hvxIXohMjGBTX17uvOui0P4KjsTwF8M72MSFg/edit?usp=sharing> What I am trying to do is find all values > 15 in a 2D range in the spreadsheet tab "InvoiceBackup", then list their order numbers and prices on a separate tab. I used Logger.log() to log every possible step where things were going wrong, and found a few, notably the line when I logged the value of mainArray and it looked like the last three rows were null after it should have 5 rows with values in them. Anyway if you take a look at the sheet you can see there are lots of problems with mainArray, and I have no idea how to solve them, I'm really new to JavaScript. The script works fine when each order# has only one box with > 15 pints, but if a single order has multiple it gets all messed up. The 2 named ranges are 1) Columns ABC of InvoiceBackup, and 2) columns P to AE of InvoiceBackup My entire code is below: ``` function MoreThanFifteenPints () { var ss = SpreadsheetApp.getActiveSpreadsheet(); var OrderWarehouseTable = ss.getRangeByName('OrderToWarehouse').getValues(); var PintsInBoxesTable = ss.getRangeByName('PintsInBoxes').getValues(); var mainArray = []; // the main table that will be returned //MTFP == More Than Fifteen Pints var IndicesOfMTFP = []; //row index var ColumnIndexMTFP = []; // column index of pints in boxes table where value is > 15 // find the Indices of MTFP for (var i = 0; i < PintsInBoxesTable.length; i++) { for (var j = 0; j < PintsInBoxesTable[i].length; j++) { if (PintsInBoxesTable[i][j] > 15) { IndicesOfMTFP.push(i); ColumnIndexMTFP.push(j); } } } Logger.log('columns of mtfp: ' + ColumnIndexMTFP); Logger.log(' indices of mtfp: ' + IndicesOfMTFP); for (var i = 0; i < IndicesOfMTFP.length; i++) { // initialize mainArray DOESN'T SEEM TO WORK CORRECTLY //mainArray[i] = new Array(5); mainArray.push(OrderWarehouseTable[(IndicesOfMTFP[i])]); } // Logger.log('first first mainarray is ' + mainArray + 'mainarray length is ' + mainArray.length); /** for (var i = 0; i < IndicesOfMTFP.length; i++) { Logger.log('indicesofMTFP[i] = ' + IndicesOfMTFP[i]); mainArray.push(OrderWarehouseTable[IndicesOfMTFP[i]]); Logger.log('FIRST MAIN ARRAY [I] IS EQUAL TO: ' + mainArray[i]); Logger.log('main array inside for loop is ' + mainArray); } */ Logger.log(' FIRST MAIN ARRAY IS: ' + mainArray + '<-- mainarray length is ' + mainArray.length); //mainArray. Logger.log('FIRST MAIN ARRAY [3] IS EQUAL TO: ' + mainArray[3]); //return IndicesOfMTFP; var PintsNumArray = []; // array of Pint numbers to add to mainArray for (var i = 0; i < IndicesOfMTFP.length; i++) { PintsNumArray.push(PintsInBoxesTable[IndicesOfMTFP[i]][ColumnIndexMTFP[i]]); //not 100% sure if this is working correctly //mainArray[i][3] = PintsInBoxesTable[IndicesOfMTFP[i]][ColumnIndexMTFP[i]]; //Logger.log('PintsNumArray[i]= ' + PintsNumArray[i]); } Logger.log('PintsNumArray = ' + PintsNumArray); for (var i = 0; i < PintsNumArray.length; i++) { //Logger.log('PintsNum [i].length= ' + PintsNumArray[i].length); mainArray[i].push(PintsNumArray[i]); //this is not working correctly mainArray[i].push(getPrice(PintsNumArray[i])); Logger.log('mainarray[i] is: '+ i + ': ' + mainArray[i]); Logger.log('main array IN THE FOR LOOP is ' + mainArray); } Logger.log('mainarray[0]: ' + mainArray[0]); Logger.log('mainarray[1]: ' + mainArray[1]); Logger.log('mainarray[2]: ' + mainArray[2]); Logger.log('mainarray[3]: ' + mainArray[3]); var Total = 0; for (var i = 0; i < PintsNumArray.length; i++) { Total += mainArray[i][4]; } //return PintsNumArray; mainArray.push(['Total',,,,Total]); //mainArray[mainArray.lastIndexOf()][0] = 'Total'; return mainArray; } function getPrice(PintQty) { var BasePrice = 10.05; if (PintQty > 15) { PintQty = PintQty - 15; PintQty = (PintQty * 2.5) + BasePrice; return PintQty; } else return 'Enter a Qty greater than 15'; } ```
2019/12/09
[ "https://Stackoverflow.com/questions/59241490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12465806/" ]
You need to use `AddIdentity` instead of `AddDefaultIdentity` if you would like to set by `ConfigureApplicationCookie`. ``` services.AddIdentity<IdentityUser,IdentityRole>() //.AddDefaultUI(UIFramework.Bootstrap4) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); ``` Or you could just try to configure `CookieAuthenticationOptions` to achieve your requirement. ``` services.AddIdentity<IdentityUser,IdentityRole>() .AddDefaultUI(UIFramework.Bootstrap4) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.PostConfigure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme, options => { options.Cookie.Expiration = TimeSpan.FromMinutes(20); options.LoginPath = "/Account/Login"; options.LogoutPath = "/Account/Logout"; options.AccessDeniedPath = "/Account/AccessDenied"; options.SlidingExpiration = true; options.ExpireTimeSpan = TimeSpan.FromMinutes(20); }); ```
I had a similar problem and the only thing that solved it was using creating a `PathString` instead of using an string for any path. ``` options.LoginPath = new PathString("/Home/Index"); ```
1,390,047
I couldn't solve this equation. Could you help me to solve this step by step. Thank you. $$\sqrt[4]{\frac{8^x}{8}}=\sqrt[3]{16}$$
2015/08/08
[ "https://math.stackexchange.com/questions/1390047", "https://math.stackexchange.com", "https://math.stackexchange.com/users/258415/" ]
\begin{align} \sqrt[4]{8^{x} \times \frac{1}{8}} &= \sqrt[3]{16} \\ \sqrt[4]{8^{x-1}} &= \sqrt[3]{16} \\ 8^{x-1} &= \left( \sqrt[3]{16} \right)^{4} \\ 8^{x-1} &= 16^{\frac{4}{3}} \\ 2^{3x-3} &= 2^{\frac{16}{3}} \\ 3x-3 &= \frac{16}{3} \quad \to \quad 3x = \frac{16}{3} +3 \quad \to \quad x = 1+\frac{16}{9} \quad \to \quad x = \frac{25}{9} \end{align}
$$2^{(3x-3)/4}=2^{4/3}$$ $$9x-9=16$$ $$x=25/9$$
50,768,023
Okie dokie, I'm trying to get Google's Dialogflow python API working with Google App Engine, and I seem to be running into issues when I run the application. I have pip installed dialogflow to a lib folder and added the lib folder through the app.yaml file. I keep running into an error where it says that it can't find 'six.moves.' Very new to this (app engine in general), so please tell me if I have something setup wrong. I've read a few other threads with no luck. This won't work locally or deployed. below are my app.yaml file: ``` runtime: python27 api_version: 1 threadsafe: true service: basic-npl-ui handlers: - url: /img static_dir: img - url: /javascript static_dir: javascript - url: /css static_dir: css - url: /.* script: main.app env_variables: GAE_USE_SOCKETS_HTTPLIB: 'anyvalue' libraries: - name: jinja2 version: latest - name: webapp2 version: latest - name: ssl version: latest - name: grpcio version: latest ``` and here's my error log (local development): ``` Traceback (most recent call last): File "/Users/AVD1WIP/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/Users/AVD1WIP/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler handler, path, err = LoadObject(self._handler) File "/Users/AVD1WIP/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject obj = __import__(path[0]) File "/Users/AVD1WIP/Documents/Orca_interns/NLP/basic_ui_app/main.py", line 28, in <module> from src.dialog_response_util import DialogflowResponseUtil File "/Users/AVD1WIP/Documents/Orca_interns/NLP/basic_ui_app/src/dialog_response_util.py", line 2, in <module> import dialogflow File "/Users/AVD1WIP/Documents/Orca_interns/NLP/basic_ui_app/lib/dialogflow/__init__.py", line 17, in <module> from dialogflow_v2 import AgentsClient File "/Users/AVD1WIP/Documents/Orca_interns/NLP/basic_ui_app/lib/dialogflow_v2/__init__.py", line 18, in <module> from dialogflow_v2.gapic import agents_client File "/Users/AVD1WIP/Documents/Orca_interns/NLP/basic_ui_app/lib/dialogflow_v2/gapic/agents_client.py", line 19, in <module> import google.api_core.gapic_v1.client_info File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/google/api_core/gapic_v1/__init__.py", line 16, in <module> from google.api_core.gapic_v1 import config File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/google/api_core/gapic_v1/config.py", line 26, in <module> from google.api_core import exceptions File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/google/api_core/exceptions.py", line 26, in <module> from six.moves import http_client ImportError: No module named moves INFO 2018-06-08 20:20:19,020 module.py:846] basic-npl-ui: "GET / HTTP/1.1" 500 - ```
2018/06/08
[ "https://Stackoverflow.com/questions/50768023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9915619/" ]
Okay, this is what I've come up with. It doesn't literally let me know when the slider is released, but it tells me when the player stops editing the slider. It still sends an alert if you pause briefly, but that is okay for my game. It doesn't send continuous alerts like if you just use \_on\_HSlider\_value\_changed(), which is what I wanted to avoid. ``` var old = self.value #start value of slider var timer_on = false #will be called continuously while editing timer func editing_slider(new): #only start a timer, if there isn't one already or you'll have a million if not timer_on: #start timer timer_on = true yield(get_tree().create_timer(.2), "timeout" ) timer_on = false #if still editing, re call function if old != new: editing_slider(new) #done editing else: print("slider set to " + str(value)) old = new func _on_HSlider_value_changed(value): editing_slider(value) ``` If you wanted to avoid the alert being called when the user pauses but hasn't released, you'd have to do do some kind of InputEvent check.
You can achieve what you want by overriding the \_gui\_input function. Attach a script to your slider, and then add this code: ``` func _gui_input(event): if (event is InputEventMouseButton) && !event.pressed && (event.button_index == BUTTON_LEFT): print("Released") ``` This will work whether the user releases the grabber or "releases an area on the slider's range to select a new value without using the grabber", and achieves what you want. However, if the code is meant to run on a device with a keyboard (e.g. a PC), then the user can also change the value via the cursor keys on the keyboard, and you may want to add support for that too.
7,386,072
My case scenario passes parameter to a procedure, that only does an insert. But two threads might try to pass the same value. How to handle this situation w/out throwing an exception and with least amount of locks? My performance requirement is at least 10k inserts per second. **EDIT:** Column is unique. Timestamp might be altered (adjusted) before insertion.
2011/09/12
[ "https://Stackoverflow.com/questions/7386072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/546051/" ]
Create index on table with ignore duplicate key option. It will not insert duplicate row and also won't through any error. E.g. ``` create unique index i1 on #tmp(id) with ignore_dup_key insert into #tmp values(1,"A") 2> go (1 row affected) 1> insert into #tmp values(1,"A") 2> go Duplicate key was ignored. (0 rows affected) ```
Try the [MERGE](http://technet.microsoft.com/en-us/library/bb510625.aspx) statement From MSDN . A common scenario is updating one or more columns in a table if a matching row exists, or inserting the data as a new row if a matching row does not exist. This is usually done by passing parameters to a stored procedure that contains the appropriate UPDATE and INSERT statements. With the MERGE statement, you can perform both tasks in a single statement. Regarding your performance concerns, there is also a page on [Optimizing MERGE Statement Performance](http://technet.microsoft.com/en-us/library/cc879317.aspx)
7,386,072
My case scenario passes parameter to a procedure, that only does an insert. But two threads might try to pass the same value. How to handle this situation w/out throwing an exception and with least amount of locks? My performance requirement is at least 10k inserts per second. **EDIT:** Column is unique. Timestamp might be altered (adjusted) before insertion.
2011/09/12
[ "https://Stackoverflow.com/questions/7386072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/546051/" ]
Create index on table with ignore duplicate key option. It will not insert duplicate row and also won't through any error. E.g. ``` create unique index i1 on #tmp(id) with ignore_dup_key insert into #tmp values(1,"A") 2> go (1 row affected) 1> insert into #tmp values(1,"A") 2> go Duplicate key was ignored. (0 rows affected) ```
As **@Martin Smith** has pointed out there is good solution - even though it is contrary to my question, it has good reasoning behind that seems well supported. The original answer you can find [here](https://stackoverflow.com/questions/3407857/only-inserting-a-row-if-its-not-already-there/3408196#3408196) posted by **@gbn**. ``` BEGIN TRY INSERT etc END TRY BEGIN CATCH IF ERROR_NUMBER() <> 2627 RAISERROR etc END CATCH ``` > > Seriously, this is quickest and the most concurrent without locks, especially at high volumes. What if the UPDLOCK is escalated and the whole table is locked? > > > The original text by Paul Nielsen you can find [here](http://sqlblog.com/blogs/paul_nielsen/archive/2007/12/12/10-lessons-from-35k-tps.aspx). - lesson 4. If anyone has a similar problem to mine it is good to have a look at it.
23,651,982
When user click on notification I want to start an Activity and two Intent Service. Is it possible to do ? If yes Please can any one give me the idea to do this ? Suppose I have no control on Activity. The Activity belongs to third party app. Please don't tell me that start intent service from your Activity . I know this.
2014/05/14
[ "https://Stackoverflow.com/questions/23651982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2020622/" ]
Follow the steps Hope this helps you 1) Create a BroadCastReceiver ``` public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Start Activity // Start Services } } ``` 2) Just Fire Broadcast on notification click. ``` NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Intent intent = new Intent(context, MyBroadcastReceiver.class); PendingIntent contentIntent = PendingIntent.getBroadcast(context, 0, intent, 0); Notification notification = new Notification(icon, ticker, when); notification.setLatestEventInfo(mSmartAndroidActivity, title, message, contentIntent); notification.flags = Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); ``` Use `PendingIntent.getBroadcast` instead of `PendingIntent.getActivity` 3) In BroadcastReceiver's onReceive() method -> call your third party activity -> Start services
The answer given by Biraj will also do the job. But for that You have to declare the BroadcastReceiver in your manifest file as well as all activity and services which you are starting from BroadcastReceiver. So I have not choosen the above way. How I have implemented ? I have started an Intent service from where I am starting activity and making a synchronous request to server . By this way I don't have to declare a BroadcastReceiver in my maniest file. I believe in writing less code so I have chosen the above Intent Service way
3,711,165
The problem is [![enter image description here](https://i.stack.imgur.com/8Mn6d.png)](https://i.stack.imgur.com/8Mn6d.png) I have been able to prove $left hand \rightarrow composite$, but I haven't be able to prove the reverse direction, so if you could point to me in the right direction via hint, I would really appreciate it. My attempt: So the situation is as follows: [![enter image description here](https://i.stack.imgur.com/71EmS.png)](https://i.stack.imgur.com/71EmS.png) Given $f: Q \rightarrow B$ and $g: Q \rightarrow D$, we need a unique $h: Q \rightarrow A$ such that -$f = h\_1 h $ -$g = h\_6h$ Now, the right hand square is a pull back, hence there exists a unique $k: Q \rightarrow B$ such that -$h\_2 k = h\_2 f$ -$h\_7 k = h\_5 g$ And as the composite rectangle is a pull back, there exists a uniqu $i: Q \rightarrow A$ such that -$(h\_2h\_1)i = h\_2 f$ -$h\_6 i = g$ Note $h\_7(h\_1 i) = (h\_7 h\_1) i = (h\_5 h\_6) i = h\_5 g$ $h\_2(h\_1 i) = h\_2 f$. So by uniqueness of $k$, $k = h\_1 i $ There also exists unique $i': Q \rightarrow A$ such that -$(h\_2 h\_1)i' = h\_2 k$ -$h\_6 i' = f$ By uniqueness, $i' = i$ And I'm not sure how to proceed from here. Thanks for your help!
2020/06/08
[ "https://math.stackexchange.com/questions/3711165", "https://math.stackexchange.com", "https://math.stackexchange.com/users/414214/" ]
You know there is $N$ such that $\forall n \ge N$ you have $d(x\_n, x) <1/2$ and you know that this implies $x\_n=x$ because the metric is discrete. Thus you proved that not only $x\_N=x$, but that FOR ALL $n \ge N$ it happens that $x\_n=x$. If the sequence is eventually constant, then it literally means that there are $x$ and $N$ such that $x\_n=x$ for every $n \ge N$. So it trivially converges to that $x$.
Dude, as u said earlier $x\_n$ converging to $x$. Now in discrete metric (or in any metric) $d(x,y)=0$ iff $x=y$ hence now for all $n\geq N$ $d(x\_{n},x)<1/2$ so in this discrete metric $d(x,y)=1$ or $0$ so $d(x\_n,x)=0$ so $x\_n=x$ for all $n\geq N$
3,711,165
The problem is [![enter image description here](https://i.stack.imgur.com/8Mn6d.png)](https://i.stack.imgur.com/8Mn6d.png) I have been able to prove $left hand \rightarrow composite$, but I haven't be able to prove the reverse direction, so if you could point to me in the right direction via hint, I would really appreciate it. My attempt: So the situation is as follows: [![enter image description here](https://i.stack.imgur.com/71EmS.png)](https://i.stack.imgur.com/71EmS.png) Given $f: Q \rightarrow B$ and $g: Q \rightarrow D$, we need a unique $h: Q \rightarrow A$ such that -$f = h\_1 h $ -$g = h\_6h$ Now, the right hand square is a pull back, hence there exists a unique $k: Q \rightarrow B$ such that -$h\_2 k = h\_2 f$ -$h\_7 k = h\_5 g$ And as the composite rectangle is a pull back, there exists a uniqu $i: Q \rightarrow A$ such that -$(h\_2h\_1)i = h\_2 f$ -$h\_6 i = g$ Note $h\_7(h\_1 i) = (h\_7 h\_1) i = (h\_5 h\_6) i = h\_5 g$ $h\_2(h\_1 i) = h\_2 f$. So by uniqueness of $k$, $k = h\_1 i $ There also exists unique $i': Q \rightarrow A$ such that -$(h\_2 h\_1)i' = h\_2 k$ -$h\_6 i' = f$ By uniqueness, $i' = i$ And I'm not sure how to proceed from here. Thanks for your help!
2020/06/08
[ "https://math.stackexchange.com/questions/3711165", "https://math.stackexchange.com", "https://math.stackexchange.com/users/414214/" ]
You know there is $N$ such that $\forall n \ge N$ you have $d(x\_n, x) <1/2$ and you know that this implies $x\_n=x$ because the metric is discrete. Thus you proved that not only $x\_N=x$, but that FOR ALL $n \ge N$ it happens that $x\_n=x$. If the sequence is eventually constant, then it literally means that there are $x$ and $N$ such that $x\_n=x$ for every $n \ge N$. So it trivially converges to that $x$.
Let $x\_n$ be a sequence of points of the metric space, converging to a point $x$. By definition of converging sequence, that means that for every $\epsilon$ you fixed, greater than $0$, you can find a positive integer $N\_{\epsilon}$ such that $d(x\_n,x)<\epsilon$ for all indexes $n$ greater than $N\_{\epsilon}$. That is, the distance of $x\_n$ from the limit point $x$ is eventually smaller than $\epsilon$. If you choose $\epsilon$ smaller that $1$, this means that you can find $N\_1$ such that $d(x\_n,x)$ is smaller than $1$ for all indexes $n$ greater than $N\_1$. As you said, in the discrete metric, two distinct points have distance $=1$. Therefore, having distance smaller than $1$ is equivalent to being the same point. This means that, for $n$ big enough, the distance between the $n$-th term of the sequence and the limit point $x$ will be smaller than $1$, that in discrete metric is equivalent to say that for $n$ big enough$, the $n$-th term of the sequence and the limit point will be the same point.
3,711,165
The problem is [![enter image description here](https://i.stack.imgur.com/8Mn6d.png)](https://i.stack.imgur.com/8Mn6d.png) I have been able to prove $left hand \rightarrow composite$, but I haven't be able to prove the reverse direction, so if you could point to me in the right direction via hint, I would really appreciate it. My attempt: So the situation is as follows: [![enter image description here](https://i.stack.imgur.com/71EmS.png)](https://i.stack.imgur.com/71EmS.png) Given $f: Q \rightarrow B$ and $g: Q \rightarrow D$, we need a unique $h: Q \rightarrow A$ such that -$f = h\_1 h $ -$g = h\_6h$ Now, the right hand square is a pull back, hence there exists a unique $k: Q \rightarrow B$ such that -$h\_2 k = h\_2 f$ -$h\_7 k = h\_5 g$ And as the composite rectangle is a pull back, there exists a uniqu $i: Q \rightarrow A$ such that -$(h\_2h\_1)i = h\_2 f$ -$h\_6 i = g$ Note $h\_7(h\_1 i) = (h\_7 h\_1) i = (h\_5 h\_6) i = h\_5 g$ $h\_2(h\_1 i) = h\_2 f$. So by uniqueness of $k$, $k = h\_1 i $ There also exists unique $i': Q \rightarrow A$ such that -$(h\_2 h\_1)i' = h\_2 k$ -$h\_6 i' = f$ By uniqueness, $i' = i$ And I'm not sure how to proceed from here. Thanks for your help!
2020/06/08
[ "https://math.stackexchange.com/questions/3711165", "https://math.stackexchange.com", "https://math.stackexchange.com/users/414214/" ]
Let $x\_n$ be a sequence of points of the metric space, converging to a point $x$. By definition of converging sequence, that means that for every $\epsilon$ you fixed, greater than $0$, you can find a positive integer $N\_{\epsilon}$ such that $d(x\_n,x)<\epsilon$ for all indexes $n$ greater than $N\_{\epsilon}$. That is, the distance of $x\_n$ from the limit point $x$ is eventually smaller than $\epsilon$. If you choose $\epsilon$ smaller that $1$, this means that you can find $N\_1$ such that $d(x\_n,x)$ is smaller than $1$ for all indexes $n$ greater than $N\_1$. As you said, in the discrete metric, two distinct points have distance $=1$. Therefore, having distance smaller than $1$ is equivalent to being the same point. This means that, for $n$ big enough, the distance between the $n$-th term of the sequence and the limit point $x$ will be smaller than $1$, that in discrete metric is equivalent to say that for $n$ big enough$, the $n$-th term of the sequence and the limit point will be the same point.
Dude, as u said earlier $x\_n$ converging to $x$. Now in discrete metric (or in any metric) $d(x,y)=0$ iff $x=y$ hence now for all $n\geq N$ $d(x\_{n},x)<1/2$ so in this discrete metric $d(x,y)=1$ or $0$ so $d(x\_n,x)=0$ so $x\_n=x$ for all $n\geq N$
31,707,629
The following code was taken from an [Arduino tutorial on smoothing](http://playground.arduino.cc/Main/Smooth): ``` int smooth(int data, float filterVal, float smoothedVal) { if (filterVal > 1) { filterVal = .99; } else if (filterVal <= 0) { filterVal = 0; } smoothedVal = (data * (1 - filterVal)) + (smoothedVal * filterVal); return (int)smoothedVal; } ``` The following statement, took from the same tutorial, got me thinking: > > This function can easily be rewritten with all-integer math, if you need more speed or want to avoid floats. > > > Fact is I do want to avoid floats and increase speed, but I wonder: how to convert this to integer arithmetic? Bit-banging solutions are a bonus ;o)
2015/07/29
[ "https://Stackoverflow.com/questions/31707629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401828/" ]
A simple technique is scaling up by multiplying the input value with for example `10000` and putting that result in an `int`, do the calculations in `int`, and then scale the output back into a `float` by dividing with the same factor. In your function you then also need scale up everything with that same factor. The choice of factor depends on the possible ranges of the values; you want to avoid overflow at the high end, and inaccuracy at the low end. If you think about it, the factor determines where you put the decimal point: fixed point, instead of floating point. The factor can be anything, it does not have to be `100`, `1000`, and so on, but `627` is fine too. If you go down this route, you want to convert as much of your code to `int`, because the conversions described above of course also take time. To illustrate my point, the following could be it: ``` #define FACTOR 10000 // Example value. int smooth(int data, int filterVal, int smoothedVal) { if (filterVal > FACTOR) { filterVal = FACTOR - 100; } else if (filterVal <= 0) { filterVal = 0; } smoothedVal = (data * (FACTOR - filterVal)) + (smoothedVal * filterVal); return smoothedVal; } ``` You may need/want to check for overflow, ...
``` // ------------------------------------------------------------------ // SMOOTHING WITH INTEGER VARIABLES (CSHARP) // ------------------------------------------------------------------ Int32 Storage; Int32 SmoothingINT(Int32 NewValue, Int32 Divisor) { Int32 AvgValue; // ------------------------- Compute the output averaged value AvgValue = Storage / Divisor; // ------------------------- Add to storage the delta (New - Old) Storage += NewValue - AvgValue; // ------------------------- return AvgValue; } ``` Or ``` ' ------------------------------------------------------------------- ' SMOOTHING WITH INTEGER VARIABLES (VbNet) ' ------------------------------------------------------------------- Function SmoothingINT(ByVal NewValue As Int32, ByVal Divisor Int32) As Int32 Dim AvgValue As Int32 Static Storage As Int32 ' -------------------------- Compute the output averaged value AvgValue = Storage \ Divisor ' -------------------------- Add to storage the delta (New - Old) Storage += NewValue - AvgValue ' -------------------------- Return AvgValue End Function ```
18,371,653
``` class switch1 { public static void main(String args[]) { int a = 10; switch(a) { default: System.out.println("Default"); case -1: System.out.println("-1"); } } } ``` I understand that this program will execute both "default" and "case -1" statements as break is not specified after the matching condition (in this case after "default"). But what I fail to understand is a) why is `break` needed in a `switch` statement? b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1")) if all it does is matching?
2013/08/22
[ "https://Stackoverflow.com/questions/18371653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2532299/" ]
As for a., requiring the use of `break` allows shorthand notation where common code can be placed at the bottom block. This may make code more readable in some cases. See "[Switch statement fallthrough in C#?](https://stackoverflow.com/questions/174155/switch-statement-fallthrough-in-c?lq=1)" for more information on fallthrough. As for b., since it matches the `default` case, that line is executed. Because no `break` is present in that block, the next line is also executed regardless of a match. Try ``` switch (a) { case 10: System.out.println("This is 10."); case 9 : System.out.println("This is 9."); break; case 8 : System.out.println("This is 8."); break; default: System.out.println("Default"); } ``` Because there is no break in the matching case, the output is ``` This is 10. This is 9. ``` Compare this with setting `a` to 11, 9, or 8.
a) Why fall-through / required break in switch? The fall-through behavior is useful in some cases, but the problem is that it's extra work in the common case. Therefore it's reasonable to expect that the "break" keyword would not be required in a more modern language So why is it there? To match the behavior of C++ (dominant language at the time Java was designed), which again matches the behavior of C (dominant language at the time C++ was designed). As for C, it (and B and BCPL, its predecessors) usually looks the way it does to make it easier to build an efficient compiler. Basically the way the switch statement works is the natural way to implement it in assembler. b) The way it behaves follows logically from the decision to use fall-through.
18,371,653
``` class switch1 { public static void main(String args[]) { int a = 10; switch(a) { default: System.out.println("Default"); case -1: System.out.println("-1"); } } } ``` I understand that this program will execute both "default" and "case -1" statements as break is not specified after the matching condition (in this case after "default"). But what I fail to understand is a) why is `break` needed in a `switch` statement? b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1")) if all it does is matching?
2013/08/22
[ "https://Stackoverflow.com/questions/18371653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2532299/" ]
> > a) why does a switch statement relies heavily on a break statement to achieve its purpose ? > > > Because that's the way they defined it. It's copied from C. Pascal doesn't have fall-through, so it doesn't have break either. It also has case ranges, which Java lacks. Languages are allowed to be different. Or the same. > > b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1")) > > > Because that's the way they defined it, with fall-through if you don't put a break. > > if all it does is matching ? > > > I don't understand the question. It doesn't do matching. It does an indexed jump to the relevant case, and falls through to the next statement if you don't put a break.
a) Why fall-through / required break in switch? The fall-through behavior is useful in some cases, but the problem is that it's extra work in the common case. Therefore it's reasonable to expect that the "break" keyword would not be required in a more modern language So why is it there? To match the behavior of C++ (dominant language at the time Java was designed), which again matches the behavior of C (dominant language at the time C++ was designed). As for C, it (and B and BCPL, its predecessors) usually looks the way it does to make it easier to build an efficient compiler. Basically the way the switch statement works is the natural way to implement it in assembler. b) The way it behaves follows logically from the decision to use fall-through.
18,371,653
``` class switch1 { public static void main(String args[]) { int a = 10; switch(a) { default: System.out.println("Default"); case -1: System.out.println("-1"); } } } ``` I understand that this program will execute both "default" and "case -1" statements as break is not specified after the matching condition (in this case after "default"). But what I fail to understand is a) why is `break` needed in a `switch` statement? b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1")) if all it does is matching?
2013/08/22
[ "https://Stackoverflow.com/questions/18371653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2532299/" ]
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. check this documentation : <http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html>
**In Switch case the point of interest is the break statement.** > > Each break statement terminates the enclosing switch statement. > Control flow continues with the first statement following the switch > block. The break statements are necessary because without them, > statements in switch blocks fall through: All statements after the > matching case label are executed in sequence, regardless of the > expression of subsequent case labels, until a break statement is > encountered. > > > The program SwitchDemoFallThrough shows statements in a switch block that fall through. The program displays the month corresponding to the integer month and the months that follow in the year: public class SwitchDemoFallThrough { ``` public static void main(String[] args) { java.util.ArrayList<String> futureMonths = new java.util.ArrayList<String>(); int month = 8; switch (month) { case 1: futureMonths.add("January"); case 2: futureMonths.add("February"); case 3: futureMonths.add("March"); case 4: futureMonths.add("April"); case 5: futureMonths.add("May"); case 6: futureMonths.add("June"); case 7: futureMonths.add("July"); case 8: futureMonths.add("August"); case 9: futureMonths.add("September"); case 10: futureMonths.add("October"); case 11: futureMonths.add("November"); case 12: futureMonths.add("December"); break; default: break; } if (futureMonths.isEmpty()) { System.out.println("Invalid month number"); } else { for (String monthName : futureMonths) { System.out.println(monthName); } } } ``` } This is the output from the code: August September October November December Technically, the final break is not required because flow falls out of the switch statement. Using a break is recommended so that modifying the code is easier and less error prone. The default section handles all values that are not explicitly handled by one of the case sections. Look Here for complete information about [switch](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html)
18,371,653
``` class switch1 { public static void main(String args[]) { int a = 10; switch(a) { default: System.out.println("Default"); case -1: System.out.println("-1"); } } } ``` I understand that this program will execute both "default" and "case -1" statements as break is not specified after the matching condition (in this case after "default"). But what I fail to understand is a) why is `break` needed in a `switch` statement? b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1")) if all it does is matching?
2013/08/22
[ "https://Stackoverflow.com/questions/18371653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2532299/" ]
Sometimes you need multiple cases to execute the same function. For example, I am letting a user specify either mode 1 or mode 32 to represent 32-bit mode, and mode 2 or mode 64 for 64-bit mode. ``` switch (input) { case 1: case 32: /* Do 32-bit related code */ break; case 2: case 64: /* Do 64-bit related code */ break; default: System.out.println("Invalid input"); } ``` This is why breaks are important. They tell the switch statement when to stop executing code for a given scenario. Additionally, the default is generally used for when the switch does not match ANY case.
`switch` statements without `break`s let you do things like this: ``` // Compute the most significant bit set in a number from 0 to 7 int topBit = -1; switch(n) { case 0: topBit = 0; break; case 1: topBit = 1; break; case 2: case 3: topBit = 2; break; case 4: case 5: case 6: case 7: topBit = 3; break; } ``` Essentially, it lets you create a set of labels, and have a condition at the top to let you jump to the initial label once. After that, the execution continues until a `break`, or reaching the end of the `switch`. This technique is old - it has been around since the assembly times, and by virtue of being included in C has made its way into Java and several other languages.
18,371,653
``` class switch1 { public static void main(String args[]) { int a = 10; switch(a) { default: System.out.println("Default"); case -1: System.out.println("-1"); } } } ``` I understand that this program will execute both "default" and "case -1" statements as break is not specified after the matching condition (in this case after "default"). But what I fail to understand is a) why is `break` needed in a `switch` statement? b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1")) if all it does is matching?
2013/08/22
[ "https://Stackoverflow.com/questions/18371653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2532299/" ]
Sometimes you need multiple cases to execute the same function. For example, I am letting a user specify either mode 1 or mode 32 to represent 32-bit mode, and mode 2 or mode 64 for 64-bit mode. ``` switch (input) { case 1: case 32: /* Do 32-bit related code */ break; case 2: case 64: /* Do 64-bit related code */ break; default: System.out.println("Invalid input"); } ``` This is why breaks are important. They tell the switch statement when to stop executing code for a given scenario. Additionally, the default is generally used for when the switch does not match ANY case.
**In Switch case the point of interest is the break statement.** > > Each break statement terminates the enclosing switch statement. > Control flow continues with the first statement following the switch > block. The break statements are necessary because without them, > statements in switch blocks fall through: All statements after the > matching case label are executed in sequence, regardless of the > expression of subsequent case labels, until a break statement is > encountered. > > > The program SwitchDemoFallThrough shows statements in a switch block that fall through. The program displays the month corresponding to the integer month and the months that follow in the year: public class SwitchDemoFallThrough { ``` public static void main(String[] args) { java.util.ArrayList<String> futureMonths = new java.util.ArrayList<String>(); int month = 8; switch (month) { case 1: futureMonths.add("January"); case 2: futureMonths.add("February"); case 3: futureMonths.add("March"); case 4: futureMonths.add("April"); case 5: futureMonths.add("May"); case 6: futureMonths.add("June"); case 7: futureMonths.add("July"); case 8: futureMonths.add("August"); case 9: futureMonths.add("September"); case 10: futureMonths.add("October"); case 11: futureMonths.add("November"); case 12: futureMonths.add("December"); break; default: break; } if (futureMonths.isEmpty()) { System.out.println("Invalid month number"); } else { for (String monthName : futureMonths) { System.out.println(monthName); } } } ``` } This is the output from the code: August September October November December Technically, the final break is not required because flow falls out of the switch statement. Using a break is recommended so that modifying the code is easier and less error prone. The default section handles all values that are not explicitly handled by one of the case sections. Look Here for complete information about [switch](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html)
18,371,653
``` class switch1 { public static void main(String args[]) { int a = 10; switch(a) { default: System.out.println("Default"); case -1: System.out.println("-1"); } } } ``` I understand that this program will execute both "default" and "case -1" statements as break is not specified after the matching condition (in this case after "default"). But what I fail to understand is a) why is `break` needed in a `switch` statement? b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1")) if all it does is matching?
2013/08/22
[ "https://Stackoverflow.com/questions/18371653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2532299/" ]
Sometimes you need multiple cases to execute the same function. For example, I am letting a user specify either mode 1 or mode 32 to represent 32-bit mode, and mode 2 or mode 64 for 64-bit mode. ``` switch (input) { case 1: case 32: /* Do 32-bit related code */ break; case 2: case 64: /* Do 64-bit related code */ break; default: System.out.println("Invalid input"); } ``` This is why breaks are important. They tell the switch statement when to stop executing code for a given scenario. Additionally, the default is generally used for when the switch does not match ANY case.
From the [Java Language Specification section on the `break` statement](http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.15): > > A break statement transfers control out of an enclosing statement. > > > and... > > a break statement ... always completes abruptly > > > a) It simply allows transfer of control out of the case statement. b) The reason why it executes the conditions that aren't what you would expect to be matching is because there are particular conditions where falling through case statements would be considered valid (Taken from [The Java Tutorials](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html)): ``` List<String> futureMonths = new ArrayList<String>(); int month = 8; switch (month) { case 1: futureMonths.add("January"); case 2: futureMonths.add("February"); case 3: futureMonths.add("March"); case 4: futureMonths.add("April"); case 5: futureMonths.add("May"); case 6: futureMonths.add("June"); case 7: futureMonths.add("July"); case 8: futureMonths.add("August"); case 9: futureMonths.add("September"); case 10: futureMonths.add("October"); case 11: futureMonths.add("November"); case 12: futureMonths.add("December"); break; default: break; } for (String monthName : futureMonths) { System.out.println(monthName); } ``` Which outputs: > > August > > > September > > > October > > > November > > > December > > >
18,371,653
``` class switch1 { public static void main(String args[]) { int a = 10; switch(a) { default: System.out.println("Default"); case -1: System.out.println("-1"); } } } ``` I understand that this program will execute both "default" and "case -1" statements as break is not specified after the matching condition (in this case after "default"). But what I fail to understand is a) why is `break` needed in a `switch` statement? b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1")) if all it does is matching?
2013/08/22
[ "https://Stackoverflow.com/questions/18371653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2532299/" ]
`switch` statements without `break`s let you do things like this: ``` // Compute the most significant bit set in a number from 0 to 7 int topBit = -1; switch(n) { case 0: topBit = 0; break; case 1: topBit = 1; break; case 2: case 3: topBit = 2; break; case 4: case 5: case 6: case 7: topBit = 3; break; } ``` Essentially, it lets you create a set of labels, and have a condition at the top to let you jump to the initial label once. After that, the execution continues until a `break`, or reaching the end of the `switch`. This technique is old - it has been around since the assembly times, and by virtue of being included in C has made its way into Java and several other languages.
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. check this documentation : <http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html>
18,371,653
``` class switch1 { public static void main(String args[]) { int a = 10; switch(a) { default: System.out.println("Default"); case -1: System.out.println("-1"); } } } ``` I understand that this program will execute both "default" and "case -1" statements as break is not specified after the matching condition (in this case after "default"). But what I fail to understand is a) why is `break` needed in a `switch` statement? b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1")) if all it does is matching?
2013/08/22
[ "https://Stackoverflow.com/questions/18371653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2532299/" ]
`switch` statements without `break`s let you do things like this: ``` // Compute the most significant bit set in a number from 0 to 7 int topBit = -1; switch(n) { case 0: topBit = 0; break; case 1: topBit = 1; break; case 2: case 3: topBit = 2; break; case 4: case 5: case 6: case 7: topBit = 3; break; } ``` Essentially, it lets you create a set of labels, and have a condition at the top to let you jump to the initial label once. After that, the execution continues until a `break`, or reaching the end of the `switch`. This technique is old - it has been around since the assembly times, and by virtue of being included in C has made its way into Java and several other languages.
As for a., requiring the use of `break` allows shorthand notation where common code can be placed at the bottom block. This may make code more readable in some cases. See "[Switch statement fallthrough in C#?](https://stackoverflow.com/questions/174155/switch-statement-fallthrough-in-c?lq=1)" for more information on fallthrough. As for b., since it matches the `default` case, that line is executed. Because no `break` is present in that block, the next line is also executed regardless of a match. Try ``` switch (a) { case 10: System.out.println("This is 10."); case 9 : System.out.println("This is 9."); break; case 8 : System.out.println("This is 8."); break; default: System.out.println("Default"); } ``` Because there is no break in the matching case, the output is ``` This is 10. This is 9. ``` Compare this with setting `a` to 11, 9, or 8.
18,371,653
``` class switch1 { public static void main(String args[]) { int a = 10; switch(a) { default: System.out.println("Default"); case -1: System.out.println("-1"); } } } ``` I understand that this program will execute both "default" and "case -1" statements as break is not specified after the matching condition (in this case after "default"). But what I fail to understand is a) why is `break` needed in a `switch` statement? b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1")) if all it does is matching?
2013/08/22
[ "https://Stackoverflow.com/questions/18371653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2532299/" ]
`switch` statements without `break`s let you do things like this: ``` // Compute the most significant bit set in a number from 0 to 7 int topBit = -1; switch(n) { case 0: topBit = 0; break; case 1: topBit = 1; break; case 2: case 3: topBit = 2; break; case 4: case 5: case 6: case 7: topBit = 3; break; } ``` Essentially, it lets you create a set of labels, and have a condition at the top to let you jump to the initial label once. After that, the execution continues until a `break`, or reaching the end of the `switch`. This technique is old - it has been around since the assembly times, and by virtue of being included in C has made its way into Java and several other languages.
**In Switch case the point of interest is the break statement.** > > Each break statement terminates the enclosing switch statement. > Control flow continues with the first statement following the switch > block. The break statements are necessary because without them, > statements in switch blocks fall through: All statements after the > matching case label are executed in sequence, regardless of the > expression of subsequent case labels, until a break statement is > encountered. > > > The program SwitchDemoFallThrough shows statements in a switch block that fall through. The program displays the month corresponding to the integer month and the months that follow in the year: public class SwitchDemoFallThrough { ``` public static void main(String[] args) { java.util.ArrayList<String> futureMonths = new java.util.ArrayList<String>(); int month = 8; switch (month) { case 1: futureMonths.add("January"); case 2: futureMonths.add("February"); case 3: futureMonths.add("March"); case 4: futureMonths.add("April"); case 5: futureMonths.add("May"); case 6: futureMonths.add("June"); case 7: futureMonths.add("July"); case 8: futureMonths.add("August"); case 9: futureMonths.add("September"); case 10: futureMonths.add("October"); case 11: futureMonths.add("November"); case 12: futureMonths.add("December"); break; default: break; } if (futureMonths.isEmpty()) { System.out.println("Invalid month number"); } else { for (String monthName : futureMonths) { System.out.println(monthName); } } } ``` } This is the output from the code: August September October November December Technically, the final break is not required because flow falls out of the switch statement. Using a break is recommended so that modifying the code is easier and less error prone. The default section handles all values that are not explicitly handled by one of the case sections. Look Here for complete information about [switch](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html)
18,371,653
``` class switch1 { public static void main(String args[]) { int a = 10; switch(a) { default: System.out.println("Default"); case -1: System.out.println("-1"); } } } ``` I understand that this program will execute both "default" and "case -1" statements as break is not specified after the matching condition (in this case after "default"). But what I fail to understand is a) why is `break` needed in a `switch` statement? b) why does it even execute the invalid matching conditions' statements (i.e executing "case -1")) if all it does is matching?
2013/08/22
[ "https://Stackoverflow.com/questions/18371653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2532299/" ]
`switch` statements without `break`s let you do things like this: ``` // Compute the most significant bit set in a number from 0 to 7 int topBit = -1; switch(n) { case 0: topBit = 0; break; case 1: topBit = 1; break; case 2: case 3: topBit = 2; break; case 4: case 5: case 6: case 7: topBit = 3; break; } ``` Essentially, it lets you create a set of labels, and have a condition at the top to let you jump to the initial label once. After that, the execution continues until a `break`, or reaching the end of the `switch`. This technique is old - it has been around since the assembly times, and by virtue of being included in C has made its way into Java and several other languages.
If you add break to a loop, it cancels out of the loop. so for a switch statement it goes to the correct case and once it is there it carries out the code until the `break` where it will then exit the switch statemnt. If you removed the break it would carry on to the next `case` and until is sees a break. If there are no `break;` the code will crash. So basically it separates different cases
19,849,858
I'm working on a program that is supposed to sort a vector of ints and then get passed to a recursive function to remove any duplicates by having an element check it's neighbor, and remove it if they're the same. Here is my code: ``` #include<iostream> #include<vector> #include<algorithm> using namespace std; void checkNum(vector<int> &v, int n) { int i = n; if (v[i] == '\0') { cout << "No duplicates found." << endl; } if (v[i]==v[i+1]) { v.erase(v.begin()+i); /*return 1 + */checkNum(v, n); } else { n++; /*return 0 + */checkNum(v, n); } int k; cout << "Sorted values, no duplicates: " << endl; for (k=0; k< v.size(); k++) cout << v[k] << " "; //return 0; } int main() { vector<int> numbers; cout << "Please enter numbers, 0 to quit: " << endl; bool more = true; while (more) { int num; cin >> num; if (num == 0) more = false; else numbers.push_back(num); } sort(numbers.begin(),numbers.end()); cout << "The sorted values are: " << endl; int i; for (i = 0; i < numbers.size(); i++) cout << numbers[i] << " "; checkNum(numbers, 0); system("pause"); return 0; } ``` My issue here is that when it runs, I get the following error after entering values: ``` Debug Assertion Failed! Program: C:\Windows\system32\MSVCP110D.dll File: d:\program files (x86)\microsoft visual studio 11.0\vc\include\vector Line: 1140 Expression: vector subscript out of range ``` It also prints multiple times when it works but I'm not terribly concerned about that. Where's the bug? Can anybody help me out? ***UPDATE:*** Here is the code that I am CURRENTLY running with: ``` #include<iostream> #include<vector> #include<algorithm> using namespace std; int checkNum(vector<int> &v, int n) { int i = n; if (i == v.size()) { cout << "No duplicates found." << endl; return 0; } if (v[i]==v[i+1]) { v.erase(v.begin()+i); return checkNum(v, n); } else { n++; return checkNum(v, n); } int k; cout << "Sorted values, no duplicates: " << endl; for (k=0; k< v.size(); k++) cout << v[k] << " " << endl; return 0; } int main() { vector<int> numbers; cout << "Please enter numbers, 0 to quit: " << endl; bool more = true; while (more) { int num; cin >> num; if (num == 0) more = false; else numbers.push_back(num); } sort(numbers.begin(),numbers.end()); cout << "The sorted values are: " << endl; int i; for (i = 0; i < numbers.size(); i++) cout << numbers[i] << " "; checkNum(numbers, 0); system("pause"); return 0; } ``` I ran with a debugger, everything was fine, was removing duplicates like it was no big deal, until the size of n/i reached the size of the list. Then I get that error message listed above. How do I fix that?
2013/11/08
[ "https://Stackoverflow.com/questions/19849858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2320914/" ]
You have commented out `return`s completely except the recursive call. The functions go on although it should not. You should use `return checkNum(v, n);` on those lines. Edit: Your code is completely flawed and won't do what you want. Here is a quick ugly code of how you should be doing it while you stick to limitation of probably homework: ``` #include<iostream> #include<vector> #include<algorithm> using namespace std; void checkNum(vector<int> &v, vector<int>::iterator& it) { if (it == v.end() - 1) //last element { cout << "After duplicate removal pass:" << endl; for (int k=0; k< v.size(); k++) cout << v[k] << " "; } else if (*it == *(it + 1)) //next element is equal to current one, erase current one { v.erase(it); //using 'it' after this line is normally not a good practice, // but we know the vector is stored sequentially and 'it' will point to another element because above we checked if this is the last element or not. return checkNum(v, it); } else //next element is not the same as this one { ++it; return checkNum(v, it); } } int main() { vector<int> numbers; cout << "Please enter numbers, 0 to quit: " << endl; bool more = true; while (more) { int num; cin >> num; if (num == 0) more = false; else numbers.push_back(num); } sort(numbers.begin(),numbers.end()); cout << "The sorted values are: " << endl; int i; for (i = 0; i < numbers.size(); i++) cout << numbers[i] << " "; vector<int>::iterator elementToStart = numbers.begin(); checkNum(numbers, elementToStart); system("pause"); return 0; } ```
Ok got it to work. You need to add a return after the line, cout << "No duplicates found" like: ``` if (i == v.size()) { cout << "No duplicates found." << endl; return; // add this return } ``` The reason is that by the time the recursive call reaches this point in the program, you are done checking for duplicates. Your recursive function should wrap things up at this point. Without the return you keep increasing n (below at the line with n++): ``` else { n++; /*return 0 + */checkNum(v, n); } ``` but then n is larger than the size of your vector v, causing the error.
72,283,127
I am implementing a variant of the the ants algorithm in a discrete 2d grid. The design is similar to how Reinforcement Learning environments work, where there is a `state` variable, and `action(s)` to transition the environment from one state to another. The state of the environment is the integer values of how many times each one of the four surrounding cells has been visited, for each ant. For example with 2 ants: ``` >>> state array([[18, 5, 0, 21], # ant 0: right (visited 18 times), up (visited 5 times), left (not visited), down (visited 21 times) [ 6, 32, 6, 12]]) ``` Now, **I want the ants to go towards the least visited cell(s), with equal probabilities**. So ant 0 will choose to go left with probability 1, and ant 1 will choose between right and left with equal probability. I have been accomplishing this using a for loop over the agents, like so: ``` def choose_action(self, state: np.ndarray) -> np.ndarray: """ Choose ants actions based on the state of the environment. :param state: the integer values of the four surrounding cells for each ant (n_ants x 4) :return: actions' indices for ants """ actions = np.zeros(self.n_ants, dtype=int) for i in range(self.n_ants): state[i] = state[i] == state[i].min() p = state[i] / state[i].sum() actions[i] = np.random.choice(self.n_actions, p=p) return actions ``` But is there a way to do this without a for loop? Note: actions indices correspond to the order of the directions in the `state` variable. Meaning that action index 0 moves the agent to the right, and so on.
2022/05/18
[ "https://Stackoverflow.com/questions/72283127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13683123/" ]
In the case *you only need the inputs* that were provided to `step 1 [setup]` to be passed to `step 3 [finish]` you should be able to access the *Execution Input* via the Context Object as described in my answer here: <https://stackoverflow.com/a/71230038/4526019> --- If `step 3 [finish]` needs the input to `step 1 [setup]` *AND* the output from `step 2 [child_sfn]` you can use `ResultPath` to avoid clobbering the payload. I'll try and show what I mean with a SFN with a single state: ⚠️ *Note: `Pass` types are obviously different than `Task` types but the premise is the same* Parent SFN Input: ```json { "a": { "value": 1 }, "b": { "value": 2 }, "c": { "value": 3 } } ``` SFN Defintion where only the `a` and `b` keys from the input should be passed, but *NOT* `c`. The "built-up" state can be preserved by creating a new key that can be safely/predictably appended to by using `ResultPath` and can be consumed by some downstream task. ```json { "StartAt": "Step1", "States": { "Step1": { "Type": "Pass", "Parameters": { "params.$": "$['a', 'b']" }, "ResultPath": "$.stateOutput.Step1", "End": true } } } ``` Output (with preserved input and "tranformed" output created by `Step1`) ```json { "a": { "v": 1 }, "b": { "v": 2 }, "c": { "v": 3 }, "stateOutput": { "Step1": { "params": { "a": { "v": 1 }, "b": { "v": 2 } } } } } ``` Basically, using `OutputPath` in `StepX` is gonna wipe out all the input that may have been built up by all the previous steps. [example from docs](https://docs.aws.amazon.com/step-functions/latest/dg/input-output-example.html) --- The workflow that I've found most useful, although extremely tedious, is to manually write out the json before and each "phase"(?) when defining the state and making any notes along the way: * **phase\_0**: output put from previous state ```json { "a": { "value": 1 }, "b": { "value": 2 }, "c": { "value": 3 } } ``` + **phase\_1**: using `InputPath`? If InputPath is defined, only send part of **phase\_0**. This basically throws everything else away. ```json { "//": "json object after InputPath" } ``` - **phase\_2**: redefine the `Payload` sent to the task via `Parameters` The object definition for what is actually sent to your lambda ```json { "//": "json object sent to the task after defining Payload.Parameters" } ``` - **phase\_3**: raw output from task i.e. the response from lambda ```json { "//": "json object returned from lambda" } ``` + **phase\_4**: optionally customize output from phase\_3 with `ResultSelector` ```json { "//": "transform the result returned by lambda (similar to Parameters.Payload)" } ``` * **phase\_5**: optionally set `ResultPath`? inserts the the object of **phase\_3** into the object of **phase\_1** at the specified path ```json { "//": "roughly object in phase_1 updated with object in phase_4" } ``` * **phase\_6**: optionally set `OutputPath` throw away everything except `OutputPath` and feed it to the next state ```json { "//": "this is what will be the input to the next state" } ``` Hopefully that helps and doesn't cause more confusion. I know I've spent too many hours trying to decipher the docs and map that to my own use cases
Not exactly sure why, but using `ResultPath` in both my step1 and step2 worked. So something like ``` stateMachine: { StartAt: 'setup', States: { setup: { Type: 'Task', TimeoutSeconds: 3600, Retry: [ { ErrorEquals: ['States.ALL'], MaxAttempts: 2, }, ], ResultPath: '$.data', Resource: setupFn, Next: 'child_sfn', }, child_sfn: { Type: 'Task', TimeoutSeconds: 3600, Retry: [ { ErrorEquals: ['States.ALL'], MaxAttempts: 2, }, ], Catch: [ { ErrorEquals: ['States.ALL'], Next: 'sfn_catch', }, ], Parameters: { StateMachineArn: 'mySfnArn', Input: { 'myInput1.$': '$.myInput1', }, }, ResultPath: '$.sfnOutput', Resource: 'arn:aws:states:::states:startExecution.sync', Next: 'finish', }, finish: { Type: 'Task', TimeoutSeconds: 3600, Retry: [ { ErrorEquals: ['States.ALL'], MaxAttempts: 2, }, ], Resource: finishFn, End: true, }, sfn_catch: { Type: 'Task', TimeoutSeconds: 3600, Resource: stepFunctionCatch, End: true, }, }, } ```
15,186,541
I was asked this question in an interview recently. > > Given an input file, a regex and an output file. Read the input file, match each line to the regex and write the matching lines to an output file. > > > I came up with the rough scheme of using a BufferedReader chained to a FileReader (to optimize Reads from the disk). I used a similar scheme for writing. > > The interviewer then said that this process takes 3 seconds to read a line from the file, 1 second to compare the regex with the line and another 5 seconds to write back. so it takes a total of 9 seconds per line. How can we improve this? > > > I suggested reading the entire file at once, processing it and writing the entire output file at once. However, I was told that won't help (Writing 1 line = 5 seconds, writing 2 lines = 10 seconds) . > > The interviewer further said that this is due to a hardware/ hard drive limitation. I was asked how I can improve my code to reduce the total seconds (currently 9 ) per line? > > > I could only think of buffered reading/ writing and could not find much on SO as well. Any thoughts ?
2013/03/03
[ "https://Stackoverflow.com/questions/15186541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2107162/" ]
I think that the interviewer was looking for a solution that performs reading/regex checking in parallel with writing the output. If you set up a work queue that you fill asynchronously by reading and filtering, and put writing in a separate thread, then the combined process would take five seconds per line, starting with the second line. The assumption here is that reading, parsing, and writing can happen independently of each other. In this case, you can be reading line 2 while line 1 is being written: you need only four seconds to read and apply your regex, and you've got a whole five seconds before the writer is ready for the second line. The writing remains your bottleneck, but the whole process gets sped up by some 44%, which isn't bad.
Well since the time for a read is fixed and the time for a write is fixed, the only option you have in this case is to change the nature of the regex bit. You could write code to apply the regex test quickly without the overhead of all the clever things that regex can do. If on the other hand the problem is that each IO request takes several seconds to be executed, but the limitation is not the actual drive, then have several readers reading simultaneously.
15,186,541
I was asked this question in an interview recently. > > Given an input file, a regex and an output file. Read the input file, match each line to the regex and write the matching lines to an output file. > > > I came up with the rough scheme of using a BufferedReader chained to a FileReader (to optimize Reads from the disk). I used a similar scheme for writing. > > The interviewer then said that this process takes 3 seconds to read a line from the file, 1 second to compare the regex with the line and another 5 seconds to write back. so it takes a total of 9 seconds per line. How can we improve this? > > > I suggested reading the entire file at once, processing it and writing the entire output file at once. However, I was told that won't help (Writing 1 line = 5 seconds, writing 2 lines = 10 seconds) . > > The interviewer further said that this is due to a hardware/ hard drive limitation. I was asked how I can improve my code to reduce the total seconds (currently 9 ) per line? > > > I could only think of buffered reading/ writing and could not find much on SO as well. Any thoughts ?
2013/03/03
[ "https://Stackoverflow.com/questions/15186541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2107162/" ]
I think that the interviewer was looking for a solution that performs reading/regex checking in parallel with writing the output. If you set up a work queue that you fill asynchronously by reading and filtering, and put writing in a separate thread, then the combined process would take five seconds per line, starting with the second line. The assumption here is that reading, parsing, and writing can happen independently of each other. In this case, you can be reading line 2 while line 1 is being written: you need only four seconds to read and apply your regex, and you've got a whole five seconds before the writer is ready for the second line. The writing remains your bottleneck, but the whole process gets sped up by some 44%, which isn't bad.
Tough question, since we don't no much about the system. My guess would be using threads/ async processing. Use one Thread to read and one to process an two or more for writing, thus reducing the time spent for IO Wait. Let my try to convert this into an ASCII Chart: * R/r means reading (3 Sec) * P/p means processing (1 Sec) * W/w means writing (5 Sec) upper case letter mark the start, lower case letter mark continuing work. A ":" means thread is idle ``` Thread 1: RrrRrrRrrRrrRr Thread 2: ...P..P..P..P. Thread 3: ....Wwwww Thread 4: .......Wwwww ``` With this setup the first batch is written back after 9 Seconds (not much to do here) but the second one completes after 12 Seconds. Single threaded the second one needs 18 Seconds total
303,130
I have a form on my wordpress page template -- ``` <form id="pollyform" method="post"> <textarea name="pollytext" id="text"></textarea> <input type="submit" id="savetext" name="savetext" value="save-text" /> </form> ``` I am trying to get the data from my textarea field and send to my script -- ``` $(document).ready(function() { $('#savetext').click(function(e){ // prevent the form from submitting normally var txt = $("#text").val(); $.ajax ({ data: { action: 'polly_pros', pollytext: txt }, type: 'post', url: polpro.ajax_url, success: function(data) { console.log(data); //should print out the name since you sent it along }, error: function() { console.log("Error"); } }); }); return false; }); ``` In my functions file I have my scripts setup to work - ``` add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' ); function ajax_test_enqueue_scripts() { wp_enqueue_script( 'pol', get_stylesheet_directory_uri() . '/pol.js', array(), '1.0.0', true ); wp_localize_script( 'pol', 'polpro', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )); } ``` however my php function isn't working -- ``` add_action('wp_ajax_polly_pros', 'polly_process'); function polly_process() { // use \Aws\Polly\PollyClient; // this was moved to before get_header in my template page where my form is. //require '/aws-autoloader.php'; // this was moved to before get_header in my template page where my form is. $the_text = $_POST['pollytext']; if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { //echo $the_text; $voice_id = "Joanna"; $text = $the_text; $rate = "medium"; $is_download = false; if(isset($_REQUEST['download']) && $_REQUEST['download']==1){ $is_download=true; } $config = array( 'version' => 'latest', 'region' => 'us-east-1', 'credentials' => [ 'key' => 'keys', 'secret' => 'keys', ] ); $client = new PollyClient($config); $args = array( 'OutputFormat' => 'mp3', 'Text' => "<speak><prosody rate='$rate'>".str_replace("&","&amp;",urldecode ($text))."</prosody></speak>", 'TextType' => 'ssml', 'VoiceId' => $voice_id ); $result = $client->synthesizeSpeech($args); $resultData = $result->get('AudioStream')->getContents(); $size = strlen($resultData); // File size $length = $size; // Content length $start = 0; // Start byte $end = $size - 1; // End byte if(!$is_download) { file_put_contents('test.mp3', $resultData); } else { file_put_contents('test.mp3', $resultData); } } die(); } ``` When I put the php code directly in the same page as my template, it works but only the first time and then I cant update the text and resend the data, etc. If I change my function code to something like this --- ``` function polly_process() { $the_text = $_POST['pollytext']; if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { echo $the_text; } } ``` I can see that its working and the value is echoed. My original polly\_process code I want to use though is giving me this error when submitting the form -- ``` jquery.js:8625 POST /admin-ajax.php 500 () send @ jquery.js:8625 ajax @ jquery.js:8161 (anonymous) @ pol.js:8 dispatch @ jquery.js:4430 r.handle @ jquery.js:4116 pol.js:20 Error ``` when checking the console I can see this is highlighted in jquery.js --- ``` // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); ``` I've checked debug.log and didnt find any relevant errors. So what am I missing? **EDIT** Checking the logs again I see this -- ``` Uncaught Error: Class 'PollyClient' not found ``` The reason though why I have this code -- ``` use \Aws\Polly\PollyClient; require '/aws-autoloader.php'; ``` in my template file before my header is because anywhere else it causes the site to crash. Specifically - ``` use \Aws\Polly\PollyClient; ``` When I have that and my polly\_process function directly in my template it works, but it's not dynamic like I need with the ajax. So how I would be able to use that code with the ajax function?
2018/05/09
[ "https://wordpress.stackexchange.com/questions/303130", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24067/" ]
It's in the post meta table (usually `wp_postmeta`), with the page id in post\_id, meta\_key with `_wp_page_template` and meta\_value with the template file name.
Example select query: ```sql SELECT * FROM wp_postmeta WHERE meta_key = '_wp_page_template' # AND post_id = 50 ``` Example update query: ```sql UPDATE wp_postmeta SET meta_value = 'templates/template-example.php' WHERE meta_key = '_wp_page_template' AND post_id = 50; ```
7,336,667
I've got an extension to this question: [How to deal with Form Collection on Symfony2 Beta?](https://stackoverflow.com/questions/5894570/how-to-deal-with-form-collection-on-symfony2-beta "How to deal with Form Collection on Symfony2 Beta?") - My project is similar, but the objects are nested deeper. I've got Articles which have one or more Content elements, each of which contains one or more Media. The Model and Controllers are working fine so far, but I don't know how to properly represent the nesting in my template. Form/ContentType.php looks all right: ``` class ContentType extends AbstractType { public function buildForm(FormBuilder $builder, array $options) { $builder ->add('headline') ->add('text') ->add('medias', 'collection', array( 'type' => new MediaType(), 'allow_add' => true )) ; } ``` And so far, the form template for creating (or editing) an Article looks like this (almost vanilla auto-generated template): ``` ... <form action="{{ path('article_create') }}" method="post" {{ form_enctype(form) }}> {{ form_widget(form) }} {% for content in form.contents %} {{ form_widget(content) }} {% endfor %} <p> <button type="submit">Create</button> </p> </form> ... ``` How do I access each Content's Media so they get properly associated?
2011/09/07
[ "https://Stackoverflow.com/questions/7336667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468744/" ]
Iterate through all content's media: ``` <form action="{{ path('article_create') }}" method="post" {{ form_enctype(form) }}> {{ form_widget(form) }} {% for content in form.contents %} {% for media in content.medias %} {{ form_widget(media) }} {% endfor %} {% endfor %} <p> <button type="submit">Create</button> </p> </form> ```
``` <form action="{{ path('article_create') }}" method="post" {{ form_enctype(form) }}> {% for media in form.contents.medias.children %} {{ form_widget(media) }} {% endfor %} {{ form_rest(form) }} <p> <button type="submit">Create</button> </p> </form> ```
21,398,869
I have written the following code. The whole thing was working fine until i added the following HTML in my PHP code. ``` echo " <div class='fpd-product' title='$name' data-thumbnail='$base_image_loc'> "; ``` If i remove this HTML(div), it fetches all the record from database and echo them, but if i add this HTML it only prints the last output from the loop. Kindly tell me where i am making mistake. ``` <?php $query ='select * from products ' . 'inner join product_description ' . 'on products.product_id= product_description.product_id'; $query_run= mysql_query($query); while($query_fetch= mysql_fetch_array($query_run)) { $product_id= $query_fetch['product_id']; $price= $query_fetch['retail_price']; $name= $query_fetch['name']; echo $name; //Image Query $image_query= "select * from product_images where product_id=$product_id"; $image_query_run= mysql_query($image_query); $base_image= mysql_fetch_array($image_query_run); $base_image_loc= $base_image['images']; //If i remove this echo it fetches all the records from database and echo them, //otherwise it will only print the last record. echo " <div class='fpd-product' title='$name' data-thumbnail='$base_image_loc'> "; while($image_query_fetch= mysql_fetch_array($image_query_run)) { $image_location= $image_query_fetch['images']; $image_name= $image_query_fetch['name']; } } ?> <img src="images/sweater/basic.png" title="Base" data-parameters='{"x": 332, "y": 311, "colors": "#D5D5D5,#990000,#cccccc", "price": 20}' /> <img src="images/sweater/highlights.png" title="Hightlights" data-parameters='{"x": 332, "y": 311}' /> <img src="images/sweater/shadow.png" title="Shadow" data-parameters='{"x": 332, "y": 309}' /> </div> ``` Thanks Taha
2014/01/28
[ "https://Stackoverflow.com/questions/21398869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2541348/" ]
your echo statement should look like this ``` echo "<div class='fpd-product' title='".$name."' data-thumbnail='".$base_image_loc."'>"; ``` and where is div close? or you can do with html like this ``` <div class='fpd-product' title='<?php echo $name; ?>' data-thumbnail='<?php echo $base_image_loc; ?>'> ``` and close the div after while loop
Change your echo statement ``` echo "<div class='fpd-product' title=".$name." data-thumbnail=".$base_image_loc.">"; ``` and close the div, end of the code ``` echo "</div>"; ```
21,398,869
I have written the following code. The whole thing was working fine until i added the following HTML in my PHP code. ``` echo " <div class='fpd-product' title='$name' data-thumbnail='$base_image_loc'> "; ``` If i remove this HTML(div), it fetches all the record from database and echo them, but if i add this HTML it only prints the last output from the loop. Kindly tell me where i am making mistake. ``` <?php $query ='select * from products ' . 'inner join product_description ' . 'on products.product_id= product_description.product_id'; $query_run= mysql_query($query); while($query_fetch= mysql_fetch_array($query_run)) { $product_id= $query_fetch['product_id']; $price= $query_fetch['retail_price']; $name= $query_fetch['name']; echo $name; //Image Query $image_query= "select * from product_images where product_id=$product_id"; $image_query_run= mysql_query($image_query); $base_image= mysql_fetch_array($image_query_run); $base_image_loc= $base_image['images']; //If i remove this echo it fetches all the records from database and echo them, //otherwise it will only print the last record. echo " <div class='fpd-product' title='$name' data-thumbnail='$base_image_loc'> "; while($image_query_fetch= mysql_fetch_array($image_query_run)) { $image_location= $image_query_fetch['images']; $image_name= $image_query_fetch['name']; } } ?> <img src="images/sweater/basic.png" title="Base" data-parameters='{"x": 332, "y": 311, "colors": "#D5D5D5,#990000,#cccccc", "price": 20}' /> <img src="images/sweater/highlights.png" title="Hightlights" data-parameters='{"x": 332, "y": 311}' /> <img src="images/sweater/shadow.png" title="Shadow" data-parameters='{"x": 332, "y": 309}' /> </div> ``` Thanks Taha
2014/01/28
[ "https://Stackoverflow.com/questions/21398869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2541348/" ]
your echo statement should look like this ``` echo "<div class='fpd-product' title='".$name."' data-thumbnail='".$base_image_loc."'>"; ``` and where is div close? or you can do with html like this ``` <div class='fpd-product' title='<?php echo $name; ?>' data-thumbnail='<?php echo $base_image_loc; ?>'> ``` and close the div after while loop
For debugging such problems, you have to check the HTML source code (rightclick in browser -> view source). If you see all records there, it is a problem purely with HTML; that means you should first use an HTML validator before anything else.
21,398,869
I have written the following code. The whole thing was working fine until i added the following HTML in my PHP code. ``` echo " <div class='fpd-product' title='$name' data-thumbnail='$base_image_loc'> "; ``` If i remove this HTML(div), it fetches all the record from database and echo them, but if i add this HTML it only prints the last output from the loop. Kindly tell me where i am making mistake. ``` <?php $query ='select * from products ' . 'inner join product_description ' . 'on products.product_id= product_description.product_id'; $query_run= mysql_query($query); while($query_fetch= mysql_fetch_array($query_run)) { $product_id= $query_fetch['product_id']; $price= $query_fetch['retail_price']; $name= $query_fetch['name']; echo $name; //Image Query $image_query= "select * from product_images where product_id=$product_id"; $image_query_run= mysql_query($image_query); $base_image= mysql_fetch_array($image_query_run); $base_image_loc= $base_image['images']; //If i remove this echo it fetches all the records from database and echo them, //otherwise it will only print the last record. echo " <div class='fpd-product' title='$name' data-thumbnail='$base_image_loc'> "; while($image_query_fetch= mysql_fetch_array($image_query_run)) { $image_location= $image_query_fetch['images']; $image_name= $image_query_fetch['name']; } } ?> <img src="images/sweater/basic.png" title="Base" data-parameters='{"x": 332, "y": 311, "colors": "#D5D5D5,#990000,#cccccc", "price": 20}' /> <img src="images/sweater/highlights.png" title="Hightlights" data-parameters='{"x": 332, "y": 311}' /> <img src="images/sweater/shadow.png" title="Shadow" data-parameters='{"x": 332, "y": 309}' /> </div> ``` Thanks Taha
2014/01/28
[ "https://Stackoverflow.com/questions/21398869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2541348/" ]
You need a `</div>` here: ``` while($image_query_fetch= mysql_fetch_array($image_query_run)) { $image_location= $image_query_fetch['images']; $image_name= $image_query_fetch['name']; } echo "</div>"; ```
Change your echo statement ``` echo "<div class='fpd-product' title=".$name." data-thumbnail=".$base_image_loc.">"; ``` and close the div, end of the code ``` echo "</div>"; ```
21,398,869
I have written the following code. The whole thing was working fine until i added the following HTML in my PHP code. ``` echo " <div class='fpd-product' title='$name' data-thumbnail='$base_image_loc'> "; ``` If i remove this HTML(div), it fetches all the record from database and echo them, but if i add this HTML it only prints the last output from the loop. Kindly tell me where i am making mistake. ``` <?php $query ='select * from products ' . 'inner join product_description ' . 'on products.product_id= product_description.product_id'; $query_run= mysql_query($query); while($query_fetch= mysql_fetch_array($query_run)) { $product_id= $query_fetch['product_id']; $price= $query_fetch['retail_price']; $name= $query_fetch['name']; echo $name; //Image Query $image_query= "select * from product_images where product_id=$product_id"; $image_query_run= mysql_query($image_query); $base_image= mysql_fetch_array($image_query_run); $base_image_loc= $base_image['images']; //If i remove this echo it fetches all the records from database and echo them, //otherwise it will only print the last record. echo " <div class='fpd-product' title='$name' data-thumbnail='$base_image_loc'> "; while($image_query_fetch= mysql_fetch_array($image_query_run)) { $image_location= $image_query_fetch['images']; $image_name= $image_query_fetch['name']; } } ?> <img src="images/sweater/basic.png" title="Base" data-parameters='{"x": 332, "y": 311, "colors": "#D5D5D5,#990000,#cccccc", "price": 20}' /> <img src="images/sweater/highlights.png" title="Hightlights" data-parameters='{"x": 332, "y": 311}' /> <img src="images/sweater/shadow.png" title="Shadow" data-parameters='{"x": 332, "y": 309}' /> </div> ``` Thanks Taha
2014/01/28
[ "https://Stackoverflow.com/questions/21398869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2541348/" ]
You need a `</div>` here: ``` while($image_query_fetch= mysql_fetch_array($image_query_run)) { $image_location= $image_query_fetch['images']; $image_name= $image_query_fetch['name']; } echo "</div>"; ```
For debugging such problems, you have to check the HTML source code (rightclick in browser -> view source). If you see all records there, it is a problem purely with HTML; that means you should first use an HTML validator before anything else.
35,545,137
``` form: ControlGroup childForm1: ControlGroup childForm2: ControlGroup childForm3: ControlGroup constructor(fb: FormBuilder) { this.form = fb.group({ name: [''], childForm1: fb.group({ child1: [''], child2: [''] }), childForm2: fb.group({ child3: [''], child4: [''] }), childForm3: fb.group({ child5: [''], child6: [''] }) }); } ``` I can get `name` by two ways: ``` console.log(this.form.find('name')); console.log(this.form.controls['name']); ``` But I cannot use similar way to get `child1`. I know a way: ``` for (name in this.childForm1.controls) { if (name === "child1") { console.log(this.childForm1.controls[name]); } } ``` But this still uses `childForm1` in the code. Is it possible using only `form` and `child1` to get it? Thanks
2016/02/22
[ "https://Stackoverflow.com/questions/35545137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2000548/" ]
Before init, I want to share a free tool (chrome app) very useful during this type of works: [DHC Rest Client](https://chrome.google.com/webstore/detail/dhc-rest-client/aejoelaoggembcahagimdiliamlcdmfm?utm_source=chrome-ntp-icon) : with this tool you can verify if your parameters, headers and your upload files work with the type of request you want to make to the server. So, this work with **Swift 2.x** and **Alamofire 3.x**: First of all prepare your headers: ``` let headers = [ "Content-Type": "application/zip", "X-Api-Key": userApiKey, ...whatever you need on headers.. ] ``` So, supposing you must send a zip file and the response will be a TEXT/HTML response type (a simple string with SUCCESS or ERROR): ``` let filePath: String! = "/Users/admin.../Documents/myZipFile.zip" var zipData: NSData! = NSData() do { zipData = try NSData(contentsOfFile: filePath, options: NSDataReadingOptions.DataReadingMappedIfSafe) } catch { print("- error during get nsdata from zip file\(error)") } let url :String! = String(format:"...myUrl?key1=%@&key2=%@",value1,value2) Alamofire.upload(.POST, url, headers: headers, data: zipData) .responseString { response in if response.result.isSuccess { let responseValue = response.result.value print("Response value is: \(responseValue)") } else { var statusCode = 0 if (response.response != nil) { statusCode = (response.response?.statusCode)! } print("Error: \(response.result.error!) with statusCode: \(statusCode)") } ``` Thats all but if you want to use multipartformdata you can do it passing your headers through headers dictionary with: > > **.upload(<#T##method: Method##Method#>, <#T##URLString: > URLStringConvertible##URLStringConvertible#>, headers: <#T##[String : > String]?#>, multipartFormData: <#T##MultipartFormData -> Void#**> > > >
Using [@alessandro-ornano](https://stackoverflow.com/a/35559587/2752041)'s answer I was able to make an upload signed request using `multipartFormData`: ``` func uploadProfilePicture(photo: UIImage, callback: apiCallback){ guard let userId = _loggedInUser?["pk"].int else { callback(Response(success: false, responseMessage: "User not logged in")) return } let requestData: requestDataType = ["timestamp": "\(Int(NSDate().timeIntervalSince1970))"] let headers = self.signRequest(requestData) _alamofireManager .upload(.POST, "\(_apiBaseUrl)profiles/\(userId)/photo/", headers: headers, multipartFormData: { formData in if let imageData = UIImageJPEGRepresentation(photo, 1){ formData.appendBodyPart(data: imageData, name: "upload", fileName: "userphoto.jpg", mimeType: "image/jpg") } for (k, v) in requestData { formData.appendBodyPart(data: v.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) } }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in self.responseHandler(response, callback: callback) // Class' private method } case .Failure(let encodingError): print(encodingError) self.dispatch_callback(callback, response: Response(success: false, responseMessage: "Unable to encode files for upload")) // Class' private method } }) } ```
3,309,614
Say I have a struct defined somewhere deep in low-level code used all over the place in the most crazy and unknown ways: ``` struct T { unsigned short name_len; char d_name[LENGTH]; } ``` With accompanying functions that fill d\_name with whatever needs to be put there, like ``` struct T* fill( somethingOrOther* X) ``` And I would like to extend the old struct+function to include a new variable: ``` struct T { unsigned short name_len; char d_name[LENGTH]; unsigned short type_len; char d_type; } ``` and the new version of the function would also fill the d\_type variable with useful things. Would this type of change break the API? Couldn't I just use the new T instead of the old T, and additionally access the new members?
2010/07/22
[ "https://Stackoverflow.com/questions/3309614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256138/" ]
If T really is used all over the place in crazy and unknown ways, then a change like that is likely to break something. Somewhere there will be a piece of code that has a local declaration of T instead of using your header file, or casts a 'mystruct \*' to a 'T \*', or something equally repugnant.
Yes- when you use an opaque pointer like that, then it is irrelevant of the contents. As long as your users only ever used the opaque pointers, you can muck around with the struct and it's implementation all you like.
3,309,614
Say I have a struct defined somewhere deep in low-level code used all over the place in the most crazy and unknown ways: ``` struct T { unsigned short name_len; char d_name[LENGTH]; } ``` With accompanying functions that fill d\_name with whatever needs to be put there, like ``` struct T* fill( somethingOrOther* X) ``` And I would like to extend the old struct+function to include a new variable: ``` struct T { unsigned short name_len; char d_name[LENGTH]; unsigned short type_len; char d_type; } ``` and the new version of the function would also fill the d\_type variable with useful things. Would this type of change break the API? Couldn't I just use the new T instead of the old T, and additionally access the new members?
2010/07/22
[ "https://Stackoverflow.com/questions/3309614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256138/" ]
It might make sense to extend your structs like this: ``` struct newT { struct T t; int newElement; ... } ``` Then you can safely use a newT pointer as a T pointer; the C standard guarantees that there is no padding before the first element of a struct.
Yes- when you use an opaque pointer like that, then it is irrelevant of the contents. As long as your users only ever used the opaque pointers, you can muck around with the struct and it's implementation all you like.
3,309,614
Say I have a struct defined somewhere deep in low-level code used all over the place in the most crazy and unknown ways: ``` struct T { unsigned short name_len; char d_name[LENGTH]; } ``` With accompanying functions that fill d\_name with whatever needs to be put there, like ``` struct T* fill( somethingOrOther* X) ``` And I would like to extend the old struct+function to include a new variable: ``` struct T { unsigned short name_len; char d_name[LENGTH]; unsigned short type_len; char d_type; } ``` and the new version of the function would also fill the d\_type variable with useful things. Would this type of change break the API? Couldn't I just use the new T instead of the old T, and additionally access the new members?
2010/07/22
[ "https://Stackoverflow.com/questions/3309614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256138/" ]
As long as the code using this API only obtains `T` objects as pointers returned by the library, and does not declare them itself, `malloc` them itself (using `sizeof(struct T)`), or do anything else that depends on the size of the struct, then it should be fine. If the calling code accessed the contents of the struct, you need to make sure you put new members at the end of the struct. One possible additional consideration is whether any code depends on `d_name` being at the end of the structure in order to allocate space for and store larger names if the declared size does not fit. I only bring this up because the names of the members suggest the struct is something like `dirent` and that's traditional practice for `dirent`.
Yes- when you use an opaque pointer like that, then it is irrelevant of the contents. As long as your users only ever used the opaque pointers, you can muck around with the struct and it's implementation all you like.
3,309,614
Say I have a struct defined somewhere deep in low-level code used all over the place in the most crazy and unknown ways: ``` struct T { unsigned short name_len; char d_name[LENGTH]; } ``` With accompanying functions that fill d\_name with whatever needs to be put there, like ``` struct T* fill( somethingOrOther* X) ``` And I would like to extend the old struct+function to include a new variable: ``` struct T { unsigned short name_len; char d_name[LENGTH]; unsigned short type_len; char d_type; } ``` and the new version of the function would also fill the d\_type variable with useful things. Would this type of change break the API? Couldn't I just use the new T instead of the old T, and additionally access the new members?
2010/07/22
[ "https://Stackoverflow.com/questions/3309614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256138/" ]
Yes- when you use an opaque pointer like that, then it is irrelevant of the contents. As long as your users only ever used the opaque pointers, you can muck around with the struct and it's implementation all you like.
Crazy and unknown is not good. The best bet is to scan through the codebase for struct T and examine how it is used, with the alternative approach of changing it and see if something breaks... If the code only uses opaque pointers, you should be on the safe side. If the code accesses the members, but doesn't do something weird, you should be safe too, with a complete recompilation. If it does something weird, like the examples of rettops, even Jukka's tip may not help. The code could use a hardcoded value for the sizeof to do pointer arithmetic within an array of these structs...
3,309,614
Say I have a struct defined somewhere deep in low-level code used all over the place in the most crazy and unknown ways: ``` struct T { unsigned short name_len; char d_name[LENGTH]; } ``` With accompanying functions that fill d\_name with whatever needs to be put there, like ``` struct T* fill( somethingOrOther* X) ``` And I would like to extend the old struct+function to include a new variable: ``` struct T { unsigned short name_len; char d_name[LENGTH]; unsigned short type_len; char d_type; } ``` and the new version of the function would also fill the d\_type variable with useful things. Would this type of change break the API? Couldn't I just use the new T instead of the old T, and additionally access the new members?
2010/07/22
[ "https://Stackoverflow.com/questions/3309614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256138/" ]
It might make sense to extend your structs like this: ``` struct newT { struct T t; int newElement; ... } ``` Then you can safely use a newT pointer as a T pointer; the C standard guarantees that there is no padding before the first element of a struct.
If T really is used all over the place in crazy and unknown ways, then a change like that is likely to break something. Somewhere there will be a piece of code that has a local declaration of T instead of using your header file, or casts a 'mystruct \*' to a 'T \*', or something equally repugnant.
3,309,614
Say I have a struct defined somewhere deep in low-level code used all over the place in the most crazy and unknown ways: ``` struct T { unsigned short name_len; char d_name[LENGTH]; } ``` With accompanying functions that fill d\_name with whatever needs to be put there, like ``` struct T* fill( somethingOrOther* X) ``` And I would like to extend the old struct+function to include a new variable: ``` struct T { unsigned short name_len; char d_name[LENGTH]; unsigned short type_len; char d_type; } ``` and the new version of the function would also fill the d\_type variable with useful things. Would this type of change break the API? Couldn't I just use the new T instead of the old T, and additionally access the new members?
2010/07/22
[ "https://Stackoverflow.com/questions/3309614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256138/" ]
As long as the code using this API only obtains `T` objects as pointers returned by the library, and does not declare them itself, `malloc` them itself (using `sizeof(struct T)`), or do anything else that depends on the size of the struct, then it should be fine. If the calling code accessed the contents of the struct, you need to make sure you put new members at the end of the struct. One possible additional consideration is whether any code depends on `d_name` being at the end of the structure in order to allocate space for and store larger names if the declared size does not fit. I only bring this up because the names of the members suggest the struct is something like `dirent` and that's traditional practice for `dirent`.
If T really is used all over the place in crazy and unknown ways, then a change like that is likely to break something. Somewhere there will be a piece of code that has a local declaration of T instead of using your header file, or casts a 'mystruct \*' to a 'T \*', or something equally repugnant.
3,309,614
Say I have a struct defined somewhere deep in low-level code used all over the place in the most crazy and unknown ways: ``` struct T { unsigned short name_len; char d_name[LENGTH]; } ``` With accompanying functions that fill d\_name with whatever needs to be put there, like ``` struct T* fill( somethingOrOther* X) ``` And I would like to extend the old struct+function to include a new variable: ``` struct T { unsigned short name_len; char d_name[LENGTH]; unsigned short type_len; char d_type; } ``` and the new version of the function would also fill the d\_type variable with useful things. Would this type of change break the API? Couldn't I just use the new T instead of the old T, and additionally access the new members?
2010/07/22
[ "https://Stackoverflow.com/questions/3309614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256138/" ]
If T really is used all over the place in crazy and unknown ways, then a change like that is likely to break something. Somewhere there will be a piece of code that has a local declaration of T instead of using your header file, or casts a 'mystruct \*' to a 'T \*', or something equally repugnant.
Crazy and unknown is not good. The best bet is to scan through the codebase for struct T and examine how it is used, with the alternative approach of changing it and see if something breaks... If the code only uses opaque pointers, you should be on the safe side. If the code accesses the members, but doesn't do something weird, you should be safe too, with a complete recompilation. If it does something weird, like the examples of rettops, even Jukka's tip may not help. The code could use a hardcoded value for the sizeof to do pointer arithmetic within an array of these structs...
3,309,614
Say I have a struct defined somewhere deep in low-level code used all over the place in the most crazy and unknown ways: ``` struct T { unsigned short name_len; char d_name[LENGTH]; } ``` With accompanying functions that fill d\_name with whatever needs to be put there, like ``` struct T* fill( somethingOrOther* X) ``` And I would like to extend the old struct+function to include a new variable: ``` struct T { unsigned short name_len; char d_name[LENGTH]; unsigned short type_len; char d_type; } ``` and the new version of the function would also fill the d\_type variable with useful things. Would this type of change break the API? Couldn't I just use the new T instead of the old T, and additionally access the new members?
2010/07/22
[ "https://Stackoverflow.com/questions/3309614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256138/" ]
It might make sense to extend your structs like this: ``` struct newT { struct T t; int newElement; ... } ``` Then you can safely use a newT pointer as a T pointer; the C standard guarantees that there is no padding before the first element of a struct.
Crazy and unknown is not good. The best bet is to scan through the codebase for struct T and examine how it is used, with the alternative approach of changing it and see if something breaks... If the code only uses opaque pointers, you should be on the safe side. If the code accesses the members, but doesn't do something weird, you should be safe too, with a complete recompilation. If it does something weird, like the examples of rettops, even Jukka's tip may not help. The code could use a hardcoded value for the sizeof to do pointer arithmetic within an array of these structs...
3,309,614
Say I have a struct defined somewhere deep in low-level code used all over the place in the most crazy and unknown ways: ``` struct T { unsigned short name_len; char d_name[LENGTH]; } ``` With accompanying functions that fill d\_name with whatever needs to be put there, like ``` struct T* fill( somethingOrOther* X) ``` And I would like to extend the old struct+function to include a new variable: ``` struct T { unsigned short name_len; char d_name[LENGTH]; unsigned short type_len; char d_type; } ``` and the new version of the function would also fill the d\_type variable with useful things. Would this type of change break the API? Couldn't I just use the new T instead of the old T, and additionally access the new members?
2010/07/22
[ "https://Stackoverflow.com/questions/3309614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256138/" ]
As long as the code using this API only obtains `T` objects as pointers returned by the library, and does not declare them itself, `malloc` them itself (using `sizeof(struct T)`), or do anything else that depends on the size of the struct, then it should be fine. If the calling code accessed the contents of the struct, you need to make sure you put new members at the end of the struct. One possible additional consideration is whether any code depends on `d_name` being at the end of the structure in order to allocate space for and store larger names if the declared size does not fit. I only bring this up because the names of the members suggest the struct is something like `dirent` and that's traditional practice for `dirent`.
Crazy and unknown is not good. The best bet is to scan through the codebase for struct T and examine how it is used, with the alternative approach of changing it and see if something breaks... If the code only uses opaque pointers, you should be on the safe side. If the code accesses the members, but doesn't do something weird, you should be safe too, with a complete recompilation. If it does something weird, like the examples of rettops, even Jukka's tip may not help. The code could use a hardcoded value for the sizeof to do pointer arithmetic within an array of these structs...
23,483,086
There is a well known blog post going around on how to set a usb bluetooth 4 dongle to be an iBeacon. It boils down to this magical command: ``` sudo hcitool -i hci0 cmd 0x08 0x0008 1e 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 00 00 00 00 00 00 00 00 00 00 00 00 00 ``` The issue with this example is that it is so opaque it's hard to use it in any more general format. I've been able to break it apart a bit: ``` sudo hcitool -i hci0 cmd ``` sends an hci command to the hci0 device ``` 0x08 0x0008 ``` is just magic to set the ad package, other stackoverflow commands have said "just use it, don't ask ``` 1e ``` is the length of the ENTIRE following data packet in bytes ``` 02 01 1a 1a ``` Are flags to set up the ad packet (details on request) ``` ff 4c 00 ... ``` is the 'company specific data' that encodes the iBeacon info What I've tried to do is replace the "FF ..." bytes with the opcodes for setting the NAME parameter "04 09 41 42 43" (which should set it to ABC) but that doesn't work. I'm surprised the hcitool doesn't give us some examples on how to set the ad packet as this would be very useful in setting all sorts of other params (like TEMP or POWER). Has anyone else had any experience in using hcitool to set things like NAME?
2014/05/05
[ "https://Stackoverflow.com/questions/23483086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3606020/" ]
Late reply, but somebody might find this useful. I found it as I was looking around for solutions myself when using hcitool. If you use `hcitool cmd --help` it will tell you something like this `cmd <ogf> <ocf> ...`. It helps to look at the [Bluetooth Core Specification](https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=229737) to find out what 0x08 and 0x0008 would be for OGF and OCF. Specifically Vol. 2, Part E, 7.8 > > For the LE Controller Commands, the OGF code is defined as 0x08 > > > and for the OCF of 0x0008 > > Advertising\_Data\_Length, Advertising\_Data > > > So basically, with 0x08 0x0008 you say you are setting (in the LE Controller) the length of the data that is sent. As for the name, since the length of the BLE advertisement packet is 31 bytes (1E), you need to send the whole 31 bytes. So if you only have ABC as the name, setting `04 09 41 42 43` is correct, but that's only five bytes. For 31 you need to add `00` 26 times. Just be careful you don't add too much or too little. Also, I wasn't under the impression that BLE ad. packets are of fixed 31 byte size, but they are at least for hcitool. It doesn't work when you specifically set the outgoing size to something smaller than `1E`.
Check out [this answer](https://stackoverflow.com/a/22148306/1461050) to a similar question. It basically describes how you can download the giant [Bluetooth Core Spec](https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=229737) document, and read through all the commands that it offers you. You can use the hcitool command to execute any of these commands if you can just figure out the right format (and figure out what the commands actually do!) Major caveat: I have not tried setting the name myself, but glancing at the spec, it looks like this is described on page 482 of the spec in section "7.3.11 Write Local Name Command". According to this the command consists of: ``` OCF: 0x0013 Name (up to 248 bytes) ``` So I would try a command like this: `hcitool -i hci0 cmd 0x08 0x0013 41 42 43` One other tip: When you issue commands like this, try running `hcidump &` so the command executes in the background. Then, you can enter experimental `hcitool` commands (or even `hciconfig` commands) and see annotated details about what (human readable) commands executed and what errors occurred, if any. Using the above tip, you can also try executing `hciconfig name abc` to set the local name using that command line tool, while you are executing a `hcidump &` in the background. This should show you the proper hcitool command values to use.
23,483,086
There is a well known blog post going around on how to set a usb bluetooth 4 dongle to be an iBeacon. It boils down to this magical command: ``` sudo hcitool -i hci0 cmd 0x08 0x0008 1e 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 00 00 00 00 00 00 00 00 00 00 00 00 00 ``` The issue with this example is that it is so opaque it's hard to use it in any more general format. I've been able to break it apart a bit: ``` sudo hcitool -i hci0 cmd ``` sends an hci command to the hci0 device ``` 0x08 0x0008 ``` is just magic to set the ad package, other stackoverflow commands have said "just use it, don't ask ``` 1e ``` is the length of the ENTIRE following data packet in bytes ``` 02 01 1a 1a ``` Are flags to set up the ad packet (details on request) ``` ff 4c 00 ... ``` is the 'company specific data' that encodes the iBeacon info What I've tried to do is replace the "FF ..." bytes with the opcodes for setting the NAME parameter "04 09 41 42 43" (which should set it to ABC) but that doesn't work. I'm surprised the hcitool doesn't give us some examples on how to set the ad packet as this would be very useful in setting all sorts of other params (like TEMP or POWER). Has anyone else had any experience in using hcitool to set things like NAME?
2014/05/05
[ "https://Stackoverflow.com/questions/23483086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3606020/" ]
No. None of this answers is correct and clean. 1) BLE have a separate command set. "LE Set Advertising Data" command must be used (see 7.8.7 vol 2 part E). 2) LE Set Advertising Data is much complex than what explained above. There are at least 2 1-octet length fields, packet must be 32 bytes length, zero padded, but the first length byte must not be 0x1e (31) but the length of the significant used part, containing one or more headers. Each header still contains a length, one AS Type byte (0x09 for set local name) and the name. SET LE LOCAL NAME: ``` hciconfig hci0 down hciconfig hci0 up hcitool -i hci0 cmd 0x08 0x0008 0c 0b 09 6c 69 6e 6b 6d 6f 74 69 6f 6e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 hciconfig hci0 leadv 0 ``` 0x0c : length of the following group of headers 0x0b : length of this header 0x09 : AD Type for complete name rest 0x0a length is the name
Check out [this answer](https://stackoverflow.com/a/22148306/1461050) to a similar question. It basically describes how you can download the giant [Bluetooth Core Spec](https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=229737) document, and read through all the commands that it offers you. You can use the hcitool command to execute any of these commands if you can just figure out the right format (and figure out what the commands actually do!) Major caveat: I have not tried setting the name myself, but glancing at the spec, it looks like this is described on page 482 of the spec in section "7.3.11 Write Local Name Command". According to this the command consists of: ``` OCF: 0x0013 Name (up to 248 bytes) ``` So I would try a command like this: `hcitool -i hci0 cmd 0x08 0x0013 41 42 43` One other tip: When you issue commands like this, try running `hcidump &` so the command executes in the background. Then, you can enter experimental `hcitool` commands (or even `hciconfig` commands) and see annotated details about what (human readable) commands executed and what errors occurred, if any. Using the above tip, you can also try executing `hciconfig name abc` to set the local name using that command line tool, while you are executing a `hcidump &` in the background. This should show you the proper hcitool command values to use.
23,483,086
There is a well known blog post going around on how to set a usb bluetooth 4 dongle to be an iBeacon. It boils down to this magical command: ``` sudo hcitool -i hci0 cmd 0x08 0x0008 1e 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 00 00 00 00 00 00 00 00 00 00 00 00 00 ``` The issue with this example is that it is so opaque it's hard to use it in any more general format. I've been able to break it apart a bit: ``` sudo hcitool -i hci0 cmd ``` sends an hci command to the hci0 device ``` 0x08 0x0008 ``` is just magic to set the ad package, other stackoverflow commands have said "just use it, don't ask ``` 1e ``` is the length of the ENTIRE following data packet in bytes ``` 02 01 1a 1a ``` Are flags to set up the ad packet (details on request) ``` ff 4c 00 ... ``` is the 'company specific data' that encodes the iBeacon info What I've tried to do is replace the "FF ..." bytes with the opcodes for setting the NAME parameter "04 09 41 42 43" (which should set it to ABC) but that doesn't work. I'm surprised the hcitool doesn't give us some examples on how to set the ad packet as this would be very useful in setting all sorts of other params (like TEMP or POWER). Has anyone else had any experience in using hcitool to set things like NAME?
2014/05/05
[ "https://Stackoverflow.com/questions/23483086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3606020/" ]
Late reply, but somebody might find this useful. I found it as I was looking around for solutions myself when using hcitool. If you use `hcitool cmd --help` it will tell you something like this `cmd <ogf> <ocf> ...`. It helps to look at the [Bluetooth Core Specification](https://www.bluetooth.org/docman/handlers/downloaddoc.ashx?doc_id=229737) to find out what 0x08 and 0x0008 would be for OGF and OCF. Specifically Vol. 2, Part E, 7.8 > > For the LE Controller Commands, the OGF code is defined as 0x08 > > > and for the OCF of 0x0008 > > Advertising\_Data\_Length, Advertising\_Data > > > So basically, with 0x08 0x0008 you say you are setting (in the LE Controller) the length of the data that is sent. As for the name, since the length of the BLE advertisement packet is 31 bytes (1E), you need to send the whole 31 bytes. So if you only have ABC as the name, setting `04 09 41 42 43` is correct, but that's only five bytes. For 31 you need to add `00` 26 times. Just be careful you don't add too much or too little. Also, I wasn't under the impression that BLE ad. packets are of fixed 31 byte size, but they are at least for hcitool. It doesn't work when you specifically set the outgoing size to something smaller than `1E`.
It would appear you need to use two commands rather than one. The iBeacon data is contained in the "LE Set Advertising Data" data and has been mentioned elsewhere in this post. To see a BLE friendly name you can use an additional command "LE Set Scan Response Data", this requires the receiver to scan your device (rather than passively read the advertising packet). So you can combine Angelo's example with [this one](https://learn.adafruit.com/pibeacon-ibeacon-with-a-raspberry-pi/adding-ibeacon-data) to set the device as an iBeacon and set the "friendly name" which is the Scan Response data ``` sudo hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 E2 0A 39 F4 73 F5 4B C4 A1 2F 17 D1 AD 07 A9 61 00 00 00 00 C8 00 sudo hcitool -i hci0 cmd 0x08 0x0009 0c 0b 09 6c 69 6e 6b 6d 6f 74 69 6f 6e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ``` This worked for me using an Ubuntu box with a BLE dongle and then scanning for the beacon using this [android BLE](https://play.google.com/store/apps/details?id=uk.co.alt236.btlescan&hl=en_GB) scanning app
23,483,086
There is a well known blog post going around on how to set a usb bluetooth 4 dongle to be an iBeacon. It boils down to this magical command: ``` sudo hcitool -i hci0 cmd 0x08 0x0008 1e 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 00 00 00 00 00 00 00 00 00 00 00 00 00 ``` The issue with this example is that it is so opaque it's hard to use it in any more general format. I've been able to break it apart a bit: ``` sudo hcitool -i hci0 cmd ``` sends an hci command to the hci0 device ``` 0x08 0x0008 ``` is just magic to set the ad package, other stackoverflow commands have said "just use it, don't ask ``` 1e ``` is the length of the ENTIRE following data packet in bytes ``` 02 01 1a 1a ``` Are flags to set up the ad packet (details on request) ``` ff 4c 00 ... ``` is the 'company specific data' that encodes the iBeacon info What I've tried to do is replace the "FF ..." bytes with the opcodes for setting the NAME parameter "04 09 41 42 43" (which should set it to ABC) but that doesn't work. I'm surprised the hcitool doesn't give us some examples on how to set the ad packet as this would be very useful in setting all sorts of other params (like TEMP or POWER). Has anyone else had any experience in using hcitool to set things like NAME?
2014/05/05
[ "https://Stackoverflow.com/questions/23483086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3606020/" ]
No. None of this answers is correct and clean. 1) BLE have a separate command set. "LE Set Advertising Data" command must be used (see 7.8.7 vol 2 part E). 2) LE Set Advertising Data is much complex than what explained above. There are at least 2 1-octet length fields, packet must be 32 bytes length, zero padded, but the first length byte must not be 0x1e (31) but the length of the significant used part, containing one or more headers. Each header still contains a length, one AS Type byte (0x09 for set local name) and the name. SET LE LOCAL NAME: ``` hciconfig hci0 down hciconfig hci0 up hcitool -i hci0 cmd 0x08 0x0008 0c 0b 09 6c 69 6e 6b 6d 6f 74 69 6f 6e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 hciconfig hci0 leadv 0 ``` 0x0c : length of the following group of headers 0x0b : length of this header 0x09 : AD Type for complete name rest 0x0a length is the name
It would appear you need to use two commands rather than one. The iBeacon data is contained in the "LE Set Advertising Data" data and has been mentioned elsewhere in this post. To see a BLE friendly name you can use an additional command "LE Set Scan Response Data", this requires the receiver to scan your device (rather than passively read the advertising packet). So you can combine Angelo's example with [this one](https://learn.adafruit.com/pibeacon-ibeacon-with-a-raspberry-pi/adding-ibeacon-data) to set the device as an iBeacon and set the "friendly name" which is the Scan Response data ``` sudo hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 E2 0A 39 F4 73 F5 4B C4 A1 2F 17 D1 AD 07 A9 61 00 00 00 00 C8 00 sudo hcitool -i hci0 cmd 0x08 0x0009 0c 0b 09 6c 69 6e 6b 6d 6f 74 69 6f 6e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ``` This worked for me using an Ubuntu box with a BLE dongle and then scanning for the beacon using this [android BLE](https://play.google.com/store/apps/details?id=uk.co.alt236.btlescan&hl=en_GB) scanning app
316,879
I have a method in an objective-C class. It has 2 callback functions written in C. The class pointer i.e. `self` is passed to these functions as `void *`. In the C functions I create a pointer of type class and assign the `void *` parameter. The first callback function executes successfully. But the `void *` pointer becomes `nil` in the 2nd callback function. Note that I haven't tweaked pointer in the first callback but still I get `nil` in 2nd callback. Any ideas what might be going wrong? For example: ``` kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification, matchingDict, RawDeviceAdded, NULL, &gRawAddedIter); RawDeviceAdded(NULL, gRawAddedIter, self); ``` This works fine. But below function receives `self` as `nil`. ``` kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification, matchingDict, BulkTestDeviceAdded, NULL, &gBulkTestAddedIter); BulkTestDeviceAdded(NULL, gBulkTestAddedIter, self); ```
2008/11/25
[ "https://Stackoverflow.com/questions/316879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39270/" ]
Generally, callbacks in Objective-C are handled by passing a delegate object and a selector to perform on that delegate. For example, this method will call a method on its delegate after logging a message, passing both itself and the message that was logged. ``` - (void)logMessage:(NSString *)message delegate:(id)delegate didLogSelector:(SEL)didLogSelector { NSLog(@"%@", message); if (delegate && didLogSelector && [delegate respondsToSelector:didLogSelector]) { (void) [delegate performSelector:didLogSelector withObject:self withObject:message]; } } ``` You might call it in code like this: ``` - (void)sayHello { [logger logMessage:@"Hello, world" delegate:self didLogSelector:@selector(messageLogger:didLogMessage:)]; } - (void)messageLogger:(id)logger didLogMessage:(NSString *)message { NSLog(@"Message logger %@ logged message '%@'", logger, message); } ``` You can also use `objc_msgSend()` directly instead, though you need to understand the Objective-C runtime enough to choose which variant to use and how to construct the prototype and function pointer through which to call it. (It's the mechanism by which message sends are actually implemented in Objective-C — what the compiler normally generates calls to in order to represent `[]` expressions.)
This is what Objective-C's selector is for: [<http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/NSInvocationOperation_Class>](http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/NSInvocationOperation_Class/Reference/Reference.html) The API isn't very intuitive, but its fine once you understand it You might need to do some refactoring as well, now there might be a better way, but when I had this problem my solution was to refactor and use InvoationOperation.
316,879
I have a method in an objective-C class. It has 2 callback functions written in C. The class pointer i.e. `self` is passed to these functions as `void *`. In the C functions I create a pointer of type class and assign the `void *` parameter. The first callback function executes successfully. But the `void *` pointer becomes `nil` in the 2nd callback function. Note that I haven't tweaked pointer in the first callback but still I get `nil` in 2nd callback. Any ideas what might be going wrong? For example: ``` kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification, matchingDict, RawDeviceAdded, NULL, &gRawAddedIter); RawDeviceAdded(NULL, gRawAddedIter, self); ``` This works fine. But below function receives `self` as `nil`. ``` kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification, matchingDict, BulkTestDeviceAdded, NULL, &gBulkTestAddedIter); BulkTestDeviceAdded(NULL, gBulkTestAddedIter, self); ```
2008/11/25
[ "https://Stackoverflow.com/questions/316879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39270/" ]
Are your problems specifically with the IOKit callback routines? The problem with the specific example you gave is that the IOServiceMatchingCallback takes only 2 parameters, not 3. You need your RawDeviceAdded() and BulkTestDeviceAdded() callback functions to match the IOServiceMatchingCallback prototype and to accept self as the first parameter (refCon), not the 3rd. Also, you need to pass in self as the second-to-last parameter of IOServiceAddMatchingNotification() to get it passed back to you by the callback. A common method for handling C callbacks in Objective-C code is just to have a static function that forwards the callback to your instance. So, your example callback code would look like this: ``` static RawDeviceAdded(void* refcon, io_iterator_t iterator) { [(MyClass*)refcon rawDeviceAdded:iterator]; } @implementation MyClass - (void)setupCallbacks { // ... all preceding setup snipped kr = IOServiceAddMatchingNotification(gNotifyPort,kIOFirstMatchNotification, matchingDict,RawDeviceAdded,(void*)self,&gRawAddedIter ); // call the callback method once to 'arm' the iterator [self rawDeviceAdded:gRawAddedIterator]; } - (void)rawDeviceAdded:(io_iterator_t)iterator { // take care of the iterator here, making sure to complete iteration to re-arm it } @end ```
This is what Objective-C's selector is for: [<http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/NSInvocationOperation_Class>](http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/NSInvocationOperation_Class/Reference/Reference.html) The API isn't very intuitive, but its fine once you understand it You might need to do some refactoring as well, now there might be a better way, but when I had this problem my solution was to refactor and use InvoationOperation.
316,879
I have a method in an objective-C class. It has 2 callback functions written in C. The class pointer i.e. `self` is passed to these functions as `void *`. In the C functions I create a pointer of type class and assign the `void *` parameter. The first callback function executes successfully. But the `void *` pointer becomes `nil` in the 2nd callback function. Note that I haven't tweaked pointer in the first callback but still I get `nil` in 2nd callback. Any ideas what might be going wrong? For example: ``` kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification, matchingDict, RawDeviceAdded, NULL, &gRawAddedIter); RawDeviceAdded(NULL, gRawAddedIter, self); ``` This works fine. But below function receives `self` as `nil`. ``` kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification, matchingDict, BulkTestDeviceAdded, NULL, &gBulkTestAddedIter); BulkTestDeviceAdded(NULL, gBulkTestAddedIter, self); ```
2008/11/25
[ "https://Stackoverflow.com/questions/316879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39270/" ]
Are your problems specifically with the IOKit callback routines? The problem with the specific example you gave is that the IOServiceMatchingCallback takes only 2 parameters, not 3. You need your RawDeviceAdded() and BulkTestDeviceAdded() callback functions to match the IOServiceMatchingCallback prototype and to accept self as the first parameter (refCon), not the 3rd. Also, you need to pass in self as the second-to-last parameter of IOServiceAddMatchingNotification() to get it passed back to you by the callback. A common method for handling C callbacks in Objective-C code is just to have a static function that forwards the callback to your instance. So, your example callback code would look like this: ``` static RawDeviceAdded(void* refcon, io_iterator_t iterator) { [(MyClass*)refcon rawDeviceAdded:iterator]; } @implementation MyClass - (void)setupCallbacks { // ... all preceding setup snipped kr = IOServiceAddMatchingNotification(gNotifyPort,kIOFirstMatchNotification, matchingDict,RawDeviceAdded,(void*)self,&gRawAddedIter ); // call the callback method once to 'arm' the iterator [self rawDeviceAdded:gRawAddedIterator]; } - (void)rawDeviceAdded:(io_iterator_t)iterator { // take care of the iterator here, making sure to complete iteration to re-arm it } @end ```
Generally, callbacks in Objective-C are handled by passing a delegate object and a selector to perform on that delegate. For example, this method will call a method on its delegate after logging a message, passing both itself and the message that was logged. ``` - (void)logMessage:(NSString *)message delegate:(id)delegate didLogSelector:(SEL)didLogSelector { NSLog(@"%@", message); if (delegate && didLogSelector && [delegate respondsToSelector:didLogSelector]) { (void) [delegate performSelector:didLogSelector withObject:self withObject:message]; } } ``` You might call it in code like this: ``` - (void)sayHello { [logger logMessage:@"Hello, world" delegate:self didLogSelector:@selector(messageLogger:didLogMessage:)]; } - (void)messageLogger:(id)logger didLogMessage:(NSString *)message { NSLog(@"Message logger %@ logged message '%@'", logger, message); } ``` You can also use `objc_msgSend()` directly instead, though you need to understand the Objective-C runtime enough to choose which variant to use and how to construct the prototype and function pointer through which to call it. (It's the mechanism by which message sends are actually implemented in Objective-C — what the compiler normally generates calls to in order to represent `[]` expressions.)
4,038,534
Suppose that $a,b,c,d$ are vectors in $\mathbb{R}^2$, so $a\_{\alpha}$ where $\alpha = 1,2$. We define a scalar product as $a \cdot b := a\_1 b\_2 - a\_2 b\_1$. Suppose also that we have a real-valued function $f(a,b,c)$ which is a function of some $3$ vectors. What does the Taylor expansion of $f$ look like to first order? For example, I want to Taylor expand $f(a+b,c,d)$ around $(a, c, d)$, so $$f (a+b, c, d) = f(a,c,d) + \ldots $$ but I don't know how to write the remaining terms. Do I get a scalar product of $b$ with some term?
2021/02/24
[ "https://math.stackexchange.com/questions/4038534", "https://math.stackexchange.com", "https://math.stackexchange.com/users/203030/" ]
There is something to confront here in your question, which has been pointed out already. The first thing is to see that your "scalar product" is not a scalar product: it's a skew symmetric bilinear form. More specifically, notice that $a \cdot a = 0 \hspace{4pt} \forall a$. What you've written is actually the magnitude of the vector-cross product of $a$ and $b$ (More precisely, given a linear map $T: \mathbb{R}^2 \to \mathbb{R}^3 $, $a \cdot b = \vert Ta \times Tb \vert$). This is not a scalar product. We can relate your skew symmetric form to the usual Euclidean inner product $( \cdot, \cdot)\_E $ by the formula $$ a \cdot b = (a, Jb)\_E $$ Where $J$ is a matrix, $$ J = \begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix} $$ So that's what we're dealing with. Now let's look at a Taylor expansion of your function. Any sensible Taylor expansion should look like $$ F(a + tb) = F(a) + (b \cdot DF(a)) t + \mathcal{O}(t^2) $$ Where $DF(a)$ is some suitable notion of derivative at $a$. From this we can see that $$ b \cdot DF(a) = \frac{d}{dt} F(a + tb) \vert\_{t=0} $$ I think that formula should get at the crux of your question. However, there's more to notice here. We can write out the right side as the usual inner product with the gradient $ \nabla F $: $$ \frac{d}{dt} F(a + tb) \vert\_{t=0} = (b, \nabla F(a))\_E $$ and using our relation of the skew symmetric form to the euclidean inner product, we have $$ b \cdot DF(a) = (b, J DF(a))\_E $$ These two are equal, and if they are equal for all $b$, this implies $$ J DF(a) = \nabla F(a) $$ $J$ is invertible, so we see that $ DF(a) = J^{-1} \nabla F(a)$. Summarizing, $$ F(a+b) = F(a) + b \cdot (J^{-1} \nabla F(a)) + \mathcal{O}(t^2) $$
If have only a partial answer, hope this helps: The difficulty here is definitely your "scalar product". I set this in quotation marks because it is not a scalar product (not even a semi-definite one) because it is skew-symmetric: $a\cdot b = -b \cdot a$ It is merely a skew-symmetric bilinear form, which does not define a metric on your space. Now, I do not know much about exotic topologies, but I am pretty sure you need at least a sense of distance (i.e., a metric) to define derivatives on any space. This is not given by your scalar product and therefore the Taylor expansion is not defined. Is it possible that your "scalar product" is independent from the geometry of the space? I.e., it is just a skew-symmetric bilinear form defined in $\mathbb{R}^2$? Then, the Taylor expansion would be the usual one with the usual scalar product $\langle a, b \rangle = a\_1 b\_1 + a\_2 b\_2$. Let me know if I am wrong with anything!
4,038,534
Suppose that $a,b,c,d$ are vectors in $\mathbb{R}^2$, so $a\_{\alpha}$ where $\alpha = 1,2$. We define a scalar product as $a \cdot b := a\_1 b\_2 - a\_2 b\_1$. Suppose also that we have a real-valued function $f(a,b,c)$ which is a function of some $3$ vectors. What does the Taylor expansion of $f$ look like to first order? For example, I want to Taylor expand $f(a+b,c,d)$ around $(a, c, d)$, so $$f (a+b, c, d) = f(a,c,d) + \ldots $$ but I don't know how to write the remaining terms. Do I get a scalar product of $b$ with some term?
2021/02/24
[ "https://math.stackexchange.com/questions/4038534", "https://math.stackexchange.com", "https://math.stackexchange.com/users/203030/" ]
$\def\va{{\bf a}} \def\vb{{\bf b}} \def\vc{{\bf c}} \def\vd{{\bf d}} \def\e{\varepsilon} \def\np{\odot}$We have \begin{align\*} f(\va+\vb,\vc,\vd) &= f(\va,\vc,\vd) + \sum\_i b\_i\left.\frac{\partial f(\va+\vb,\vc,\vd)}{\partial b\_i}\right|\_{b\_i=0} + \ldots \\ &= f(\va,\vc,\vd) + \sum\_i b\_i \frac{\partial f(\va,\vc,\vd)}{\partial a\_i} + \ldots \\ &= f(\va,\vc,\vd) + (\vb,\nabla\_\va f(\va,\vc,\vd)) + \ldots, \end{align\*} where $(,)$ is the usual inner product and where $\nabla\_\va f = \langle \partial f/\partial a\_1,\partial f/\partial a\_2\rangle$ is the gradient. But $(\langle a\_1,a\_2\rangle,\langle b\_1,b\_2\rangle) = \langle a\_1,a\_2\rangle\np\langle -b\_2,b\_1\rangle$. (To avoid confusion with the dot product we will write $\va\np\vb=a\_1b\_2-a\_2b\_1$.) Thus, \begin{align\*} f(\va+\vb,\vc,\vd) &= f(\va,\vc,\vd) + \vb\np \widetilde\nabla\_\va f(\va,\vc,\vd) + \ldots, \end{align\*} where $\widetilde\nabla\_\va f = \langle -\partial f/\partial a\_2,\partial f/\partial a\_1\rangle$. **Addendum** As is discussed in detail in the other answers, the product $\va\np\vb$ is only a "scalar product" in the sense that it is a product of vectors returning a real value.
If have only a partial answer, hope this helps: The difficulty here is definitely your "scalar product". I set this in quotation marks because it is not a scalar product (not even a semi-definite one) because it is skew-symmetric: $a\cdot b = -b \cdot a$ It is merely a skew-symmetric bilinear form, which does not define a metric on your space. Now, I do not know much about exotic topologies, but I am pretty sure you need at least a sense of distance (i.e., a metric) to define derivatives on any space. This is not given by your scalar product and therefore the Taylor expansion is not defined. Is it possible that your "scalar product" is independent from the geometry of the space? I.e., it is just a skew-symmetric bilinear form defined in $\mathbb{R}^2$? Then, the Taylor expansion would be the usual one with the usual scalar product $\langle a, b \rangle = a\_1 b\_1 + a\_2 b\_2$. Let me know if I am wrong with anything!
4,038,534
Suppose that $a,b,c,d$ are vectors in $\mathbb{R}^2$, so $a\_{\alpha}$ where $\alpha = 1,2$. We define a scalar product as $a \cdot b := a\_1 b\_2 - a\_2 b\_1$. Suppose also that we have a real-valued function $f(a,b,c)$ which is a function of some $3$ vectors. What does the Taylor expansion of $f$ look like to first order? For example, I want to Taylor expand $f(a+b,c,d)$ around $(a, c, d)$, so $$f (a+b, c, d) = f(a,c,d) + \ldots $$ but I don't know how to write the remaining terms. Do I get a scalar product of $b$ with some term?
2021/02/24
[ "https://math.stackexchange.com/questions/4038534", "https://math.stackexchange.com", "https://math.stackexchange.com/users/203030/" ]
There is something to confront here in your question, which has been pointed out already. The first thing is to see that your "scalar product" is not a scalar product: it's a skew symmetric bilinear form. More specifically, notice that $a \cdot a = 0 \hspace{4pt} \forall a$. What you've written is actually the magnitude of the vector-cross product of $a$ and $b$ (More precisely, given a linear map $T: \mathbb{R}^2 \to \mathbb{R}^3 $, $a \cdot b = \vert Ta \times Tb \vert$). This is not a scalar product. We can relate your skew symmetric form to the usual Euclidean inner product $( \cdot, \cdot)\_E $ by the formula $$ a \cdot b = (a, Jb)\_E $$ Where $J$ is a matrix, $$ J = \begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix} $$ So that's what we're dealing with. Now let's look at a Taylor expansion of your function. Any sensible Taylor expansion should look like $$ F(a + tb) = F(a) + (b \cdot DF(a)) t + \mathcal{O}(t^2) $$ Where $DF(a)$ is some suitable notion of derivative at $a$. From this we can see that $$ b \cdot DF(a) = \frac{d}{dt} F(a + tb) \vert\_{t=0} $$ I think that formula should get at the crux of your question. However, there's more to notice here. We can write out the right side as the usual inner product with the gradient $ \nabla F $: $$ \frac{d}{dt} F(a + tb) \vert\_{t=0} = (b, \nabla F(a))\_E $$ and using our relation of the skew symmetric form to the euclidean inner product, we have $$ b \cdot DF(a) = (b, J DF(a))\_E $$ These two are equal, and if they are equal for all $b$, this implies $$ J DF(a) = \nabla F(a) $$ $J$ is invertible, so we see that $ DF(a) = J^{-1} \nabla F(a)$. Summarizing, $$ F(a+b) = F(a) + b \cdot (J^{-1} \nabla F(a)) + \mathcal{O}(t^2) $$
$\def\va{{\bf a}} \def\vb{{\bf b}} \def\vc{{\bf c}} \def\vd{{\bf d}} \def\e{\varepsilon} \def\np{\odot}$We have \begin{align\*} f(\va+\vb,\vc,\vd) &= f(\va,\vc,\vd) + \sum\_i b\_i\left.\frac{\partial f(\va+\vb,\vc,\vd)}{\partial b\_i}\right|\_{b\_i=0} + \ldots \\ &= f(\va,\vc,\vd) + \sum\_i b\_i \frac{\partial f(\va,\vc,\vd)}{\partial a\_i} + \ldots \\ &= f(\va,\vc,\vd) + (\vb,\nabla\_\va f(\va,\vc,\vd)) + \ldots, \end{align\*} where $(,)$ is the usual inner product and where $\nabla\_\va f = \langle \partial f/\partial a\_1,\partial f/\partial a\_2\rangle$ is the gradient. But $(\langle a\_1,a\_2\rangle,\langle b\_1,b\_2\rangle) = \langle a\_1,a\_2\rangle\np\langle -b\_2,b\_1\rangle$. (To avoid confusion with the dot product we will write $\va\np\vb=a\_1b\_2-a\_2b\_1$.) Thus, \begin{align\*} f(\va+\vb,\vc,\vd) &= f(\va,\vc,\vd) + \vb\np \widetilde\nabla\_\va f(\va,\vc,\vd) + \ldots, \end{align\*} where $\widetilde\nabla\_\va f = \langle -\partial f/\partial a\_2,\partial f/\partial a\_1\rangle$. **Addendum** As is discussed in detail in the other answers, the product $\va\np\vb$ is only a "scalar product" in the sense that it is a product of vectors returning a real value.
74,020,294
From a dos prompt if I lauch the following command ``` echo text=1>script.conf ``` in the script.conf will be written `text=` and not `text=1` How can I solve this problem? Thanks.
2022/10/10
[ "https://Stackoverflow.com/questions/74020294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16578432/" ]
I hope I've understood your question well. Try: ```py from ast import literal_eval df["experimental_properties"] = df["experimental_properties"].apply( lambda x: {d["name"]: d["property"] for d in literal_eval(x)} ) df = pd.concat([df, df.pop("experimental_properties").apply(pd.Series)], axis=1) print(df) ``` Prints: ```none Boiling Point Density 0 115.3 °C NaN 1 91 °C @ Press: 20 Torr NaN 2 58 °C @ Press: 12 Torr 0.8753 g/cm<sup>3</sup> @ Temp: 20 °C ```
Is the expected output really what you are looking for? Another way to visualise the data would be to have "name", "property", and "sourceNumber" as column names. ``` import json import pandas as pd data = [ '''[{'name': 'Boiling Point', 'property': '115.3 °C', 'sourceNumber': 1}]''', '''[{'name': 'Boiling Point', 'property': '91 °C @ Press: 20 Torr', 'sourceNumber': 1}]''', '''[{'name': 'Boiling Point', 'property': '58 °C @ Press: 12 Torr', 'sourceNumber': 1}, {'name': 'Density', 'property': '0.8753 g/cm<sup>3</sup> @ Temp: 20 °C', 'sourceNumber': 1}]'''] #Initialise a naiveList naiveList = [] #String to List for i in data: tempStringOfData = i tempStringOfData = tempStringOfData.replace("\'", "\"") tempJsonData = json.loads(tempStringOfData) naiveList.append(tempJsonData) #Initialise a List for Dictionaries newListOfDictionaries = [] for i in naiveList: for j in i: newListOfDictionaries.append(j) df = pd.DataFrame(newListOfDictionaries) print(df) ``` Which gives you ``` name property sourceNumber 0 Boiling Point 115.3 °C 1 1 Boiling Point 91 °C @ Press: 20 Torr 1 2 Boiling Point 58 °C @ Press: 12 Torr 1 3 Density 0.8753 g/cm<sup>3</sup> @ Temp: 20 °C 1 ```
242,423
So I've been asked to prove non-differentiability using this particular method, and I'm a bit lost. I'm supposed to prove that $f(x,y) = |x-y|$ is not differentiable along the $x=y$ line. To do it, I'm supposed to use this definition of differentiability: A function $f$ is called differentiable at a point $a$ in it's domain if there exists a vector $c\in\mathbb{R^{n}}$ such that: $$\lim\limits\_{\bf h \to \bf 0} \frac{f(\boldsymbol a + \boldsymbol h) - f(\boldsymbol a) - \boldsymbol c \cdot \boldsymbol h}{|h|} = 0$$ Okay, so obviously $c$ would be the gradient of $f$ at that point, and obviously it won't exist because there is an apex there, but I can't for the life of me prove that it doesn't exist. Any help would be appreciated.
2012/11/22
[ "https://math.stackexchange.com/questions/242423", "https://math.stackexchange.com", "https://math.stackexchange.com/users/50288/" ]
A subset $A$ of a set $X$ is closed with respect to a metric $d$ on $X$ precisely if every point in the closure of $A$ is in $A$. A point $a\in X$ is in the closure of $A$ if for every positive number $\varepsilon$, no matter how small, the ball of radius $\varepsilon$ centered at $a$ intersects $A$.
An alternative but very important way to define a closed subset of a metric space X is as the complement of an open subset of X. The definition of an open subset is defined here: <http://en.wikipedia.org/wiki/Open_set#Metric_spaces> You can then define a closed subset A of X as any set where it's complement X\A is open in X. This definition of closed subset of X is equivalent to Michael's definition (and as an exercise you should try to prove that the two definitions are equivalent).
65,267,593
When I execute the following simple script in PowerShell 7.1, I get the (correct) value of 3, regardless of whether the script's encoding is Latin1 or UTF8. ``` 'Bär'.length ``` This surprises me because I was under the (apparently wrong) impression that the default encoding in PowerShell 5.1 is UTF16-LE and in PowerShell 7.1 UTF-8. Because both scripts evaluate the expression to 3, I am forced to conclude that PowerShell 7.1 applies some heuristic method to infer a Script's encoding when executing it. Is my conclusion correct and is this documented somewhere?
2020/12/12
[ "https://Stackoverflow.com/questions/65267593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180275/" ]
The encoding is unrelated to this case: you are calling `string.Length` which is documented to return the number of UTF-16 code units. This roughly correlates to letters (when you ignore combining characters and high codepoints like emoji) Encoding only comes into play when converting implicitly or explicitly to/from a byte array, file, or p/invoke. It doesn’t affect how .Net stores the data backing a string. Speaking to the encoding for PS1 files, that is dependent upon version. Older versions have a fallback encoding of `Encoding.ASCII`, but will respect a BOM for UTF-16 or UTF-8. Newer versions use UTF-8 as the fallback. In at least 5.1.19041.1, loading the file `'Bär'.Length` (`27 42 C3 A4 72 27 2E 4C 65 6E 67 74 68`) and running it with `. .\Bar.ps1` will result in 4 printing. If the same file is saved as Windows-1252 (`27 42 E4 72 27 2E 4C 65 6E 67 74 68`), then it will print 3. tl;dr: `string.Length` always returns number of UTF-16 code units. PS1 files should be in UTF-8 with BOM for cross version compatibility.
I think without a BOM, PS 5 assumes ansi or windows-1252, while PS 7 assumes utf8 no bom. This file saved as ansi in notepad works in PS 5 but not perfectly in PS 7. Just like a utf8 no bom file with special characters wouldn't work perfectly in PS 5. A utf16 ps1 file would always have a BOM or encoding signature. A powershell string in memory would always be utf16, but a character is considered to have a length of 1 except for emoji's. If you have emacs, esc-x hexl-mode is a nice way to look at it. ``` '¿Cómo estás?' ``` ``` format-hex file.ps1 Label: C:\Users\js\foo\file.ps1 Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 27 BF 43 F3 6D 6F 20 65 73 74 E1 73 3F 27 0D 0A '¿Cómo estás?'�� ```
65,267,593
When I execute the following simple script in PowerShell 7.1, I get the (correct) value of 3, regardless of whether the script's encoding is Latin1 or UTF8. ``` 'Bär'.length ``` This surprises me because I was under the (apparently wrong) impression that the default encoding in PowerShell 5.1 is UTF16-LE and in PowerShell 7.1 UTF-8. Because both scripts evaluate the expression to 3, I am forced to conclude that PowerShell 7.1 applies some heuristic method to infer a Script's encoding when executing it. Is my conclusion correct and is this documented somewhere?
2020/12/12
[ "https://Stackoverflow.com/questions/65267593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180275/" ]
> > I was under the (apparently wrong) impression that the default encoding in PowerShell 5.1 is UTF16-LE and in PowerShell 7.1 UTF-8. > > > There are two distinct default character encodings to consider: * The **default *output* encoding** used by various cmdlets (`Out-File`, `Set-Content`) and the redirection operators (`>`, `>>`) **when *writing* a file**. + This encoding ***varies wildly across cmdlets* in *Windows PowerShell*** (PowerShell versions up to 5.1) but now - fortunately - **consistently defaults to BOM-less UTF-8 in *PowerShell [Core] v6+*** - see [this answer](https://stackoverflow.com/a/40098904/45375) for more information. + Note: This encoding is *always unrelated to the encoding of a file that data may have been read from originally*, because PowerShell does not preserve this information and never passes text as raw bytes through - text is *always* converted to .NET (`[string]`, [`System.String`](https://learn.microsoft.com/en-US/dotnet/api/System.String)) instances by PowerShell before the data is processed further. * The **default *input* encoding**, when ***reading* a file** - both *source code* read by the engine and files read by `Get-Content`, for instance, which **applies only to *files without a BOM*** (because files *with* BOMs are always properly recognized). + In the absence of a BOM: - ***Windows PowerShell*** assumes the system's **active ANSI code page**, such as Windows-1252 on US-English systems. Note that this means that systems with different active system locales (settings for non-Unicode applications) can interpret a given file *differently*. - ***PowerShell [Core] v6+*** more sensibly assumes **UTF-8**, which is capable of representing *all* Unicode characters and whose interpretation doesn't depend on system settings. + Note that these are fixed, deterministic assumptions - **no heuristic is employed**. + The upshot is that **for *cross-edition* source code** the best encoding to use is **UTF-8 *with BOM***, which both editions recognize properly. --- **As for a source-code file containing `'Bär'.length`**: *If* the source-code file's encoding is properly recognized, the result is always `3`, given that a .NET string instance (`[string]`, [`System.String`](https://learn.microsoft.com/en-US/dotnet/api/System.String)) is constructed, which *in memory* is always composed of UTF-16 code units (`[char]`, [`System.Char`](https://learn.microsoft.com/en-US/dotnet/api/System.Char)), and given that `.Length` counts the number of these code units.[1] Leaving broken files out of the picture (such as a UTF-16 file without a BOM, or a file with a BOM that doesn't match the actual encoding): The only scenario in which `.Length` does *not* return `3` is: * In *Windows PowerShell*, if the file was saved as a UTF-8 file *without a BOM*. + Since ANSI code pages use a fixed-width single-byte encoding, each byte that is part of a UTF-8 byte *sequence* is *individually* (mis-)interpreted as a character, and since `ä` (LATIN SMALL LETTER A WITH DIAERESIS, [`U+00E4`](http://www.fileformat.info/info/unicode/char/e4)) is encoded as *2* bytes in UTF-8, `0xc3` and `0xa4`, the resulting string has *4* characters. + Thus, the string renders as `Bär` * By contrast, in *PowerShell [Core] v6+*, a BOM-less file that was saved based on the active ANSI (or OEM code) page (e.g., with `Set-Content` in *Windows PowerShell*) causes all non-ASCII characters (in the 8-bit range) to be considered *invalid* characters - because they cannot be interpreted as UTF-8. + All such invalid characters are simply replaced with `�` (REPLACEMENT CHARACTER, [`U+FFFD`](http://www.fileformat.info/info/unicode/char/fffd)) - in other words: *information is lost*. + Thus, the string renders as `B�r` - and its `.Length` is still `3`. --- [1] A single UTF-16 code unit is capable of directly encoding all 65K characters in the so-called BMP (Basic Multi-Lingual Plane) of Unicode, but for characters outside this plane *pairs* of code units encode a single Unicode character. The upshot: `.Length` doesn't *always* return the count of *characters*, notably not with emoji; e.g., `''.length` is *2*
The encoding is unrelated to this case: you are calling `string.Length` which is documented to return the number of UTF-16 code units. This roughly correlates to letters (when you ignore combining characters and high codepoints like emoji) Encoding only comes into play when converting implicitly or explicitly to/from a byte array, file, or p/invoke. It doesn’t affect how .Net stores the data backing a string. Speaking to the encoding for PS1 files, that is dependent upon version. Older versions have a fallback encoding of `Encoding.ASCII`, but will respect a BOM for UTF-16 or UTF-8. Newer versions use UTF-8 as the fallback. In at least 5.1.19041.1, loading the file `'Bär'.Length` (`27 42 C3 A4 72 27 2E 4C 65 6E 67 74 68`) and running it with `. .\Bar.ps1` will result in 4 printing. If the same file is saved as Windows-1252 (`27 42 E4 72 27 2E 4C 65 6E 67 74 68`), then it will print 3. tl;dr: `string.Length` always returns number of UTF-16 code units. PS1 files should be in UTF-8 with BOM for cross version compatibility.
65,267,593
When I execute the following simple script in PowerShell 7.1, I get the (correct) value of 3, regardless of whether the script's encoding is Latin1 or UTF8. ``` 'Bär'.length ``` This surprises me because I was under the (apparently wrong) impression that the default encoding in PowerShell 5.1 is UTF16-LE and in PowerShell 7.1 UTF-8. Because both scripts evaluate the expression to 3, I am forced to conclude that PowerShell 7.1 applies some heuristic method to infer a Script's encoding when executing it. Is my conclusion correct and is this documented somewhere?
2020/12/12
[ "https://Stackoverflow.com/questions/65267593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180275/" ]
> > I was under the (apparently wrong) impression that the default encoding in PowerShell 5.1 is UTF16-LE and in PowerShell 7.1 UTF-8. > > > There are two distinct default character encodings to consider: * The **default *output* encoding** used by various cmdlets (`Out-File`, `Set-Content`) and the redirection operators (`>`, `>>`) **when *writing* a file**. + This encoding ***varies wildly across cmdlets* in *Windows PowerShell*** (PowerShell versions up to 5.1) but now - fortunately - **consistently defaults to BOM-less UTF-8 in *PowerShell [Core] v6+*** - see [this answer](https://stackoverflow.com/a/40098904/45375) for more information. + Note: This encoding is *always unrelated to the encoding of a file that data may have been read from originally*, because PowerShell does not preserve this information and never passes text as raw bytes through - text is *always* converted to .NET (`[string]`, [`System.String`](https://learn.microsoft.com/en-US/dotnet/api/System.String)) instances by PowerShell before the data is processed further. * The **default *input* encoding**, when ***reading* a file** - both *source code* read by the engine and files read by `Get-Content`, for instance, which **applies only to *files without a BOM*** (because files *with* BOMs are always properly recognized). + In the absence of a BOM: - ***Windows PowerShell*** assumes the system's **active ANSI code page**, such as Windows-1252 on US-English systems. Note that this means that systems with different active system locales (settings for non-Unicode applications) can interpret a given file *differently*. - ***PowerShell [Core] v6+*** more sensibly assumes **UTF-8**, which is capable of representing *all* Unicode characters and whose interpretation doesn't depend on system settings. + Note that these are fixed, deterministic assumptions - **no heuristic is employed**. + The upshot is that **for *cross-edition* source code** the best encoding to use is **UTF-8 *with BOM***, which both editions recognize properly. --- **As for a source-code file containing `'Bär'.length`**: *If* the source-code file's encoding is properly recognized, the result is always `3`, given that a .NET string instance (`[string]`, [`System.String`](https://learn.microsoft.com/en-US/dotnet/api/System.String)) is constructed, which *in memory* is always composed of UTF-16 code units (`[char]`, [`System.Char`](https://learn.microsoft.com/en-US/dotnet/api/System.Char)), and given that `.Length` counts the number of these code units.[1] Leaving broken files out of the picture (such as a UTF-16 file without a BOM, or a file with a BOM that doesn't match the actual encoding): The only scenario in which `.Length` does *not* return `3` is: * In *Windows PowerShell*, if the file was saved as a UTF-8 file *without a BOM*. + Since ANSI code pages use a fixed-width single-byte encoding, each byte that is part of a UTF-8 byte *sequence* is *individually* (mis-)interpreted as a character, and since `ä` (LATIN SMALL LETTER A WITH DIAERESIS, [`U+00E4`](http://www.fileformat.info/info/unicode/char/e4)) is encoded as *2* bytes in UTF-8, `0xc3` and `0xa4`, the resulting string has *4* characters. + Thus, the string renders as `Bär` * By contrast, in *PowerShell [Core] v6+*, a BOM-less file that was saved based on the active ANSI (or OEM code) page (e.g., with `Set-Content` in *Windows PowerShell*) causes all non-ASCII characters (in the 8-bit range) to be considered *invalid* characters - because they cannot be interpreted as UTF-8. + All such invalid characters are simply replaced with `�` (REPLACEMENT CHARACTER, [`U+FFFD`](http://www.fileformat.info/info/unicode/char/fffd)) - in other words: *information is lost*. + Thus, the string renders as `B�r` - and its `.Length` is still `3`. --- [1] A single UTF-16 code unit is capable of directly encoding all 65K characters in the so-called BMP (Basic Multi-Lingual Plane) of Unicode, but for characters outside this plane *pairs* of code units encode a single Unicode character. The upshot: `.Length` doesn't *always* return the count of *characters*, notably not with emoji; e.g., `''.length` is *2*
I think without a BOM, PS 5 assumes ansi or windows-1252, while PS 7 assumes utf8 no bom. This file saved as ansi in notepad works in PS 5 but not perfectly in PS 7. Just like a utf8 no bom file with special characters wouldn't work perfectly in PS 5. A utf16 ps1 file would always have a BOM or encoding signature. A powershell string in memory would always be utf16, but a character is considered to have a length of 1 except for emoji's. If you have emacs, esc-x hexl-mode is a nice way to look at it. ``` '¿Cómo estás?' ``` ``` format-hex file.ps1 Label: C:\Users\js\foo\file.ps1 Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 27 BF 43 F3 6D 6F 20 65 73 74 E1 73 3F 27 0D 0A '¿Cómo estás?'�� ```
32,325,025
I'm reading a file and then running a for loop for each value. My script is stopping after executing the first value. The file\_detail.txt has multiple lines. But it is not proceeding to the next value. My script looks something like this -- ``` open (my $fh, "<", "$mycrdir/file_detail.txt" ); foreach(my $value = <$fh>) { chomp($value); if ($value eq "abc") { qx/"mkdir $mydir"/; func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } elsif($value eq "123") { qx/"mkdir $mydir"/; func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } } ```
2015/09/01
[ "https://Stackoverflow.com/questions/32325025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4519655/" ]
Change your `foreach` to `while`. `my $value = <$fh>` returns a single value, which is the first line of the file. `foreach` then receives that single value and loops over only that one value, after which the loop terminates without reading the next line from `$fh`.
Either use while loop as Dave mentioned or slurp the file in an array then loop over array using foreach. ``` use IO::All; my @lines = io($filename)->slurp; foreach (@lines){ #work on each line } ```
32,325,025
I'm reading a file and then running a for loop for each value. My script is stopping after executing the first value. The file\_detail.txt has multiple lines. But it is not proceeding to the next value. My script looks something like this -- ``` open (my $fh, "<", "$mycrdir/file_detail.txt" ); foreach(my $value = <$fh>) { chomp($value); if ($value eq "abc") { qx/"mkdir $mydir"/; func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } elsif($value eq "123") { qx/"mkdir $mydir"/; func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } } ```
2015/09/01
[ "https://Stackoverflow.com/questions/32325025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4519655/" ]
Your code needs: 1. use warnings; use strict; 2. error handling on `open` 3. error handling on `qx`, i.e. replace it with `system` since you do not care about the output, or better yet, with `File::Path::mkpath()` 4. change the `foreach` to a `while` 5. add an `else` clause to your loop Try this: **Input** ``` 123 456 abc def ``` **Program** ``` #!/usr/bin/env perl use strict; use warnings; use File::Path qw( make_path ); my ($mycrnum, $mydir, %envparams); $mydir = 'bar'; my $file = "foo.txt"; open (my $fh, "<", "$file") or die "Unable to open '$file' : $!"; while(my $value = <$fh>) { chomp($value); print "Value is '$value'\n"; if ($value eq "abc") { unless (-d $mydir) { make_path($mydir) or die "Unable to mkdir '$mydir'"; } func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } elsif($value eq "123") { unless (-d $mydir) { make_path($mydir) or die "Unable to mkdir '$mydir'"; } func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } else { print "Don't know what to do with line '$value'\n"; } } sub func1 { print "You called func1\n"; } sub func2 { print "You called func2\n"; } ``` **Output** ``` Value is '123' You called func1 You called func2 Value is '456' Don't know what to do with line '456' Value is 'abc' You called func1 You called func2 Value is 'def' Don't know what to do with line 'def' ```
Change your `foreach` to `while`. `my $value = <$fh>` returns a single value, which is the first line of the file. `foreach` then receives that single value and loops over only that one value, after which the loop terminates without reading the next line from `$fh`.
32,325,025
I'm reading a file and then running a for loop for each value. My script is stopping after executing the first value. The file\_detail.txt has multiple lines. But it is not proceeding to the next value. My script looks something like this -- ``` open (my $fh, "<", "$mycrdir/file_detail.txt" ); foreach(my $value = <$fh>) { chomp($value); if ($value eq "abc") { qx/"mkdir $mydir"/; func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } elsif($value eq "123") { qx/"mkdir $mydir"/; func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } } ```
2015/09/01
[ "https://Stackoverflow.com/questions/32325025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4519655/" ]
Change your `foreach` to `while`. `my $value = <$fh>` returns a single value, which is the first line of the file. `foreach` then receives that single value and loops over only that one value, after which the loop terminates without reading the next line from `$fh`.
Maybe, here is an other solution, if I mean well the problem ... ``` open FH, "$mycrdir/file_detail.txt" || die $!; while(<$FH>) { chomp; if (/^abc$/) { ... } elsif(/^123$/) { ... } } close FH; ```
32,325,025
I'm reading a file and then running a for loop for each value. My script is stopping after executing the first value. The file\_detail.txt has multiple lines. But it is not proceeding to the next value. My script looks something like this -- ``` open (my $fh, "<", "$mycrdir/file_detail.txt" ); foreach(my $value = <$fh>) { chomp($value); if ($value eq "abc") { qx/"mkdir $mydir"/; func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } elsif($value eq "123") { qx/"mkdir $mydir"/; func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } } ```
2015/09/01
[ "https://Stackoverflow.com/questions/32325025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4519655/" ]
Your code needs: 1. use warnings; use strict; 2. error handling on `open` 3. error handling on `qx`, i.e. replace it with `system` since you do not care about the output, or better yet, with `File::Path::mkpath()` 4. change the `foreach` to a `while` 5. add an `else` clause to your loop Try this: **Input** ``` 123 456 abc def ``` **Program** ``` #!/usr/bin/env perl use strict; use warnings; use File::Path qw( make_path ); my ($mycrnum, $mydir, %envparams); $mydir = 'bar'; my $file = "foo.txt"; open (my $fh, "<", "$file") or die "Unable to open '$file' : $!"; while(my $value = <$fh>) { chomp($value); print "Value is '$value'\n"; if ($value eq "abc") { unless (-d $mydir) { make_path($mydir) or die "Unable to mkdir '$mydir'"; } func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } elsif($value eq "123") { unless (-d $mydir) { make_path($mydir) or die "Unable to mkdir '$mydir'"; } func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } else { print "Don't know what to do with line '$value'\n"; } } sub func1 { print "You called func1\n"; } sub func2 { print "You called func2\n"; } ``` **Output** ``` Value is '123' You called func1 You called func2 Value is '456' Don't know what to do with line '456' Value is 'abc' You called func1 You called func2 Value is 'def' Don't know what to do with line 'def' ```
Either use while loop as Dave mentioned or slurp the file in an array then loop over array using foreach. ``` use IO::All; my @lines = io($filename)->slurp; foreach (@lines){ #work on each line } ```
32,325,025
I'm reading a file and then running a for loop for each value. My script is stopping after executing the first value. The file\_detail.txt has multiple lines. But it is not proceeding to the next value. My script looks something like this -- ``` open (my $fh, "<", "$mycrdir/file_detail.txt" ); foreach(my $value = <$fh>) { chomp($value); if ($value eq "abc") { qx/"mkdir $mydir"/; func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } elsif($value eq "123") { qx/"mkdir $mydir"/; func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } } ```
2015/09/01
[ "https://Stackoverflow.com/questions/32325025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4519655/" ]
Your code needs: 1. use warnings; use strict; 2. error handling on `open` 3. error handling on `qx`, i.e. replace it with `system` since you do not care about the output, or better yet, with `File::Path::mkpath()` 4. change the `foreach` to a `while` 5. add an `else` clause to your loop Try this: **Input** ``` 123 456 abc def ``` **Program** ``` #!/usr/bin/env perl use strict; use warnings; use File::Path qw( make_path ); my ($mycrnum, $mydir, %envparams); $mydir = 'bar'; my $file = "foo.txt"; open (my $fh, "<", "$file") or die "Unable to open '$file' : $!"; while(my $value = <$fh>) { chomp($value); print "Value is '$value'\n"; if ($value eq "abc") { unless (-d $mydir) { make_path($mydir) or die "Unable to mkdir '$mydir'"; } func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } elsif($value eq "123") { unless (-d $mydir) { make_path($mydir) or die "Unable to mkdir '$mydir'"; } func1($mycrnum,$mydir,$value,%envparams); func2($mycrnum,$mydir,$value,%envparams); } else { print "Don't know what to do with line '$value'\n"; } } sub func1 { print "You called func1\n"; } sub func2 { print "You called func2\n"; } ``` **Output** ``` Value is '123' You called func1 You called func2 Value is '456' Don't know what to do with line '456' Value is 'abc' You called func1 You called func2 Value is 'def' Don't know what to do with line 'def' ```
Maybe, here is an other solution, if I mean well the problem ... ``` open FH, "$mycrdir/file_detail.txt" || die $!; while(<$FH>) { chomp; if (/^abc$/) { ... } elsif(/^123$/) { ... } } close FH; ```
6,114
This is inspired partly by [this question](https://mathoverflow.net/questions/5957/what-is-a-metric-space), especially Tom Leinster's answer. Let me start with some background. I apologize that this will be rather long, since I'm hoping for input from people who probably don't much about the following. Classically, there are two obvious categories whose objects are Banach spaces (let's say all Banach spaces are real for simplicity): in the first, morphisms are bounded linear maps and isomorphisms are exactly what are usually called isomorphisms of Banach spaces; in the second, morphisms are linear contractions (bounded linear maps with norm at most 1) and isomorphisms are linear isometries. These categories distinguish between the "isomorphic" and "isometric" theories of Banach spaces. Now if I'm interested in finite-dimensional spaces, then the "isomorphic" category is not rigid enough, because any two n-dimensional Banach spaces are isomorphic. But the isometric category is too rigid for most purposes. So we get more quantitative about our isomorphisms. One way to do this is with the Banach-Mazur distance. If X and Y are both n-dimensional Banach spaces, $$d(X,Y) = \inf\_T (\lVert T \rVert \lVert T^{-1} \rVert),$$ where the infimum is over all linear isomorphisms $T:X\to Y$. Then $\log d$ is a metric on the class of isometry classes of n-dimensional Banach spaces. Theorems about spaces of arbitrary dimension which include some constants independent of the dimension are characterized as "isomorphic results". One example is Kashin's theorem: There exists a constant c>0 such that for every n, $\ell\_1^n$ has a subspace X with $\dim X = m= \lfloor n/2 \rfloor$ such that $d(X,\ell\_2^m) < c$. (Here $\ell\_p^n$ denotes R^n with the $\ell\_p$ norm $\lVert x \rVert\_p = (\sum |x\_i|^p)^{1/p}$.) Thus $\ell\_1^n$ contains an n/2-dimensional subspace isomorphic to Hilbert space in a dimension-independent way. On the other hand there are "almost isometric" results, typified by Dvoretzky's theorem: There exists a function $f$ such that for every n-dimensional Banach space X and every $\varepsilon > 0$, X has a subspace Y with $\dim Y = m \ge f(\varepsilon) \log (n+1)$ such that $d(Y,\ell\_2^m) < 1+\varepsilon$. Thus any space contains subspaces, of not too small dimension, which are arbitrarily close to being isometrically Hilbert spaces. So my question, finally, is: are there natural categories in which to interpret such results? I suppose that the objects should not be individual spaces, but sequences of spaces with increasing dimensions. In particular, as the two results quoted above highlight, the sequence of n-dimensional Hilbert spaces $\ell\_2^n$ should play a distinguished role. But I have no idea what the morphisms should be to accomodate quantitative control over norms in these ways.
2009/11/19
[ "https://mathoverflow.net/questions/6114", "https://mathoverflow.net", "https://mathoverflow.net/users/1044/" ]
This is a rewording of Matthew's answer, but one can use nonstandard analysis to obtain a category that achieves what Mark wants. After taking ultrapowers, one obtains non-standard integers (ultralimits of standard integers), nonstandard finite dimensional Banach spaces (ultralimits of standard finite dimensional Banach spaces), nonstandard linear transformations (ultralimits of standard linear transformations), etc. One can then separate these non-standard objects into various classes, e.g. bounded non-standard reals (ultralimits of uniformly bounded standard reals, or equivalently non-standard reals that are bounded in magnitude by a standard real), bounded nonstandard linear transformations, poly(n)-bounded nonstandard linear transformations, polylog(n)-bounded nonstandard linear transformations, etc., where n is an unbounded nonstandard natural number (which, in practice, would be used to bound dimensions of things). Each of these form a category. Thus, for instance Kashin's theorem becomes the statement that every nonstandard Banach space of some nonstandard finite dimension N has an M-dimensional subspace which is isomorphic (in the category of bounded nonstandard linear transformations) to $\ell^2(M)$ whenever $M \leq N/2$ (or more generally when $M \leq (1-\epsilon)N$ for some standard $\epsilon > 0$. Dvoretsky's theorem is trickier. Here, I guess one needs to work with the category of almost contractions: operators whose operator norm is at most $1+o(1)$ (i.e. bounded by $1+\epsilon$ for every standard $\epsilon > 0$. Then I think the theorem says that any nonstandard finite dimensional Banach space with some nonstandard dimension N has a M-dimensional subspace that is almost isometric to $\ell^2(M)$, whenever $M = o(\log N)$. (I may have messed up the quantifiers slightly, but this is pretty close to what the nonstandard translation of things should be.)
The best solution that I can think of is one that analysts have already embraced: Use the category of linear maps, but enrich the category over itself. In other words, make $\mathrm{Hom}(X,Y)$ into a Banach space as well using operator norm. Then it isn't so bad that all $n$-dimensional Banach spaces are isomorphic. Since the isomorphisms have norms themselves, you can ask how well they are isomorphic. Strictly speaking, you can't enrich a category over itself, because that's circular. However, there is a way out of that in category theory; self-enrichment is called "internal Hom" and there are axioms for it. It is closely related to making the category into a tensor category, and finite-dimensional Banach spaces are that too. Another way of saying is this: A category in which everything is isomorphic is a groupoid, plus some non-invertible maps. That may seem unsatisfying. The $n$-dimensional Banach spaces are indeed a groupoid, but they are a normed groupoid, which is not so bad. --- Okay, that last paragraph is something that Mark already was saying, so let me make a slightly different point. Organizing objects of study into a category is a kind of justification. If it is an enriched category, then it is a relative justification: The modules of an algebra are a category over the category of vector spaces, so modules are justified relative to vector spaces. (And not just relative to sets in that case.) Sometimes the best justification is a self-justification, and that's what internal homs do for you. The categories Set and Vect are already like this. Since in the category of Banach spaces, $\mathrm{Hom}(X,Y)$ is also a Banach space, that's a self-justification in much the same spirit. I suppose that to fully capture the idea, you should introduce Banach algebras and mixed multiplication between Banach spaces. The bilinear composition of $\mathrm{Hom}(X,Y)$ and $\mathrm{Hom}(Y,X)$ is what tells you how close $X$ and $Y$ are to isometric.
6,114
This is inspired partly by [this question](https://mathoverflow.net/questions/5957/what-is-a-metric-space), especially Tom Leinster's answer. Let me start with some background. I apologize that this will be rather long, since I'm hoping for input from people who probably don't much about the following. Classically, there are two obvious categories whose objects are Banach spaces (let's say all Banach spaces are real for simplicity): in the first, morphisms are bounded linear maps and isomorphisms are exactly what are usually called isomorphisms of Banach spaces; in the second, morphisms are linear contractions (bounded linear maps with norm at most 1) and isomorphisms are linear isometries. These categories distinguish between the "isomorphic" and "isometric" theories of Banach spaces. Now if I'm interested in finite-dimensional spaces, then the "isomorphic" category is not rigid enough, because any two n-dimensional Banach spaces are isomorphic. But the isometric category is too rigid for most purposes. So we get more quantitative about our isomorphisms. One way to do this is with the Banach-Mazur distance. If X and Y are both n-dimensional Banach spaces, $$d(X,Y) = \inf\_T (\lVert T \rVert \lVert T^{-1} \rVert),$$ where the infimum is over all linear isomorphisms $T:X\to Y$. Then $\log d$ is a metric on the class of isometry classes of n-dimensional Banach spaces. Theorems about spaces of arbitrary dimension which include some constants independent of the dimension are characterized as "isomorphic results". One example is Kashin's theorem: There exists a constant c>0 such that for every n, $\ell\_1^n$ has a subspace X with $\dim X = m= \lfloor n/2 \rfloor$ such that $d(X,\ell\_2^m) < c$. (Here $\ell\_p^n$ denotes R^n with the $\ell\_p$ norm $\lVert x \rVert\_p = (\sum |x\_i|^p)^{1/p}$.) Thus $\ell\_1^n$ contains an n/2-dimensional subspace isomorphic to Hilbert space in a dimension-independent way. On the other hand there are "almost isometric" results, typified by Dvoretzky's theorem: There exists a function $f$ such that for every n-dimensional Banach space X and every $\varepsilon > 0$, X has a subspace Y with $\dim Y = m \ge f(\varepsilon) \log (n+1)$ such that $d(Y,\ell\_2^m) < 1+\varepsilon$. Thus any space contains subspaces, of not too small dimension, which are arbitrarily close to being isometrically Hilbert spaces. So my question, finally, is: are there natural categories in which to interpret such results? I suppose that the objects should not be individual spaces, but sequences of spaces with increasing dimensions. In particular, as the two results quoted above highlight, the sequence of n-dimensional Hilbert spaces $\ell\_2^n$ should play a distinguished role. But I have no idea what the morphisms should be to accomodate quantitative control over norms in these ways.
2009/11/19
[ "https://mathoverflow.net/questions/6114", "https://mathoverflow.net", "https://mathoverflow.net/users/1044/" ]
This is a rewording of Matthew's answer, but one can use nonstandard analysis to obtain a category that achieves what Mark wants. After taking ultrapowers, one obtains non-standard integers (ultralimits of standard integers), nonstandard finite dimensional Banach spaces (ultralimits of standard finite dimensional Banach spaces), nonstandard linear transformations (ultralimits of standard linear transformations), etc. One can then separate these non-standard objects into various classes, e.g. bounded non-standard reals (ultralimits of uniformly bounded standard reals, or equivalently non-standard reals that are bounded in magnitude by a standard real), bounded nonstandard linear transformations, poly(n)-bounded nonstandard linear transformations, polylog(n)-bounded nonstandard linear transformations, etc., where n is an unbounded nonstandard natural number (which, in practice, would be used to bound dimensions of things). Each of these form a category. Thus, for instance Kashin's theorem becomes the statement that every nonstandard Banach space of some nonstandard finite dimension N has an M-dimensional subspace which is isomorphic (in the category of bounded nonstandard linear transformations) to $\ell^2(M)$ whenever $M \leq N/2$ (or more generally when $M \leq (1-\epsilon)N$ for some standard $\epsilon > 0$. Dvoretsky's theorem is trickier. Here, I guess one needs to work with the category of almost contractions: operators whose operator norm is at most $1+o(1)$ (i.e. bounded by $1+\epsilon$ for every standard $\epsilon > 0$. Then I think the theorem says that any nonstandard finite dimensional Banach space with some nonstandard dimension N has a M-dimensional subspace that is almost isometric to $\ell^2(M)$, whenever $M = o(\log N)$. (I may have messed up the quantifiers slightly, but this is pretty close to what the nonstandard translation of things should be.)
A (reasonably) standard trick to convert finite-dimensional limiting type problems into single, infinite dimensional problems is to use Ultraproducts (or non-standard hulls, if you know more model theory than I do). Let $(E\_i)$ be a family of Banach spaces on an index set $I$, and let $\ell^\infty(I,E\_i)$ be the Banach space of all *bounded* families $(x\_i)\_{i\in I}$ where $x\_i\in E\_i$. Let $U$ be a non-principal ultrafilter on $I$, and consider $N\_U=\{ (x\_i)\in\ell^\infty(I,E\_i) : \lim\_{i\rightarrow U} \|x\_i\|=0 \}$. This is a closed subspace, so we can form the quotient Banach space $\ell^\infty(I,E\_i) / N\_U$. This is the *ultraproduct* on the $(E\_i)$. If $E\_i=E$ for all $i$, we get an *ultrapower* of $E$. (If you know about ultraproducts from logic, there are the obvious "normed" definitions). Heinrich has a nice paper in Crelles on this. For example, Dvoretzky's theorem now becomes: for any infinite dimensional Banach space $X$, all ultrapowers of $X$ contain an isometric copy of $\ell^2$. (Okay, so I've lost some constants). I'm not sure quite how to get this into a category theory setting, however.
15,964,051
This question is bit complex atleast for me. Well, I am working on a project and need some bit more help.. Actually i have a module , where when 1 user login he get limited data from 1 table and he update its records. That is done ! second thing, the issue : i have 5 user who will login and will work on data. but no user should get same data, like we have 1000 records. Then when 1st user login: he get 10 records from 1 - 10. 2nd user login : he get next 10 ; 11- 20. same so on.. and when next day they login ; they get records from 51. because 5 user last day worked on first 50 data records. My issue is how to achieve that 2 goals ? do i need a framework for this ? or it can be done using simple php n sql ? any support will be helpful for me. :)
2013/04/12
[ "https://Stackoverflow.com/questions/15964051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2232188/" ]
Ok. This is just a raw answer to give you a better idea. This is how you will insert the login . Consider having a table containing following fields, Table Name: Temp\_Table user, assigned\_rows\_last\_no, date\_assigned ``` <?php $con=mysqli_connect("example.com","hiren","abc123","my_db"); // These things can be included into a single file say config.php and including in every file so that you dont need to specify connection string everytime. if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //This query required to be included into the file, which is exactly after login.php $sql = mysqli_query($con,"SELECT assigned_rows_last_no FROM Temp_Table ORDER BY assigned_rows_last_no DESC LIMIT 1"); // This is because I want the last row number assigned to the user. IF ($sql == 0) // Check whether the return answer is NULL or not. { // If the result is empty than add new entry of the user with defined row number. // Suppose that current username can be retrieved from SESSION and stored into a variable. $insertquery = mysqli_query($con, "INSERT INTO Temp_Table Values ('" . $username . $"', 10, CURDATE()"); mysqli_close($con); } else { // Select the last entry of row and add 10 to it. Ex. User2 has been assigned to 11-20, table contains 20 in the row of user2, now user3 comes, this query will select the row_no, add 10 and insert again into the table (i.e. value 30 which means 21-30.) settype($sql, "int"); $sql = $sql + 10; $insertquery = mysqli_query($con, "INSERT INTO Temp_Table Values ('" . $username . $"', '" . $sql . "', CURDATE()"); mysqli_close($con); } mysqli_close($con); ?> ``` The field Date will help you to recognize the entries of today, so that you can set your logic for "There should be no duplicate entries for the same user on same day" Now, Make you own page, which check the above mentioned things, and assign the rows to the users. Note: This code will only be able to clear out the logic for you, I am not sure whether it will work in your code without any changes.
You don't need a extra framework. Simply done with php 'n' sql! Why you don't save the last edited lines (linenumbers) in a extra SQL-Table? Maybe with the username / userid.
28,260,559
In Python3 I can do (thanks to [pep 3102](https://www.python.org/dev/peps/pep-3102/)): ``` def some_fun(a, *args, log=None, verbose=0): pass ``` and be sure that if I call this with: ``` some_fun(1, 2, 3, lob=debug_log) ``` I get a type error on the unexpected keyword argument `lob`. On Python2 I cannot define `some_fun()` with keyword-only arguments after an arbitrary argument list. I have to do: ``` def some_fun(a, *args, **kw): log = kw.get("log", None) verbose = kw.get("verbose", 0) ``` this works all fine and dandy when called correctly, but I would like to get a type error just as with Python3 when I provide one or more wrong keyword arguments to `some_fun()`.
2015/02/01
[ "https://Stackoverflow.com/questions/28260559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4516363/" ]
Instead of using `.get()` to retrieve the values, use `.pop()` and check if `kw` is empty after popping all keyword-only arguments. I use a small helper function for this: ``` def check_empty_kwargs(kwargs): import inspect try: keys = kwargs.keys() assert len(keys) == 0 except AssertionError: # uncomment if you want only one of the unexpected kwargs in the msg # keys = keys[:1] msg = "{0}() got an unexpected keyword argument{1} {2}".format( inspect.stack()[1][3], # caller name 's' if len(keys) > 1 else '', ', '.join(["'{0}'".format(k) for k in keys])) raise TypeError(msg) ``` And you would use it like: ``` def some_fun(a, *args, **kw): log = kw.pop("log", None) verbose = kw.pop("verbose", 0) check_empty_kwargs(kw) ``` calling that with (assuming `debug_log` is defined) ``` some_fun(1, 2, 3, lob=debug_log) .... TypeError: some_fun() got an unexpected keyword argument 'lob' ``` The traceback will (of course) be different from Python3
You can check against allowed keys, eg: ``` def f(a, *args, **kwargs): surplus = set(kwargs).difference(('log', 'foo', 'bar')) if surplus: raise TypeError('got unexpected keyword argument(s): ' + ', '.join(surplus)) ```
28,260,559
In Python3 I can do (thanks to [pep 3102](https://www.python.org/dev/peps/pep-3102/)): ``` def some_fun(a, *args, log=None, verbose=0): pass ``` and be sure that if I call this with: ``` some_fun(1, 2, 3, lob=debug_log) ``` I get a type error on the unexpected keyword argument `lob`. On Python2 I cannot define `some_fun()` with keyword-only arguments after an arbitrary argument list. I have to do: ``` def some_fun(a, *args, **kw): log = kw.get("log", None) verbose = kw.get("verbose", 0) ``` this works all fine and dandy when called correctly, but I would like to get a type error just as with Python3 when I provide one or more wrong keyword arguments to `some_fun()`.
2015/02/01
[ "https://Stackoverflow.com/questions/28260559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4516363/" ]
Instead of using `.get()` to retrieve the values, use `.pop()` and check if `kw` is empty after popping all keyword-only arguments. I use a small helper function for this: ``` def check_empty_kwargs(kwargs): import inspect try: keys = kwargs.keys() assert len(keys) == 0 except AssertionError: # uncomment if you want only one of the unexpected kwargs in the msg # keys = keys[:1] msg = "{0}() got an unexpected keyword argument{1} {2}".format( inspect.stack()[1][3], # caller name 's' if len(keys) > 1 else '', ', '.join(["'{0}'".format(k) for k in keys])) raise TypeError(msg) ``` And you would use it like: ``` def some_fun(a, *args, **kw): log = kw.pop("log", None) verbose = kw.pop("verbose", 0) check_empty_kwargs(kw) ``` calling that with (assuming `debug_log` is defined) ``` some_fun(1, 2, 3, lob=debug_log) .... TypeError: some_fun() got an unexpected keyword argument 'lob' ``` The traceback will (of course) be different from Python3
If you have a bunch of processing steps, you can combine the above techniques with another one: ``` def f(a, *args, **kwargs): # we allow xyz, a, b xyz = kwargs.pop('xyz', 1) # now xyz must be gone, so we can only have a and/or b others = (lambda a=1, b=2: (a, b)(**kwargs)) # either that was ok or it failed return xyz, others ```
23,754,814
I'm attempting to implement a circular queue class in Java. And in doing so I had to created a node class to group together elements and pointers to the next node. Being circular, the nodes need to be able to point to themselves. However when I go to compile the code below, the compiler (javac) is telling me I'm doing something wrong with my constructors (namely lines 5 and 8) giving the error of the question's namesake, and I cannot figure out why it isn't working. Any help and explanation of why my usage is incorrect is appreciated. ``` public class Node<Key>{ private Key key; private Node<Key> next; public Node(){ this(null, this); } public Node(Key k){ this(k, this); } public Node(Key k, Node<Key> node){ key = k; next = node; } public boolean isEmpty(){return key == null;} public Key getKey(){return key;} public void setKey(Key k){key = k;} public Node<Key> getNext(){return next;} public void setNext(Node<Key> n){next = n;} } ```
2014/05/20
[ "https://Stackoverflow.com/questions/23754814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The compile error is ``` Cannot refer to 'this' nor 'super' while explicitly invoking a constructor ``` Basically, you cannot use "`this`" from inside "`this(...)`"
You dont need to pass it in all cases. since you can refer to it in the other construtor
23,754,814
I'm attempting to implement a circular queue class in Java. And in doing so I had to created a node class to group together elements and pointers to the next node. Being circular, the nodes need to be able to point to themselves. However when I go to compile the code below, the compiler (javac) is telling me I'm doing something wrong with my constructors (namely lines 5 and 8) giving the error of the question's namesake, and I cannot figure out why it isn't working. Any help and explanation of why my usage is incorrect is appreciated. ``` public class Node<Key>{ private Key key; private Node<Key> next; public Node(){ this(null, this); } public Node(Key k){ this(k, this); } public Node(Key k, Node<Key> node){ key = k; next = node; } public boolean isEmpty(){return key == null;} public Key getKey(){return key;} public void setKey(Key k){key = k;} public Node<Key> getNext(){return next;} public void setNext(Node<Key> n){next = n;} } ```
2014/05/20
[ "https://Stackoverflow.com/questions/23754814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You cannot refer tho this (or super) in a constructor, so you should change your code like this: ``` public class Node<Key>{ private Key key; private Node<Key> next; public Node(){ key = null; next = this; } public Node(final Key k){ key = null; next = this; } public Node(final Key k, final Node<Key> node){ key = k; next = node; } public boolean isEmpty(){return key == null;} public Key getKey(){return key;} public void setKey(final Key k){key = k;} public Node<Key> getNext(){return next;} public void setNext(final Node<Key> n){next = n;} } ```
The compile error is ``` Cannot refer to 'this' nor 'super' while explicitly invoking a constructor ``` Basically, you cannot use "`this`" from inside "`this(...)`"
23,754,814
I'm attempting to implement a circular queue class in Java. And in doing so I had to created a node class to group together elements and pointers to the next node. Being circular, the nodes need to be able to point to themselves. However when I go to compile the code below, the compiler (javac) is telling me I'm doing something wrong with my constructors (namely lines 5 and 8) giving the error of the question's namesake, and I cannot figure out why it isn't working. Any help and explanation of why my usage is incorrect is appreciated. ``` public class Node<Key>{ private Key key; private Node<Key> next; public Node(){ this(null, this); } public Node(Key k){ this(k, this); } public Node(Key k, Node<Key> node){ key = k; next = node; } public boolean isEmpty(){return key == null;} public Key getKey(){return key;} public void setKey(Key k){key = k;} public Node<Key> getNext(){return next;} public void setNext(Node<Key> n){next = n;} } ```
2014/05/20
[ "https://Stackoverflow.com/questions/23754814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The compile error is ``` Cannot refer to 'this' nor 'super' while explicitly invoking a constructor ``` Basically, you cannot use "`this`" from inside "`this(...)`"
Can not pass "this" as a parameter to call the constructor.
23,754,814
I'm attempting to implement a circular queue class in Java. And in doing so I had to created a node class to group together elements and pointers to the next node. Being circular, the nodes need to be able to point to themselves. However when I go to compile the code below, the compiler (javac) is telling me I'm doing something wrong with my constructors (namely lines 5 and 8) giving the error of the question's namesake, and I cannot figure out why it isn't working. Any help and explanation of why my usage is incorrect is appreciated. ``` public class Node<Key>{ private Key key; private Node<Key> next; public Node(){ this(null, this); } public Node(Key k){ this(k, this); } public Node(Key k, Node<Key> node){ key = k; next = node; } public boolean isEmpty(){return key == null;} public Key getKey(){return key;} public void setKey(Key k){key = k;} public Node<Key> getNext(){return next;} public void setNext(Node<Key> n){next = n;} } ```
2014/05/20
[ "https://Stackoverflow.com/questions/23754814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You cannot refer tho this (or super) in a constructor, so you should change your code like this: ``` public class Node<Key>{ private Key key; private Node<Key> next; public Node(){ key = null; next = this; } public Node(final Key k){ key = null; next = this; } public Node(final Key k, final Node<Key> node){ key = k; next = node; } public boolean isEmpty(){return key == null;} public Key getKey(){return key;} public void setKey(final Key k){key = k;} public Node<Key> getNext(){return next;} public void setNext(final Node<Key> n){next = n;} } ```
You dont need to pass it in all cases. since you can refer to it in the other construtor
23,754,814
I'm attempting to implement a circular queue class in Java. And in doing so I had to created a node class to group together elements and pointers to the next node. Being circular, the nodes need to be able to point to themselves. However when I go to compile the code below, the compiler (javac) is telling me I'm doing something wrong with my constructors (namely lines 5 and 8) giving the error of the question's namesake, and I cannot figure out why it isn't working. Any help and explanation of why my usage is incorrect is appreciated. ``` public class Node<Key>{ private Key key; private Node<Key> next; public Node(){ this(null, this); } public Node(Key k){ this(k, this); } public Node(Key k, Node<Key> node){ key = k; next = node; } public boolean isEmpty(){return key == null;} public Key getKey(){return key;} public void setKey(Key k){key = k;} public Node<Key> getNext(){return next;} public void setNext(Node<Key> n){next = n;} } ```
2014/05/20
[ "https://Stackoverflow.com/questions/23754814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You cannot refer tho this (or super) in a constructor, so you should change your code like this: ``` public class Node<Key>{ private Key key; private Node<Key> next; public Node(){ key = null; next = this; } public Node(final Key k){ key = null; next = this; } public Node(final Key k, final Node<Key> node){ key = k; next = node; } public boolean isEmpty(){return key == null;} public Key getKey(){return key;} public void setKey(final Key k){key = k;} public Node<Key> getNext(){return next;} public void setNext(final Node<Key> n){next = n;} } ```
Can not pass "this" as a parameter to call the constructor.