qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
64,923,873 | So to give a little context im using expo-firebase-analytics (latest version) on Expo (27) and im trying to activate setDebugModeEnabled so that i can use the debugView on firebase analytics.
The problem is that when running it i get the following warning
>
> The method or property expo-firebase-analytics.setDebugModeEnabled is not available on ios, are you sure you've linked all the native dependencies properly?]
>
>
>
I havent found any information about it on the web | 2020/11/20 | [
"https://Stackoverflow.com/questions/64923873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11710240/"
] | Ok so i tried to reproduce the issue.It seems ("even though it seemed obvious") that its not available for a reason on ios. but it is in android. if you use an android device it shoudl work seamlesly | if you check on the exports is the function there? |
380,289 | I want to build a digital terrain model from nautical charts. I need to capture the points where depth is indicated in the chart, and for each point, I must attribute the depth value. One by one, to be sure I capture all points and give the right value. And left a marker on the points to indicate which was already digitized. Below an example of a nautical chart. Blue is water, light brown is land, numbers are depth.
[](https://i.stack.imgur.com/AjF4W.png)
I found tools to digitize points, lines and plots. But didn't find how to attribute values manually to the digitized points. | 2020/11/26 | [
"https://gis.stackexchange.com/questions/380289",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/171036/"
] | So you created a points layer and already set a few points, right? As I guess from your question, you have not yet defined any attribute fields. So you should add a field for the values you want to enter (depth). Right click your layer > open attribute table field calculator: [](https://i.stack.imgur.com/6KNRV.png). In the opening dialogue, set a name for the field, field data type (like integer or real). You have to give a default input to create the field. You could just type NULL or introduce a value that appears often. Click OK. Now, your field is created. You can now fill in the values for each item (be sure to be in edit mode).
[](https://i.stack.imgur.com/jrPOc.png) | In case you haven't got your vector file yet:
First create a new layer. You want a vector file, shapefiles are most commonly used.
[](https://i.stack.imgur.com/H790q.png)
Make sure to select Points for Geometry type and fill in Depth or something similar as name for the new field. As Type chose 'Decimal number'. Click on add to Field List and save.
[](https://i.stack.imgur.com/EH2rf.png)
In case you already have a shapefile or other vector file:
1. Open attribute table (F6) and make sure the layer is editable (pencil).
2. New Field (ctrl+w).
3. Fill in Depth or something similar as name for the new field.
4. As Type chose 'Decimal number'.
[](https://i.stack.imgur.com/pSSXB.png)
Now when you digitise a new point, it will ask for a depth and you can fill it in manually. |
380,289 | I want to build a digital terrain model from nautical charts. I need to capture the points where depth is indicated in the chart, and for each point, I must attribute the depth value. One by one, to be sure I capture all points and give the right value. And left a marker on the points to indicate which was already digitized. Below an example of a nautical chart. Blue is water, light brown is land, numbers are depth.
[](https://i.stack.imgur.com/AjF4W.png)
I found tools to digitize points, lines and plots. But didn't find how to attribute values manually to the digitized points. | 2020/11/26 | [
"https://gis.stackexchange.com/questions/380289",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/171036/"
] | So you created a points layer and already set a few points, right? As I guess from your question, you have not yet defined any attribute fields. So you should add a field for the values you want to enter (depth). Right click your layer > open attribute table field calculator: [](https://i.stack.imgur.com/6KNRV.png). In the opening dialogue, set a name for the field, field data type (like integer or real). You have to give a default input to create the field. You could just type NULL or introduce a value that appears often. Click OK. Now, your field is created. You can now fill in the values for each item (be sure to be in edit mode).
[](https://i.stack.imgur.com/jrPOc.png) | I got it!
But, maybe I found a bug.
Part 1 - The (expected) right way...
a) with a layer, create a new shapefile layer
b) using the Field Calculator, create a new field... get some points
c) export the shapefile as CSV with geometry AS\_XY
d) done!
But this is not working! When I do this, I got only the fields but not the coordinates.
For a test, here is the Attribute table
[](https://i.stack.imgur.com/ahK64.png)
Here is how I'm exporting it
[](https://i.stack.imgur.com/ypzbx.png)
This is what I got
[](https://i.stack.imgur.com/yiWSH.png)
But... when I created the longitude and latitude fields (described below), this is the attributed table
[](https://i.stack.imgur.com/lNnO0.png)
And exporting it exactly the same way above, I got this
[](https://i.stack.imgur.com/EPCSk.png)
I thought that was too stupid I couldn't get the coordinates just exporting the CSV and asking for the geometry. But it was not working... It only works after a create the fields!
Part 2 - The turnaround
After assessing the problem and consulting youtube, forum, etc... I finally got what I need, that is to visualize the longitude, latitude, and depth in the Attribute table. Sort of useless thing... but!
So, here an explanation for those who are not QGIS frequent users like myself.
(you already have your nautical chart layer...)
1 - create a new shapefile layer (multipoint!)
2 - using the Field Calculator tool (the abacus!), create the fields as described above... but before you set the 'depth' field, that I need to type manually after getting the points,
3 - "Create a new field" **AND MARK THE OPTION** "Create virtual field"
4 - Name it (as it going to be Longitude, just 'x'...)
5 - Change output field type to 'decimal number'
6 - Here is the trick! In the 'expression' aba, the middle column is a list of things (I don't know how they call them... packages?). Click in the black arrow to expand and will appear a list of 'functions'(?). Scroll down until you find '$x'. Double click on it and it will be inserted in the left box. Click 'OK'. This will deliver the longitude...
7 - Repeat the process to create a second field for latitude...
8 - Create the field 'depth' or whatever you want to prescribe during the point captures, using 'NULL' in the left box.
9 - (bonus) To change the order of fields in the table ([Changing column order in QGIS?](https://gis.stackexchange.com/questions/322741/changing-column-order-in-qgis))
10 - (bonus) If you don't see the table like below, don't panic! At the bottom/right of the Attribute Table there are two buttons that switch between 'table' and 'item list'
[](https://i.stack.imgur.com/uhysz.jpg) |
380,289 | I want to build a digital terrain model from nautical charts. I need to capture the points where depth is indicated in the chart, and for each point, I must attribute the depth value. One by one, to be sure I capture all points and give the right value. And left a marker on the points to indicate which was already digitized. Below an example of a nautical chart. Blue is water, light brown is land, numbers are depth.
[](https://i.stack.imgur.com/AjF4W.png)
I found tools to digitize points, lines and plots. But didn't find how to attribute values manually to the digitized points. | 2020/11/26 | [
"https://gis.stackexchange.com/questions/380289",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/171036/"
] | In case you haven't got your vector file yet:
First create a new layer. You want a vector file, shapefiles are most commonly used.
[](https://i.stack.imgur.com/H790q.png)
Make sure to select Points for Geometry type and fill in Depth or something similar as name for the new field. As Type chose 'Decimal number'. Click on add to Field List and save.
[](https://i.stack.imgur.com/EH2rf.png)
In case you already have a shapefile or other vector file:
1. Open attribute table (F6) and make sure the layer is editable (pencil).
2. New Field (ctrl+w).
3. Fill in Depth or something similar as name for the new field.
4. As Type chose 'Decimal number'.
[](https://i.stack.imgur.com/pSSXB.png)
Now when you digitise a new point, it will ask for a depth and you can fill it in manually. | I got it!
But, maybe I found a bug.
Part 1 - The (expected) right way...
a) with a layer, create a new shapefile layer
b) using the Field Calculator, create a new field... get some points
c) export the shapefile as CSV with geometry AS\_XY
d) done!
But this is not working! When I do this, I got only the fields but not the coordinates.
For a test, here is the Attribute table
[](https://i.stack.imgur.com/ahK64.png)
Here is how I'm exporting it
[](https://i.stack.imgur.com/ypzbx.png)
This is what I got
[](https://i.stack.imgur.com/yiWSH.png)
But... when I created the longitude and latitude fields (described below), this is the attributed table
[](https://i.stack.imgur.com/lNnO0.png)
And exporting it exactly the same way above, I got this
[](https://i.stack.imgur.com/EPCSk.png)
I thought that was too stupid I couldn't get the coordinates just exporting the CSV and asking for the geometry. But it was not working... It only works after a create the fields!
Part 2 - The turnaround
After assessing the problem and consulting youtube, forum, etc... I finally got what I need, that is to visualize the longitude, latitude, and depth in the Attribute table. Sort of useless thing... but!
So, here an explanation for those who are not QGIS frequent users like myself.
(you already have your nautical chart layer...)
1 - create a new shapefile layer (multipoint!)
2 - using the Field Calculator tool (the abacus!), create the fields as described above... but before you set the 'depth' field, that I need to type manually after getting the points,
3 - "Create a new field" **AND MARK THE OPTION** "Create virtual field"
4 - Name it (as it going to be Longitude, just 'x'...)
5 - Change output field type to 'decimal number'
6 - Here is the trick! In the 'expression' aba, the middle column is a list of things (I don't know how they call them... packages?). Click in the black arrow to expand and will appear a list of 'functions'(?). Scroll down until you find '$x'. Double click on it and it will be inserted in the left box. Click 'OK'. This will deliver the longitude...
7 - Repeat the process to create a second field for latitude...
8 - Create the field 'depth' or whatever you want to prescribe during the point captures, using 'NULL' in the left box.
9 - (bonus) To change the order of fields in the table ([Changing column order in QGIS?](https://gis.stackexchange.com/questions/322741/changing-column-order-in-qgis))
10 - (bonus) If you don't see the table like below, don't panic! At the bottom/right of the Attribute Table there are two buttons that switch between 'table' and 'item list'
[](https://i.stack.imgur.com/uhysz.jpg) |
70,384,470 | I already have SUMO, OMNET++ and Veins running on my machine, but I am new to Veins. I would like to run Python scripts using Veins framework.
Let us say in the Python script we are given two objects `object_A` and `object_B` that contain data about the corresponding cars `car_A` and `car_B`. I would like to enable some exchange of information between the `object_A` and `object_B` based on the scenario happening in Veins. Could somebody explain to me, how can I accomplish my goal or point me to the corresponding literature?
I found [this repository](https://github.com/veins/veins_python) where Python and Veins are combined, but I cannot make sense of it.
Thank you! | 2021/12/16 | [
"https://Stackoverflow.com/questions/70384470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452880/"
] | I would use [Jackson](https://github.com/FasterXML/jackson) for that job:
```
private static final ObjectMapper MAPPER = new ObjectMapper();
public static String getFirstId(String json) throws JsonProcessingException {
return MAPPER.readTree(json).get("accommodations").get(0).get("id").asText();
}
```
Then you can do:
```
System.out.println(getFirstId(json));
```
Output:
```
00000000031000000067
```
If you want to print de `JSON` as a tree you can do:
```
public static String toTree(String json) throws JsonProcessingException {
return MAPPER.readTree(json).toPrettyString();
}
```
Then you can do:
```
System.out.println(toTree(json));
```
Output:
```
{
"isCompany" : false,
"accommodations" : [ {
"id" : "00000000031000000067",
"isChecked" : false,
"name" : "5 JULI 2017",
"addressLine1" : "STRAAT 10 ",
"addressLine2" : "1000 New York",
"nightsDeclared" : 0,
"schoolNightsDeclared" : 0,
"schoolNightsAttached" : 0,
"taxableNights" : 0.0,
"totalPayment" : 0.0,
"isInProgress" : false,
"isLate" : false,
"isPayed" : "false",
"deadline" : "2021-12-31",
"initialAmount" : 0.0,
"remainingAmount" : 0.0
}, {
"id" : "00000000031000006362",
"isChecked" : false,
"name" : "BELLEVIE",
"addressLine1" : "STRAAT 10 ",
"addressLine2" : "1000 New York",
"nightsDeclared" : 0,
"schoolNightsDeclared" : 0,
"schoolNightsAttached" : 0,
"taxableNights" : 0.0,
"totalPayment" : 0.0,
"isInProgress" : false,
"isLate" : false,
"isPayed" : "false",
"deadline" : "2021-12-31",
"initialAmount" : 0.0,
"remainingAmount" : 0.0
} ]
}
``` | I would recommend using circe to parse the JsonString and there are two ways to do this:
1. requires you to add the following packages to your sbt build:
```
val core = "io.circe" %% "circe-core" % circeVersion
val generic = "io.circe" %% "circe-generic" % circeVersion
val parser = "io.circe" %% "circe-parser" % circeVersion
addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.1" cross CrossVersion.full),
```
This method uses case classes and field fetching in order to get your desired objects. The Case classes can be defined specifically the fields you want or express the whole json object as documentation. This solution gives you a lot of flexibility but requires a lot of boiler plate
```scala
// SOLUTION 1:
import io.circe.parser.decode
import io.circe.generic.JsonCodec
/**
* First Build two case classes to represent
* the JSON object that you will be parsing to
*/
@JsonCodec
case class Accommodation(id: String)
@JsonCodec
case class Response(isCompany: Boolean, accommodations: List[Accommodation]) {
def getFirstAccomodationID: Option[String] = {
this.accommodations.headOption match {
case Some(accommodation) => Some(accommodation.id)
case _ => None
}
}
}
/* In order to actually pull the data */
val response: Either[io.circe.Error,Response] = decode[Response](jsonString)
println(response.right.get.getFirstAccomodationID)
```
2. Requires you to add the following packages
```
val core = "io.circe" %% "circe-core" % circeVersion
val generic = "io.circe" %% "circe-generic" % circeVersion
val parser = "io.circe" %% "circe-parser" % circeVersion
val optics = "io.circe" %% "circe-optics" % circeVersion
```
This solution uses json parsing and traversal to get to the exact fields you want and allows you to specify exactly what fields you want.
This solution is also more compact and easier to reason with for someone reading the code.
```scala
// SOLUTION 2:
import io.circe._,
import io.circe.parser._
/* First convert the String into a JSON object */
val json: Json = parse(jsonString).getOrElse(Json.Null)
import io.circe.optics.JsonPath._
/* Use Circe Optics to define the json path you wish to traverse */
val _getFirstAccomodationID = root.accommodations.each.id.string
/* Finally, fetch the actual String value */
val firstId: Option[String] = _getFirstAccomodationID.getAll(json).headOption
println(firstId)
``` |
70,384,470 | I already have SUMO, OMNET++ and Veins running on my machine, but I am new to Veins. I would like to run Python scripts using Veins framework.
Let us say in the Python script we are given two objects `object_A` and `object_B` that contain data about the corresponding cars `car_A` and `car_B`. I would like to enable some exchange of information between the `object_A` and `object_B` based on the scenario happening in Veins. Could somebody explain to me, how can I accomplish my goal or point me to the corresponding literature?
I found [this repository](https://github.com/veins/veins_python) where Python and Veins are combined, but I cannot make sense of it.
Thank you! | 2021/12/16 | [
"https://Stackoverflow.com/questions/70384470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452880/"
] | If your JSON is embedded inside HTML, you have 2 possibilities:
1. Use a `css` check like you've done so far to extract the JSON from the HTML and then use [`transform`](https://gatling.io/docs/gatling/reference/current/core/check/#transform) to parse the JSON and extract the desired value, eg with Jackson as suggested in the other answer
2. Use `regex` to extract the desired value in one go, eg `check(regex(""""accommodations":\[\{"id":"(.*?)""""))` | I would recommend using circe to parse the JsonString and there are two ways to do this:
1. requires you to add the following packages to your sbt build:
```
val core = "io.circe" %% "circe-core" % circeVersion
val generic = "io.circe" %% "circe-generic" % circeVersion
val parser = "io.circe" %% "circe-parser" % circeVersion
addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.1" cross CrossVersion.full),
```
This method uses case classes and field fetching in order to get your desired objects. The Case classes can be defined specifically the fields you want or express the whole json object as documentation. This solution gives you a lot of flexibility but requires a lot of boiler plate
```scala
// SOLUTION 1:
import io.circe.parser.decode
import io.circe.generic.JsonCodec
/**
* First Build two case classes to represent
* the JSON object that you will be parsing to
*/
@JsonCodec
case class Accommodation(id: String)
@JsonCodec
case class Response(isCompany: Boolean, accommodations: List[Accommodation]) {
def getFirstAccomodationID: Option[String] = {
this.accommodations.headOption match {
case Some(accommodation) => Some(accommodation.id)
case _ => None
}
}
}
/* In order to actually pull the data */
val response: Either[io.circe.Error,Response] = decode[Response](jsonString)
println(response.right.get.getFirstAccomodationID)
```
2. Requires you to add the following packages
```
val core = "io.circe" %% "circe-core" % circeVersion
val generic = "io.circe" %% "circe-generic" % circeVersion
val parser = "io.circe" %% "circe-parser" % circeVersion
val optics = "io.circe" %% "circe-optics" % circeVersion
```
This solution uses json parsing and traversal to get to the exact fields you want and allows you to specify exactly what fields you want.
This solution is also more compact and easier to reason with for someone reading the code.
```scala
// SOLUTION 2:
import io.circe._,
import io.circe.parser._
/* First convert the String into a JSON object */
val json: Json = parse(jsonString).getOrElse(Json.Null)
import io.circe.optics.JsonPath._
/* Use Circe Optics to define the json path you wish to traverse */
val _getFirstAccomodationID = root.accommodations.each.id.string
/* Finally, fetch the actual String value */
val firstId: Option[String] = _getFirstAccomodationID.getAll(json).headOption
println(firstId)
``` |
70,384,470 | I already have SUMO, OMNET++ and Veins running on my machine, but I am new to Veins. I would like to run Python scripts using Veins framework.
Let us say in the Python script we are given two objects `object_A` and `object_B` that contain data about the corresponding cars `car_A` and `car_B`. I would like to enable some exchange of information between the `object_A` and `object_B` based on the scenario happening in Veins. Could somebody explain to me, how can I accomplish my goal or point me to the corresponding literature?
I found [this repository](https://github.com/veins/veins_python) where Python and Veins are combined, but I cannot make sense of it.
Thank you! | 2021/12/16 | [
"https://Stackoverflow.com/questions/70384470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452880/"
] | This can be done in a few steps.
1. At the first need to extract only json and change response body.
2. And then you can use simple `jsonPath` and work with json
For change - use `transformResponse` where extract json string and remove break lines and set as new response body
```
http("...")
.get("...")
.transformResponse { (response, _) =>
val json = response.body.string match {
case s"""<div id="DATA--DECL-DATA">${json}</div>""" => json.replaceAll("\n", "")
}
response.copy(body = new StringResponseBody(json, response.body.charset))
}
.check(jsonPath("$...").find.saveAs("..."))
``` | I would recommend using circe to parse the JsonString and there are two ways to do this:
1. requires you to add the following packages to your sbt build:
```
val core = "io.circe" %% "circe-core" % circeVersion
val generic = "io.circe" %% "circe-generic" % circeVersion
val parser = "io.circe" %% "circe-parser" % circeVersion
addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.1" cross CrossVersion.full),
```
This method uses case classes and field fetching in order to get your desired objects. The Case classes can be defined specifically the fields you want or express the whole json object as documentation. This solution gives you a lot of flexibility but requires a lot of boiler plate
```scala
// SOLUTION 1:
import io.circe.parser.decode
import io.circe.generic.JsonCodec
/**
* First Build two case classes to represent
* the JSON object that you will be parsing to
*/
@JsonCodec
case class Accommodation(id: String)
@JsonCodec
case class Response(isCompany: Boolean, accommodations: List[Accommodation]) {
def getFirstAccomodationID: Option[String] = {
this.accommodations.headOption match {
case Some(accommodation) => Some(accommodation.id)
case _ => None
}
}
}
/* In order to actually pull the data */
val response: Either[io.circe.Error,Response] = decode[Response](jsonString)
println(response.right.get.getFirstAccomodationID)
```
2. Requires you to add the following packages
```
val core = "io.circe" %% "circe-core" % circeVersion
val generic = "io.circe" %% "circe-generic" % circeVersion
val parser = "io.circe" %% "circe-parser" % circeVersion
val optics = "io.circe" %% "circe-optics" % circeVersion
```
This solution uses json parsing and traversal to get to the exact fields you want and allows you to specify exactly what fields you want.
This solution is also more compact and easier to reason with for someone reading the code.
```scala
// SOLUTION 2:
import io.circe._,
import io.circe.parser._
/* First convert the String into a JSON object */
val json: Json = parse(jsonString).getOrElse(Json.Null)
import io.circe.optics.JsonPath._
/* Use Circe Optics to define the json path you wish to traverse */
val _getFirstAccomodationID = root.accommodations.each.id.string
/* Finally, fetch the actual String value */
val firstId: Option[String] = _getFirstAccomodationID.getAll(json).headOption
println(firstId)
``` |
26,346,700 | Rather than an Excel formula of this kind:
```
=IF(AVERAGE(A1:A4)<4,"POOR",IF(AVERAGE(A1:A4)<5,"Meet Expectation",IF(AVERAGE(A1:A4)<7,"Good",IF(AVERAGE(A1:A4)<8,"Excellent","Outstanding"))))
```
how might I achieve similar results with a lookup table? | 2014/10/13 | [
"https://Stackoverflow.com/questions/26346700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4138688/"
] | With a lookup table (and without requiring an exact match):

Where an exacct match is not found it defaults to the next lower matching value. `9` can not be found but `8` can be, hence `Outstanding`. You have not been specific about the breakpoints (eg `5` seems to be both `Meet Expectation` and `Good`) but the table is easy to adjust to suit by adding or deducting a very small amount to the number to the left of `Good`.
The table is here named `Qarray` and can be placed anywhere in the same workbook if the named range is of Workbook scope. | Formula:
========
`=IF(A1<4,"POOR",IF(AND(A1>=4,A1<5),"Meets Expectations",IF(AND(A1>=5,A1<7),"Good",IF(AND(A1>=7,A1<8),"Excellent","Outstanding"))))` |
5,884,670 | I have a WPF projet that uses the WPFMediaKit and I have realised that it runs the camera and even the MessageBox.Show() code when in visual studio editing. That wouldn't be a problem if it was only the camera that it was trying to run its doing some other stuff that crash the instant i go into design view.
Why is this happening and where can it be turned off? Is there some sort of livepreview-off switch? | 2011/05/04 | [
"https://Stackoverflow.com/questions/5884670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68438/"
] | You can't stop it, it's made so user controls can draw themselves and react smartly to the user at design time.
You can however check for the `DesignMode` property inside your control and not do the camera operations (or anything at all if you wish). | Sounds like a problem with WPFMediaKit itself. It should have been written to take the IsDesignMode property into account as Blindy pointed out... |
6,396,477 | Can anyone advise me on how I can add a "plus" button in a UITableView Cell like what you see in the screen shot below?
 | 2011/06/18 | [
"https://Stackoverflow.com/questions/6396477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683898/"
] | You can customize your cell by getting the `contentView` property of your `UITableViewCell` and adding the `UIImage` of the plus button as a subview. | That's not a built-in control. It's probably a custom-style UIButton with that image in its .image property. |
6,396,477 | Can anyone advise me on how I can add a "plus" button in a UITableView Cell like what you see in the screen shot below?
 | 2011/06/18 | [
"https://Stackoverflow.com/questions/6396477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683898/"
] | The simple way: get an image of the plus, set it for the `cell.imageView.image`. | That's not a built-in control. It's probably a custom-style UIButton with that image in its .image property. |
6,396,477 | Can anyone advise me on how I can add a "plus" button in a UITableView Cell like what you see in the screen shot below?
 | 2011/06/18 | [
"https://Stackoverflow.com/questions/6396477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683898/"
] | You can also put the table view into editing mode, implement `editingStyleForRowAtIndexPath:` and return `UITableViewCellEditingStyleInsert` (which puts a green circle with a plus sign).
For example...
```
- (IBAction)editButtonPressed
{
//toggle editing on/off...
[tableView setEditing:(!tableView.editing) animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0)
return UITableViewCellEditingStyleInsert;
//gives green circle with +
else
return UITableViewCellEditingStyleDelete;
//or UITableViewCellEditingStyleNone
}
```
When the green button is pressed, the table view will call `tableView:commitEditingStyle:forRowAtIndexPath:`:
```
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleInsert)
{
//handle insert...
}
else
{
//handle delete...
}
}
``` | That's not a built-in control. It's probably a custom-style UIButton with that image in its .image property. |
6,396,477 | Can anyone advise me on how I can add a "plus" button in a UITableView Cell like what you see in the screen shot below?
 | 2011/06/18 | [
"https://Stackoverflow.com/questions/6396477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683898/"
] | The simple way: get an image of the plus, set it for the `cell.imageView.image`. | You can customize your cell by getting the `contentView` property of your `UITableViewCell` and adding the `UIImage` of the plus button as a subview. |
6,396,477 | Can anyone advise me on how I can add a "plus" button in a UITableView Cell like what you see in the screen shot below?
 | 2011/06/18 | [
"https://Stackoverflow.com/questions/6396477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683898/"
] | You can also put the table view into editing mode, implement `editingStyleForRowAtIndexPath:` and return `UITableViewCellEditingStyleInsert` (which puts a green circle with a plus sign).
For example...
```
- (IBAction)editButtonPressed
{
//toggle editing on/off...
[tableView setEditing:(!tableView.editing) animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0)
return UITableViewCellEditingStyleInsert;
//gives green circle with +
else
return UITableViewCellEditingStyleDelete;
//or UITableViewCellEditingStyleNone
}
```
When the green button is pressed, the table view will call `tableView:commitEditingStyle:forRowAtIndexPath:`:
```
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleInsert)
{
//handle insert...
}
else
{
//handle delete...
}
}
``` | You can customize your cell by getting the `contentView` property of your `UITableViewCell` and adding the `UIImage` of the plus button as a subview. |
6,396,477 | Can anyone advise me on how I can add a "plus" button in a UITableView Cell like what you see in the screen shot below?
 | 2011/06/18 | [
"https://Stackoverflow.com/questions/6396477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683898/"
] | You can also put the table view into editing mode, implement `editingStyleForRowAtIndexPath:` and return `UITableViewCellEditingStyleInsert` (which puts a green circle with a plus sign).
For example...
```
- (IBAction)editButtonPressed
{
//toggle editing on/off...
[tableView setEditing:(!tableView.editing) animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0)
return UITableViewCellEditingStyleInsert;
//gives green circle with +
else
return UITableViewCellEditingStyleDelete;
//or UITableViewCellEditingStyleNone
}
```
When the green button is pressed, the table view will call `tableView:commitEditingStyle:forRowAtIndexPath:`:
```
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleInsert)
{
//handle insert...
}
else
{
//handle delete...
}
}
``` | The simple way: get an image of the plus, set it for the `cell.imageView.image`. |
50,357,180 | I am working on page, that gives you (based on range input) random string from array. It works by form with post method, that goes to same website, where is that form. But I ran into problems. Mostly it gives same string, as it gave before, so I would like to somehow save key from array, and compare it to new randomly picked one. Problem is, that I am beginner, and I don't know how to do that. I would be really happy, if You could help me.
Current piece of code: ($vystup stands for output, $rageFactor is input from range, $rage0 - $rage4 are arrays containing strings)
```
$rageFactor = $_POST["rageFactor"];
if ($rageFactor == "0"){
$vystup = $rage0[array_rand($rage0)];
} else if ($rageFactor == "1"){
$vystup = $rage1[array_rand($rage1)];
} else if ($rageFactor == "2"){
$vystup = $rage2[array_rand($rage2)];
} else if ($rageFactor == "3"){
$vystup = $rage3[array_rand($rage3)];
}
```
Thanks :)
//edit1
```
$rage = array("rage0", "rage1", "rage2", "rage3");
$vystup = $rage[$rageFactor][array_rand($rage[$rageFactor])];
``` | 2018/05/15 | [
"https://Stackoverflow.com/questions/50357180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6483765/"
] | You only add `x` to sum once and that's after you print it out. Move adding `x` to `sum` into the loop.
You also need to make sure you don't add the `-1` which likely acts only as a condition ending the loop and not a term you want to add. | If you want to find the sum of numbers you should add them in while loop.
So your line of code
```
sum = sum+x;
```
Should be places in do while
```
do
{
scanf("%d",&x);
sum = sum+x;
}while(x!=-1);
```
But now you added -1 in your sum and i doubt you want that, so you should add 1 to sum after do while
```
do
{
scanf("%d",&x);
sum = sum+x;
}while(x!=-1);
sum = sum+1;
```
Or instead use while loop
```
x=0;
while(x!=-1)
{
scanf("%d",&x);
sum=sum+x;
}
``` |
50,357,180 | I am working on page, that gives you (based on range input) random string from array. It works by form with post method, that goes to same website, where is that form. But I ran into problems. Mostly it gives same string, as it gave before, so I would like to somehow save key from array, and compare it to new randomly picked one. Problem is, that I am beginner, and I don't know how to do that. I would be really happy, if You could help me.
Current piece of code: ($vystup stands for output, $rageFactor is input from range, $rage0 - $rage4 are arrays containing strings)
```
$rageFactor = $_POST["rageFactor"];
if ($rageFactor == "0"){
$vystup = $rage0[array_rand($rage0)];
} else if ($rageFactor == "1"){
$vystup = $rage1[array_rand($rage1)];
} else if ($rageFactor == "2"){
$vystup = $rage2[array_rand($rage2)];
} else if ($rageFactor == "3"){
$vystup = $rage3[array_rand($rage3)];
}
```
Thanks :)
//edit1
```
$rage = array("rage0", "rage1", "rage2", "rage3");
$vystup = $rage[$rageFactor][array_rand($rage[$rageFactor])];
``` | 2018/05/15 | [
"https://Stackoverflow.com/questions/50357180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6483765/"
] | You only add `x` to sum once and that's after you print it out. Move adding `x` to `sum` into the loop.
You also need to make sure you don't add the `-1` which likely acts only as a condition ending the loop and not a term you want to add. | Building on the answer by Jacek, here is the detail to get an efficient summing without the final adding of -1 and without additional `if`:
```
int x=0;
int s=0;
/* ... */
do
{
sum = x + sum; /* first time x==0, no effect */
s=scanf_s("%d", &x); /* note scan success */
} while ((x != -1) && (s==1)); /* also quit on scan failure */
/* do not sum = x + sum; anywhere outside of the loop */
``` |
50,357,180 | I am working on page, that gives you (based on range input) random string from array. It works by form with post method, that goes to same website, where is that form. But I ran into problems. Mostly it gives same string, as it gave before, so I would like to somehow save key from array, and compare it to new randomly picked one. Problem is, that I am beginner, and I don't know how to do that. I would be really happy, if You could help me.
Current piece of code: ($vystup stands for output, $rageFactor is input from range, $rage0 - $rage4 are arrays containing strings)
```
$rageFactor = $_POST["rageFactor"];
if ($rageFactor == "0"){
$vystup = $rage0[array_rand($rage0)];
} else if ($rageFactor == "1"){
$vystup = $rage1[array_rand($rage1)];
} else if ($rageFactor == "2"){
$vystup = $rage2[array_rand($rage2)];
} else if ($rageFactor == "3"){
$vystup = $rage3[array_rand($rage3)];
}
```
Thanks :)
//edit1
```
$rage = array("rage0", "rage1", "rage2", "rage3");
$vystup = $rage[$rageFactor][array_rand($rage[$rageFactor])];
``` | 2018/05/15 | [
"https://Stackoverflow.com/questions/50357180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6483765/"
] | If you want to find the sum of numbers you should add them in while loop.
So your line of code
```
sum = sum+x;
```
Should be places in do while
```
do
{
scanf("%d",&x);
sum = sum+x;
}while(x!=-1);
```
But now you added -1 in your sum and i doubt you want that, so you should add 1 to sum after do while
```
do
{
scanf("%d",&x);
sum = sum+x;
}while(x!=-1);
sum = sum+1;
```
Or instead use while loop
```
x=0;
while(x!=-1)
{
scanf("%d",&x);
sum=sum+x;
}
``` | Building on the answer by Jacek, here is the detail to get an efficient summing without the final adding of -1 and without additional `if`:
```
int x=0;
int s=0;
/* ... */
do
{
sum = x + sum; /* first time x==0, no effect */
s=scanf_s("%d", &x); /* note scan success */
} while ((x != -1) && (s==1)); /* also quit on scan failure */
/* do not sum = x + sum; anywhere outside of the loop */
``` |
281,167 | I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing.
The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in the table that's being queried. The Access project is stored and run from a terminal server session on the actual SQL server, so I don't think it's a network issue, and there's another form which is very similar that uses the same type of querying...
Thanks
PG
```
SELECT TabDrawer.DrawerName, TabDrawer.DrawerSortCode, TabDrawer.DrawerAccountNo, TabDrawer.DrawerPostCode, QryAllTransactons.TPCChequeNumber, tabdrawer.drawerref
FROM TabDrawer LEFT JOIN QryAllTransactons ON TabDrawer.DrawerRef=QryAllTransactons.tpcdrawer
WHERE (Forms!FrmSearchCompany!SearchName Is Null
Or [drawername] Like Forms!FrmSearchCompany!SearchName & "*")
And (Forms!FrmSearchCompany.SearchPostcode Is Null
Or [Drawerpostcode] Like Forms!FrmSearchCompany!Searchpostcode & "*")
And (Forms!FrmSearchCompany!SearchSortCode Is Null
Or [drawersortcode] Like Forms!FrmSearchCompany!Searchsortcode & "*")
And (Forms!FrmSearchCompany!Searchaccount Is Null
Or [draweraccountno] Like Forms!FrmSearchCompany!Searchaccount & "*")
And (Forms!FrmSearchCompany!Searchcheque Is Null
Or [tpcchequenumber] Like Forms!FrmSearchCompany!Searchcheque & "*");
");
```
---
**EDIT**
The Hold up seems to be in the union query that forms the QryAllTransactons query.
```
SELECT
"TPC" AS Type,
TabTPC.TPCRef,
TabTPC.TPCBranch,
TabTPC.TPCDate,
TabTPC.TPCChequeNumber,
TabTPC.TPCChequeValue,
TabTPC.TPCFee,
TabTPC.TPCAction,
TabTPC.TPCMember,
tabtpc.tpcdrawer,
TabTPC.TPCUser,
TabTPC.TPCDiscount,
tabcustomers.*
FROM
TabTPC
INNER JOIN TabCustomers ON TabTPC.TPCMember = TabCustomers.CustomerID
UNION ALL
SELECT
"CTP" AS Type,
TabCTP.CTPRef,
TabCTP.CTPBranch,
TabCTP.CTPDate,
TabCTP.CTPChequeNumb,
TabCTP.CTPAmount,
TabCTP.CTPFee,
TabCTP.CTPAction,
TabCTP.CTPMember,
0 as CTPXXX,
TabCTP.CTPUser,
TabCTP.CTPDiscount,
TABCUSTOMERS.*
FROM
TabCTP
INNER JOIN TabCustomers ON Tabctp.ctpMember = TabCustomers.CustomerID;
```
I've done a fair bit of work with simple union queries, but never had this before... | 2008/11/11 | [
"https://Stackoverflow.com/questions/281167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30140/"
] | At first, try compacting and repairing the .mdb file.
Then, simplify your WHERE clause:
```
WHERE
[drawername] Like Nz(Forms!FrmSearchCompany!SearchName, "") & "*"
And
[Drawerpostcode] Like Nz(Forms!FrmSearchCompany!Searchpostcode, "") & "*"
And
[drawersortcode] Like Nz(Forms!FrmSearchCompany!Searchsortcode, "") & "*"
And
[draweraccountno] Like Nz(Forms!FrmSearchCompany!Searchaccount, "") & "*"
And
[tpcchequenumber] Like Nz(Forms!FrmSearchCompany!Searchcheque, "") & "*"
```
Does it still run slowly?
**EDIT**
As it turned out, the question was not clear in that it is an up-sized Access Database with an SQL Server back end-and an Access Project front-end.
This sheds a different light on the whole problem.
Can you explain in more detail *how* this whole query is intended to be used?
If you use it to populate the RecordSource of some Form or Report, I think you will be able to refactor the whole thing like this:
* make a view on the SQL server that returns the right data
* query that view with a SQL server syntax, not with Access syntax
* let the server sort it out | How many rows are in QryAllTransactons?
If your result returns 0 rows then Access may be able to see that immediately and stop, but if it returns even a single row then it needs to pull in the entire resultset of QryAllTransactons so that it can do the join internally. That would be my first guess as to what is happening.
Your best bet it usually to do joins on SQL Server. Try creating a view that does the LEFT OUTER JOIN and query against that.
Your goal, even when Access is running on the SQL Server itself and minimizes network traffic, is to only send to Access what it absolutely needs. Otherwise a large table will still take up memory, etc. |
281,167 | I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing.
The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in the table that's being queried. The Access project is stored and run from a terminal server session on the actual SQL server, so I don't think it's a network issue, and there's another form which is very similar that uses the same type of querying...
Thanks
PG
```
SELECT TabDrawer.DrawerName, TabDrawer.DrawerSortCode, TabDrawer.DrawerAccountNo, TabDrawer.DrawerPostCode, QryAllTransactons.TPCChequeNumber, tabdrawer.drawerref
FROM TabDrawer LEFT JOIN QryAllTransactons ON TabDrawer.DrawerRef=QryAllTransactons.tpcdrawer
WHERE (Forms!FrmSearchCompany!SearchName Is Null
Or [drawername] Like Forms!FrmSearchCompany!SearchName & "*")
And (Forms!FrmSearchCompany.SearchPostcode Is Null
Or [Drawerpostcode] Like Forms!FrmSearchCompany!Searchpostcode & "*")
And (Forms!FrmSearchCompany!SearchSortCode Is Null
Or [drawersortcode] Like Forms!FrmSearchCompany!Searchsortcode & "*")
And (Forms!FrmSearchCompany!Searchaccount Is Null
Or [draweraccountno] Like Forms!FrmSearchCompany!Searchaccount & "*")
And (Forms!FrmSearchCompany!Searchcheque Is Null
Or [tpcchequenumber] Like Forms!FrmSearchCompany!Searchcheque & "*");
");
```
---
**EDIT**
The Hold up seems to be in the union query that forms the QryAllTransactons query.
```
SELECT
"TPC" AS Type,
TabTPC.TPCRef,
TabTPC.TPCBranch,
TabTPC.TPCDate,
TabTPC.TPCChequeNumber,
TabTPC.TPCChequeValue,
TabTPC.TPCFee,
TabTPC.TPCAction,
TabTPC.TPCMember,
tabtpc.tpcdrawer,
TabTPC.TPCUser,
TabTPC.TPCDiscount,
tabcustomers.*
FROM
TabTPC
INNER JOIN TabCustomers ON TabTPC.TPCMember = TabCustomers.CustomerID
UNION ALL
SELECT
"CTP" AS Type,
TabCTP.CTPRef,
TabCTP.CTPBranch,
TabCTP.CTPDate,
TabCTP.CTPChequeNumb,
TabCTP.CTPAmount,
TabCTP.CTPFee,
TabCTP.CTPAction,
TabCTP.CTPMember,
0 as CTPXXX,
TabCTP.CTPUser,
TabCTP.CTPDiscount,
TABCUSTOMERS.*
FROM
TabCTP
INNER JOIN TabCustomers ON Tabctp.ctpMember = TabCustomers.CustomerID;
```
I've done a fair bit of work with simple union queries, but never had this before... | 2008/11/11 | [
"https://Stackoverflow.com/questions/281167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30140/"
] | At first, try compacting and repairing the .mdb file.
Then, simplify your WHERE clause:
```
WHERE
[drawername] Like Nz(Forms!FrmSearchCompany!SearchName, "") & "*"
And
[Drawerpostcode] Like Nz(Forms!FrmSearchCompany!Searchpostcode, "") & "*"
And
[drawersortcode] Like Nz(Forms!FrmSearchCompany!Searchsortcode, "") & "*"
And
[draweraccountno] Like Nz(Forms!FrmSearchCompany!Searchaccount, "") & "*"
And
[tpcchequenumber] Like Nz(Forms!FrmSearchCompany!Searchcheque, "") & "*"
```
Does it still run slowly?
**EDIT**
As it turned out, the question was not clear in that it is an up-sized Access Database with an SQL Server back end-and an Access Project front-end.
This sheds a different light on the whole problem.
Can you explain in more detail *how* this whole query is intended to be used?
If you use it to populate the RecordSource of some Form or Report, I think you will be able to refactor the whole thing like this:
* make a view on the SQL server that returns the right data
* query that view with a SQL server syntax, not with Access syntax
* let the server sort it out | Have you tried running each of the subqueries in the union? Usually optimizers don't spend much time trying to inspect efficiencies between union elements - each one runs on its own merits.
Given that fact, you could also put the "IF" logic into the procedural code and run each of the tests in some likely order of discovery, without significant additional overhead from more calls. |
281,167 | I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing.
The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in the table that's being queried. The Access project is stored and run from a terminal server session on the actual SQL server, so I don't think it's a network issue, and there's another form which is very similar that uses the same type of querying...
Thanks
PG
```
SELECT TabDrawer.DrawerName, TabDrawer.DrawerSortCode, TabDrawer.DrawerAccountNo, TabDrawer.DrawerPostCode, QryAllTransactons.TPCChequeNumber, tabdrawer.drawerref
FROM TabDrawer LEFT JOIN QryAllTransactons ON TabDrawer.DrawerRef=QryAllTransactons.tpcdrawer
WHERE (Forms!FrmSearchCompany!SearchName Is Null
Or [drawername] Like Forms!FrmSearchCompany!SearchName & "*")
And (Forms!FrmSearchCompany.SearchPostcode Is Null
Or [Drawerpostcode] Like Forms!FrmSearchCompany!Searchpostcode & "*")
And (Forms!FrmSearchCompany!SearchSortCode Is Null
Or [drawersortcode] Like Forms!FrmSearchCompany!Searchsortcode & "*")
And (Forms!FrmSearchCompany!Searchaccount Is Null
Or [draweraccountno] Like Forms!FrmSearchCompany!Searchaccount & "*")
And (Forms!FrmSearchCompany!Searchcheque Is Null
Or [tpcchequenumber] Like Forms!FrmSearchCompany!Searchcheque & "*");
");
```
---
**EDIT**
The Hold up seems to be in the union query that forms the QryAllTransactons query.
```
SELECT
"TPC" AS Type,
TabTPC.TPCRef,
TabTPC.TPCBranch,
TabTPC.TPCDate,
TabTPC.TPCChequeNumber,
TabTPC.TPCChequeValue,
TabTPC.TPCFee,
TabTPC.TPCAction,
TabTPC.TPCMember,
tabtpc.tpcdrawer,
TabTPC.TPCUser,
TabTPC.TPCDiscount,
tabcustomers.*
FROM
TabTPC
INNER JOIN TabCustomers ON TabTPC.TPCMember = TabCustomers.CustomerID
UNION ALL
SELECT
"CTP" AS Type,
TabCTP.CTPRef,
TabCTP.CTPBranch,
TabCTP.CTPDate,
TabCTP.CTPChequeNumb,
TabCTP.CTPAmount,
TabCTP.CTPFee,
TabCTP.CTPAction,
TabCTP.CTPMember,
0 as CTPXXX,
TabCTP.CTPUser,
TabCTP.CTPDiscount,
TABCUSTOMERS.*
FROM
TabCTP
INNER JOIN TabCustomers ON Tabctp.ctpMember = TabCustomers.CustomerID;
```
I've done a fair bit of work with simple union queries, but never had this before... | 2008/11/11 | [
"https://Stackoverflow.com/questions/281167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30140/"
] | At first, try compacting and repairing the .mdb file.
Then, simplify your WHERE clause:
```
WHERE
[drawername] Like Nz(Forms!FrmSearchCompany!SearchName, "") & "*"
And
[Drawerpostcode] Like Nz(Forms!FrmSearchCompany!Searchpostcode, "") & "*"
And
[drawersortcode] Like Nz(Forms!FrmSearchCompany!Searchsortcode, "") & "*"
And
[draweraccountno] Like Nz(Forms!FrmSearchCompany!Searchaccount, "") & "*"
And
[tpcchequenumber] Like Nz(Forms!FrmSearchCompany!Searchcheque, "") & "*"
```
Does it still run slowly?
**EDIT**
As it turned out, the question was not clear in that it is an up-sized Access Database with an SQL Server back end-and an Access Project front-end.
This sheds a different light on the whole problem.
Can you explain in more detail *how* this whole query is intended to be used?
If you use it to populate the RecordSource of some Form or Report, I think you will be able to refactor the whole thing like this:
* make a view on the SQL server that returns the right data
* query that view with a SQL server syntax, not with Access syntax
* let the server sort it out | Get rid of those like operators.
In your case you don't need them. Just check if the field starts with a given value which you can achive whith something like this:
```
Left([field], Len(value)) = value
```
This method applied to your query would look like this (did some reformatting for better readability):
```
SELECT
TabDrawer.DrawerName,
TabDrawer.DrawerSortCode,
TabDrawer.DrawerAccountNo,
TabDrawer.DrawerPostCode,
QryAllTransactons.TPCChequeNumber,
TabDrawer.DrawerRef
FROM
TabDrawer
LEFT JOIN QryAllTransactons
ON TabDrawer.DrawerRef = QryAllTransactons.TpcDrawer
WHERE
(Forms!FrmSearchCompany!SearchName Is Null
Or Left([drawername], Len(Forms!FrmSearchCompany!SearchName)) = Forms!FrmSearchCompany!SearchName)
And
(Forms!FrmSearchCompany.SearchPostcode Is Null
Or Left([Drawerpostcode], Len(Forms!FrmSearchCompany!Searchpostcode)) = Forms!FrmSearchCompany!Searchpostcode)
And
(Forms!FrmSearchCompany!SearchSortCode Is Null
Or Left([drawersortcode], Len(Forms!FrmSearchCompany!Searchsortcode)) = Forms!FrmSearchCompany!Searchsortcode)
And
(Forms!FrmSearchCompany!Searchaccount Is Null
Or Left([draweraccountno], Len(Forms!FrmSearchCompany!Searchaccount)) = Forms!FrmSearchCompany!Searchaccount)
And
(Forms!FrmSearchCompany!Searchcheque Is Null
Or Left([tpcchequenumber], Len(Forms!FrmSearchCompany!Searchcheque)) = Forms!FrmSearchCompany!Searchcheque)
```
Note that you're comparing case sensitive. I'm not totally sure if the like operator in MS-Access is case insensitive. Convert both strings to upper- or lowercase, if needed. |
281,167 | I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing.
The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in the table that's being queried. The Access project is stored and run from a terminal server session on the actual SQL server, so I don't think it's a network issue, and there's another form which is very similar that uses the same type of querying...
Thanks
PG
```
SELECT TabDrawer.DrawerName, TabDrawer.DrawerSortCode, TabDrawer.DrawerAccountNo, TabDrawer.DrawerPostCode, QryAllTransactons.TPCChequeNumber, tabdrawer.drawerref
FROM TabDrawer LEFT JOIN QryAllTransactons ON TabDrawer.DrawerRef=QryAllTransactons.tpcdrawer
WHERE (Forms!FrmSearchCompany!SearchName Is Null
Or [drawername] Like Forms!FrmSearchCompany!SearchName & "*")
And (Forms!FrmSearchCompany.SearchPostcode Is Null
Or [Drawerpostcode] Like Forms!FrmSearchCompany!Searchpostcode & "*")
And (Forms!FrmSearchCompany!SearchSortCode Is Null
Or [drawersortcode] Like Forms!FrmSearchCompany!Searchsortcode & "*")
And (Forms!FrmSearchCompany!Searchaccount Is Null
Or [draweraccountno] Like Forms!FrmSearchCompany!Searchaccount & "*")
And (Forms!FrmSearchCompany!Searchcheque Is Null
Or [tpcchequenumber] Like Forms!FrmSearchCompany!Searchcheque & "*");
");
```
---
**EDIT**
The Hold up seems to be in the union query that forms the QryAllTransactons query.
```
SELECT
"TPC" AS Type,
TabTPC.TPCRef,
TabTPC.TPCBranch,
TabTPC.TPCDate,
TabTPC.TPCChequeNumber,
TabTPC.TPCChequeValue,
TabTPC.TPCFee,
TabTPC.TPCAction,
TabTPC.TPCMember,
tabtpc.tpcdrawer,
TabTPC.TPCUser,
TabTPC.TPCDiscount,
tabcustomers.*
FROM
TabTPC
INNER JOIN TabCustomers ON TabTPC.TPCMember = TabCustomers.CustomerID
UNION ALL
SELECT
"CTP" AS Type,
TabCTP.CTPRef,
TabCTP.CTPBranch,
TabCTP.CTPDate,
TabCTP.CTPChequeNumb,
TabCTP.CTPAmount,
TabCTP.CTPFee,
TabCTP.CTPAction,
TabCTP.CTPMember,
0 as CTPXXX,
TabCTP.CTPUser,
TabCTP.CTPDiscount,
TABCUSTOMERS.*
FROM
TabCTP
INNER JOIN TabCustomers ON Tabctp.ctpMember = TabCustomers.CustomerID;
```
I've done a fair bit of work with simple union queries, but never had this before... | 2008/11/11 | [
"https://Stackoverflow.com/questions/281167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30140/"
] | Two things. Since this is an Access database with a SQL Server backend, you may find a considerable speed improvement by converting this to a stored proc.
Second, do you really need to return all those fields, especially in the tabCustomers table? Never return more fields than you actually intend to use and you will improve performance. | At first, try compacting and repairing the .mdb file.
Then, simplify your WHERE clause:
```
WHERE
[drawername] Like Nz(Forms!FrmSearchCompany!SearchName, "") & "*"
And
[Drawerpostcode] Like Nz(Forms!FrmSearchCompany!Searchpostcode, "") & "*"
And
[drawersortcode] Like Nz(Forms!FrmSearchCompany!Searchsortcode, "") & "*"
And
[draweraccountno] Like Nz(Forms!FrmSearchCompany!Searchaccount, "") & "*"
And
[tpcchequenumber] Like Nz(Forms!FrmSearchCompany!Searchcheque, "") & "*"
```
Does it still run slowly?
**EDIT**
As it turned out, the question was not clear in that it is an up-sized Access Database with an SQL Server back end-and an Access Project front-end.
This sheds a different light on the whole problem.
Can you explain in more detail *how* this whole query is intended to be used?
If you use it to populate the RecordSource of some Form or Report, I think you will be able to refactor the whole thing like this:
* make a view on the SQL server that returns the right data
* query that view with a SQL server syntax, not with Access syntax
* let the server sort it out |
281,167 | I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing.
The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in the table that's being queried. The Access project is stored and run from a terminal server session on the actual SQL server, so I don't think it's a network issue, and there's another form which is very similar that uses the same type of querying...
Thanks
PG
```
SELECT TabDrawer.DrawerName, TabDrawer.DrawerSortCode, TabDrawer.DrawerAccountNo, TabDrawer.DrawerPostCode, QryAllTransactons.TPCChequeNumber, tabdrawer.drawerref
FROM TabDrawer LEFT JOIN QryAllTransactons ON TabDrawer.DrawerRef=QryAllTransactons.tpcdrawer
WHERE (Forms!FrmSearchCompany!SearchName Is Null
Or [drawername] Like Forms!FrmSearchCompany!SearchName & "*")
And (Forms!FrmSearchCompany.SearchPostcode Is Null
Or [Drawerpostcode] Like Forms!FrmSearchCompany!Searchpostcode & "*")
And (Forms!FrmSearchCompany!SearchSortCode Is Null
Or [drawersortcode] Like Forms!FrmSearchCompany!Searchsortcode & "*")
And (Forms!FrmSearchCompany!Searchaccount Is Null
Or [draweraccountno] Like Forms!FrmSearchCompany!Searchaccount & "*")
And (Forms!FrmSearchCompany!Searchcheque Is Null
Or [tpcchequenumber] Like Forms!FrmSearchCompany!Searchcheque & "*");
");
```
---
**EDIT**
The Hold up seems to be in the union query that forms the QryAllTransactons query.
```
SELECT
"TPC" AS Type,
TabTPC.TPCRef,
TabTPC.TPCBranch,
TabTPC.TPCDate,
TabTPC.TPCChequeNumber,
TabTPC.TPCChequeValue,
TabTPC.TPCFee,
TabTPC.TPCAction,
TabTPC.TPCMember,
tabtpc.tpcdrawer,
TabTPC.TPCUser,
TabTPC.TPCDiscount,
tabcustomers.*
FROM
TabTPC
INNER JOIN TabCustomers ON TabTPC.TPCMember = TabCustomers.CustomerID
UNION ALL
SELECT
"CTP" AS Type,
TabCTP.CTPRef,
TabCTP.CTPBranch,
TabCTP.CTPDate,
TabCTP.CTPChequeNumb,
TabCTP.CTPAmount,
TabCTP.CTPFee,
TabCTP.CTPAction,
TabCTP.CTPMember,
0 as CTPXXX,
TabCTP.CTPUser,
TabCTP.CTPDiscount,
TABCUSTOMERS.*
FROM
TabCTP
INNER JOIN TabCustomers ON Tabctp.ctpMember = TabCustomers.CustomerID;
```
I've done a fair bit of work with simple union queries, but never had this before... | 2008/11/11 | [
"https://Stackoverflow.com/questions/281167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30140/"
] | At first, try compacting and repairing the .mdb file.
Then, simplify your WHERE clause:
```
WHERE
[drawername] Like Nz(Forms!FrmSearchCompany!SearchName, "") & "*"
And
[Drawerpostcode] Like Nz(Forms!FrmSearchCompany!Searchpostcode, "") & "*"
And
[drawersortcode] Like Nz(Forms!FrmSearchCompany!Searchsortcode, "") & "*"
And
[draweraccountno] Like Nz(Forms!FrmSearchCompany!Searchaccount, "") & "*"
And
[tpcchequenumber] Like Nz(Forms!FrmSearchCompany!Searchcheque, "") & "*"
```
Does it still run slowly?
**EDIT**
As it turned out, the question was not clear in that it is an up-sized Access Database with an SQL Server back end-and an Access Project front-end.
This sheds a different light on the whole problem.
Can you explain in more detail *how* this whole query is intended to be used?
If you use it to populate the RecordSource of some Form or Report, I think you will be able to refactor the whole thing like this:
* make a view on the SQL server that returns the right data
* query that view with a SQL server syntax, not with Access syntax
* let the server sort it out | When you upsized did you make sure the tables were properly indexed? Indexes will speed queries tremendously if used properly (note they may also slow down inserts/updates/deletes, so choose carefully what to index) |
281,167 | I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing.
The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in the table that's being queried. The Access project is stored and run from a terminal server session on the actual SQL server, so I don't think it's a network issue, and there's another form which is very similar that uses the same type of querying...
Thanks
PG
```
SELECT TabDrawer.DrawerName, TabDrawer.DrawerSortCode, TabDrawer.DrawerAccountNo, TabDrawer.DrawerPostCode, QryAllTransactons.TPCChequeNumber, tabdrawer.drawerref
FROM TabDrawer LEFT JOIN QryAllTransactons ON TabDrawer.DrawerRef=QryAllTransactons.tpcdrawer
WHERE (Forms!FrmSearchCompany!SearchName Is Null
Or [drawername] Like Forms!FrmSearchCompany!SearchName & "*")
And (Forms!FrmSearchCompany.SearchPostcode Is Null
Or [Drawerpostcode] Like Forms!FrmSearchCompany!Searchpostcode & "*")
And (Forms!FrmSearchCompany!SearchSortCode Is Null
Or [drawersortcode] Like Forms!FrmSearchCompany!Searchsortcode & "*")
And (Forms!FrmSearchCompany!Searchaccount Is Null
Or [draweraccountno] Like Forms!FrmSearchCompany!Searchaccount & "*")
And (Forms!FrmSearchCompany!Searchcheque Is Null
Or [tpcchequenumber] Like Forms!FrmSearchCompany!Searchcheque & "*");
");
```
---
**EDIT**
The Hold up seems to be in the union query that forms the QryAllTransactons query.
```
SELECT
"TPC" AS Type,
TabTPC.TPCRef,
TabTPC.TPCBranch,
TabTPC.TPCDate,
TabTPC.TPCChequeNumber,
TabTPC.TPCChequeValue,
TabTPC.TPCFee,
TabTPC.TPCAction,
TabTPC.TPCMember,
tabtpc.tpcdrawer,
TabTPC.TPCUser,
TabTPC.TPCDiscount,
tabcustomers.*
FROM
TabTPC
INNER JOIN TabCustomers ON TabTPC.TPCMember = TabCustomers.CustomerID
UNION ALL
SELECT
"CTP" AS Type,
TabCTP.CTPRef,
TabCTP.CTPBranch,
TabCTP.CTPDate,
TabCTP.CTPChequeNumb,
TabCTP.CTPAmount,
TabCTP.CTPFee,
TabCTP.CTPAction,
TabCTP.CTPMember,
0 as CTPXXX,
TabCTP.CTPUser,
TabCTP.CTPDiscount,
TABCUSTOMERS.*
FROM
TabCTP
INNER JOIN TabCustomers ON Tabctp.ctpMember = TabCustomers.CustomerID;
```
I've done a fair bit of work with simple union queries, but never had this before... | 2008/11/11 | [
"https://Stackoverflow.com/questions/281167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30140/"
] | Two things. Since this is an Access database with a SQL Server backend, you may find a considerable speed improvement by converting this to a stored proc.
Second, do you really need to return all those fields, especially in the tabCustomers table? Never return more fields than you actually intend to use and you will improve performance. | How many rows are in QryAllTransactons?
If your result returns 0 rows then Access may be able to see that immediately and stop, but if it returns even a single row then it needs to pull in the entire resultset of QryAllTransactons so that it can do the join internally. That would be my first guess as to what is happening.
Your best bet it usually to do joins on SQL Server. Try creating a view that does the LEFT OUTER JOIN and query against that.
Your goal, even when Access is running on the SQL Server itself and minimizes network traffic, is to only send to Access what it absolutely needs. Otherwise a large table will still take up memory, etc. |
281,167 | I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing.
The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in the table that's being queried. The Access project is stored and run from a terminal server session on the actual SQL server, so I don't think it's a network issue, and there's another form which is very similar that uses the same type of querying...
Thanks
PG
```
SELECT TabDrawer.DrawerName, TabDrawer.DrawerSortCode, TabDrawer.DrawerAccountNo, TabDrawer.DrawerPostCode, QryAllTransactons.TPCChequeNumber, tabdrawer.drawerref
FROM TabDrawer LEFT JOIN QryAllTransactons ON TabDrawer.DrawerRef=QryAllTransactons.tpcdrawer
WHERE (Forms!FrmSearchCompany!SearchName Is Null
Or [drawername] Like Forms!FrmSearchCompany!SearchName & "*")
And (Forms!FrmSearchCompany.SearchPostcode Is Null
Or [Drawerpostcode] Like Forms!FrmSearchCompany!Searchpostcode & "*")
And (Forms!FrmSearchCompany!SearchSortCode Is Null
Or [drawersortcode] Like Forms!FrmSearchCompany!Searchsortcode & "*")
And (Forms!FrmSearchCompany!Searchaccount Is Null
Or [draweraccountno] Like Forms!FrmSearchCompany!Searchaccount & "*")
And (Forms!FrmSearchCompany!Searchcheque Is Null
Or [tpcchequenumber] Like Forms!FrmSearchCompany!Searchcheque & "*");
");
```
---
**EDIT**
The Hold up seems to be in the union query that forms the QryAllTransactons query.
```
SELECT
"TPC" AS Type,
TabTPC.TPCRef,
TabTPC.TPCBranch,
TabTPC.TPCDate,
TabTPC.TPCChequeNumber,
TabTPC.TPCChequeValue,
TabTPC.TPCFee,
TabTPC.TPCAction,
TabTPC.TPCMember,
tabtpc.tpcdrawer,
TabTPC.TPCUser,
TabTPC.TPCDiscount,
tabcustomers.*
FROM
TabTPC
INNER JOIN TabCustomers ON TabTPC.TPCMember = TabCustomers.CustomerID
UNION ALL
SELECT
"CTP" AS Type,
TabCTP.CTPRef,
TabCTP.CTPBranch,
TabCTP.CTPDate,
TabCTP.CTPChequeNumb,
TabCTP.CTPAmount,
TabCTP.CTPFee,
TabCTP.CTPAction,
TabCTP.CTPMember,
0 as CTPXXX,
TabCTP.CTPUser,
TabCTP.CTPDiscount,
TABCUSTOMERS.*
FROM
TabCTP
INNER JOIN TabCustomers ON Tabctp.ctpMember = TabCustomers.CustomerID;
```
I've done a fair bit of work with simple union queries, but never had this before... | 2008/11/11 | [
"https://Stackoverflow.com/questions/281167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30140/"
] | Two things. Since this is an Access database with a SQL Server backend, you may find a considerable speed improvement by converting this to a stored proc.
Second, do you really need to return all those fields, especially in the tabCustomers table? Never return more fields than you actually intend to use and you will improve performance. | Have you tried running each of the subqueries in the union? Usually optimizers don't spend much time trying to inspect efficiencies between union elements - each one runs on its own merits.
Given that fact, you could also put the "IF" logic into the procedural code and run each of the tests in some likely order of discovery, without significant additional overhead from more calls. |
281,167 | I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing.
The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in the table that's being queried. The Access project is stored and run from a terminal server session on the actual SQL server, so I don't think it's a network issue, and there's another form which is very similar that uses the same type of querying...
Thanks
PG
```
SELECT TabDrawer.DrawerName, TabDrawer.DrawerSortCode, TabDrawer.DrawerAccountNo, TabDrawer.DrawerPostCode, QryAllTransactons.TPCChequeNumber, tabdrawer.drawerref
FROM TabDrawer LEFT JOIN QryAllTransactons ON TabDrawer.DrawerRef=QryAllTransactons.tpcdrawer
WHERE (Forms!FrmSearchCompany!SearchName Is Null
Or [drawername] Like Forms!FrmSearchCompany!SearchName & "*")
And (Forms!FrmSearchCompany.SearchPostcode Is Null
Or [Drawerpostcode] Like Forms!FrmSearchCompany!Searchpostcode & "*")
And (Forms!FrmSearchCompany!SearchSortCode Is Null
Or [drawersortcode] Like Forms!FrmSearchCompany!Searchsortcode & "*")
And (Forms!FrmSearchCompany!Searchaccount Is Null
Or [draweraccountno] Like Forms!FrmSearchCompany!Searchaccount & "*")
And (Forms!FrmSearchCompany!Searchcheque Is Null
Or [tpcchequenumber] Like Forms!FrmSearchCompany!Searchcheque & "*");
");
```
---
**EDIT**
The Hold up seems to be in the union query that forms the QryAllTransactons query.
```
SELECT
"TPC" AS Type,
TabTPC.TPCRef,
TabTPC.TPCBranch,
TabTPC.TPCDate,
TabTPC.TPCChequeNumber,
TabTPC.TPCChequeValue,
TabTPC.TPCFee,
TabTPC.TPCAction,
TabTPC.TPCMember,
tabtpc.tpcdrawer,
TabTPC.TPCUser,
TabTPC.TPCDiscount,
tabcustomers.*
FROM
TabTPC
INNER JOIN TabCustomers ON TabTPC.TPCMember = TabCustomers.CustomerID
UNION ALL
SELECT
"CTP" AS Type,
TabCTP.CTPRef,
TabCTP.CTPBranch,
TabCTP.CTPDate,
TabCTP.CTPChequeNumb,
TabCTP.CTPAmount,
TabCTP.CTPFee,
TabCTP.CTPAction,
TabCTP.CTPMember,
0 as CTPXXX,
TabCTP.CTPUser,
TabCTP.CTPDiscount,
TABCUSTOMERS.*
FROM
TabCTP
INNER JOIN TabCustomers ON Tabctp.ctpMember = TabCustomers.CustomerID;
```
I've done a fair bit of work with simple union queries, but never had this before... | 2008/11/11 | [
"https://Stackoverflow.com/questions/281167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30140/"
] | Two things. Since this is an Access database with a SQL Server backend, you may find a considerable speed improvement by converting this to a stored proc.
Second, do you really need to return all those fields, especially in the tabCustomers table? Never return more fields than you actually intend to use and you will improve performance. | Get rid of those like operators.
In your case you don't need them. Just check if the field starts with a given value which you can achive whith something like this:
```
Left([field], Len(value)) = value
```
This method applied to your query would look like this (did some reformatting for better readability):
```
SELECT
TabDrawer.DrawerName,
TabDrawer.DrawerSortCode,
TabDrawer.DrawerAccountNo,
TabDrawer.DrawerPostCode,
QryAllTransactons.TPCChequeNumber,
TabDrawer.DrawerRef
FROM
TabDrawer
LEFT JOIN QryAllTransactons
ON TabDrawer.DrawerRef = QryAllTransactons.TpcDrawer
WHERE
(Forms!FrmSearchCompany!SearchName Is Null
Or Left([drawername], Len(Forms!FrmSearchCompany!SearchName)) = Forms!FrmSearchCompany!SearchName)
And
(Forms!FrmSearchCompany.SearchPostcode Is Null
Or Left([Drawerpostcode], Len(Forms!FrmSearchCompany!Searchpostcode)) = Forms!FrmSearchCompany!Searchpostcode)
And
(Forms!FrmSearchCompany!SearchSortCode Is Null
Or Left([drawersortcode], Len(Forms!FrmSearchCompany!Searchsortcode)) = Forms!FrmSearchCompany!Searchsortcode)
And
(Forms!FrmSearchCompany!Searchaccount Is Null
Or Left([draweraccountno], Len(Forms!FrmSearchCompany!Searchaccount)) = Forms!FrmSearchCompany!Searchaccount)
And
(Forms!FrmSearchCompany!Searchcheque Is Null
Or Left([tpcchequenumber], Len(Forms!FrmSearchCompany!Searchcheque)) = Forms!FrmSearchCompany!Searchcheque)
```
Note that you're comparing case sensitive. I'm not totally sure if the like operator in MS-Access is case insensitive. Convert both strings to upper- or lowercase, if needed. |
281,167 | I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing.
The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in the table that's being queried. The Access project is stored and run from a terminal server session on the actual SQL server, so I don't think it's a network issue, and there's another form which is very similar that uses the same type of querying...
Thanks
PG
```
SELECT TabDrawer.DrawerName, TabDrawer.DrawerSortCode, TabDrawer.DrawerAccountNo, TabDrawer.DrawerPostCode, QryAllTransactons.TPCChequeNumber, tabdrawer.drawerref
FROM TabDrawer LEFT JOIN QryAllTransactons ON TabDrawer.DrawerRef=QryAllTransactons.tpcdrawer
WHERE (Forms!FrmSearchCompany!SearchName Is Null
Or [drawername] Like Forms!FrmSearchCompany!SearchName & "*")
And (Forms!FrmSearchCompany.SearchPostcode Is Null
Or [Drawerpostcode] Like Forms!FrmSearchCompany!Searchpostcode & "*")
And (Forms!FrmSearchCompany!SearchSortCode Is Null
Or [drawersortcode] Like Forms!FrmSearchCompany!Searchsortcode & "*")
And (Forms!FrmSearchCompany!Searchaccount Is Null
Or [draweraccountno] Like Forms!FrmSearchCompany!Searchaccount & "*")
And (Forms!FrmSearchCompany!Searchcheque Is Null
Or [tpcchequenumber] Like Forms!FrmSearchCompany!Searchcheque & "*");
");
```
---
**EDIT**
The Hold up seems to be in the union query that forms the QryAllTransactons query.
```
SELECT
"TPC" AS Type,
TabTPC.TPCRef,
TabTPC.TPCBranch,
TabTPC.TPCDate,
TabTPC.TPCChequeNumber,
TabTPC.TPCChequeValue,
TabTPC.TPCFee,
TabTPC.TPCAction,
TabTPC.TPCMember,
tabtpc.tpcdrawer,
TabTPC.TPCUser,
TabTPC.TPCDiscount,
tabcustomers.*
FROM
TabTPC
INNER JOIN TabCustomers ON TabTPC.TPCMember = TabCustomers.CustomerID
UNION ALL
SELECT
"CTP" AS Type,
TabCTP.CTPRef,
TabCTP.CTPBranch,
TabCTP.CTPDate,
TabCTP.CTPChequeNumb,
TabCTP.CTPAmount,
TabCTP.CTPFee,
TabCTP.CTPAction,
TabCTP.CTPMember,
0 as CTPXXX,
TabCTP.CTPUser,
TabCTP.CTPDiscount,
TABCUSTOMERS.*
FROM
TabCTP
INNER JOIN TabCustomers ON Tabctp.ctpMember = TabCustomers.CustomerID;
```
I've done a fair bit of work with simple union queries, but never had this before... | 2008/11/11 | [
"https://Stackoverflow.com/questions/281167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30140/"
] | Two things. Since this is an Access database with a SQL Server backend, you may find a considerable speed improvement by converting this to a stored proc.
Second, do you really need to return all those fields, especially in the tabCustomers table? Never return more fields than you actually intend to use and you will improve performance. | When you upsized did you make sure the tables were properly indexed? Indexes will speed queries tremendously if used properly (note they may also slow down inserts/updates/deletes, so choose carefully what to index) |
221,897 | Well, the title says what I'd like to achieve: I'd like some workstations connect through my 1st internet account and some through my second one.
1. The workstations are in a workgroup. They're not in a domain. So They don't have a server. One workstation has the internet connection and shares the internet through the whole LAN.
2. I have 2 ADSL internet accounts on that workstation.
3. The workstation's OS is Windows XP SP2.
I think I should define two http proxy servers on the workstation (probably via a software) and set the IE/Firefox proxy settings on each workstation to the appropriate proxy server. e.g. If I want station A to connect via ADSL1 I should set the proxy settings for ADSL1 as I have defined it in my workstation.
My question is:
1. is my approach correct? Do I need to use a third party software to be able to achieve what I have described or can I just use Windows connection sharing features?
2. What if I have to connect via ftp/telnet/etc? should I define other proxy servers and set the appropriate values in workstations as well? | 2010/12/14 | [
"https://superuser.com/questions/221897",
"https://superuser.com",
"https://superuser.com/users/51559/"
] | That's one approach...but it doesn't solve other protocols.
if you just want to load balance over the two networks it's as simple as making sure the route cost is the same...route /? for help i think.
The other possibility is to run a linux router in a VM and bridge network connections to the VM so you have a fully configurable router running on the XP host hardware.
Yet another approach is to make everything happen over socks proxies(this can handle any socks aware app or you can try a socks wrapper). You could then run 2 different socks proxies that forward over different links. | Please also refer to @aking1012's answer.
If you are not familiar with routing setups, you can consider dual-WAN routers like the infamous [Cisco RV042 Dual WAN VPN Router](http://www.cisco.com/en/US/products/ps9925/index.html). These offer reasonable performance at ~$150.
Similar products exist from other brands, and you can also consider dd-wrt on certain router hardware to get similar solution at a lower cost. ( refer to [Dual-WAN for simple round-robin load equalization](http://www.dd-wrt.com/wiki/index.php/Dual-WAN_for_simple_round-robin_load_equalization) for an example ) |
221,897 | Well, the title says what I'd like to achieve: I'd like some workstations connect through my 1st internet account and some through my second one.
1. The workstations are in a workgroup. They're not in a domain. So They don't have a server. One workstation has the internet connection and shares the internet through the whole LAN.
2. I have 2 ADSL internet accounts on that workstation.
3. The workstation's OS is Windows XP SP2.
I think I should define two http proxy servers on the workstation (probably via a software) and set the IE/Firefox proxy settings on each workstation to the appropriate proxy server. e.g. If I want station A to connect via ADSL1 I should set the proxy settings for ADSL1 as I have defined it in my workstation.
My question is:
1. is my approach correct? Do I need to use a third party software to be able to achieve what I have described or can I just use Windows connection sharing features?
2. What if I have to connect via ftp/telnet/etc? should I define other proxy servers and set the appropriate values in workstations as well? | 2010/12/14 | [
"https://superuser.com/questions/221897",
"https://superuser.com",
"https://superuser.com/users/51559/"
] | That's one approach...but it doesn't solve other protocols.
if you just want to load balance over the two networks it's as simple as making sure the route cost is the same...route /? for help i think.
The other possibility is to run a linux router in a VM and bridge network connections to the VM so you have a fully configurable router running on the XP host hardware.
Yet another approach is to make everything happen over socks proxies(this can handle any socks aware app or you can try a socks wrapper). You could then run 2 different socks proxies that forward over different links. | Connect each router to your switch and make sure they have different IPs in the same subnet. To define which internet connection is used by a particular machine, set its [default gateway](http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ras_config_incoming_tcpip_defaultgw.mspx?mfr=true) value to the corresponding router. |
327,284 | Can someone explain which will be better, laptop with core i3 processor, 4GB RAM OR core i5 processor, 2GB RAM ? | 2011/08/24 | [
"https://superuser.com/questions/327284",
"https://superuser.com",
"https://superuser.com/users/95076/"
] | It depends really on *which* generation processors, and what you use it for - do you need a specific extension that's in one and not the other (for example VT). I generally tend to find that, except in exceptional circumstances, i'm not actually using all my processor power, so the processor i use is less critical.
On the other hand, many modern OSes, including windows 7 uses spare ram for caching, so you might see a advantage there.
One would need a little more information for a definitive answer. | Based on the information given, this is unanswerable.
However, if we were to assume a modern OS running under a standard workload, 4GB of memory would be better. |
327,284 | Can someone explain which will be better, laptop with core i3 processor, 4GB RAM OR core i5 processor, 2GB RAM ? | 2011/08/24 | [
"https://superuser.com/questions/327284",
"https://superuser.com",
"https://superuser.com/users/95076/"
] | It depends really on *which* generation processors, and what you use it for - do you need a specific extension that's in one and not the other (for example VT). I generally tend to find that, except in exceptional circumstances, i'm not actually using all my processor power, so the processor i use is less critical.
On the other hand, many modern OSes, including windows 7 uses spare ram for caching, so you might see a advantage there.
One would need a little more information for a definitive answer. | Does the i5 laptop have empty memory banks or support a larger memory module? If yes, I'd go with that one since memory can be upgraded but CPUs can't. Otherwise, 2GB is quite minimal for Win7, and too small for Vista. Other OSs can survive with 2GB but the more applications you run simultaneously, the slower it gets. |
327,284 | Can someone explain which will be better, laptop with core i3 processor, 4GB RAM OR core i5 processor, 2GB RAM ? | 2011/08/24 | [
"https://superuser.com/questions/327284",
"https://superuser.com",
"https://superuser.com/users/95076/"
] | It depends really on *which* generation processors, and what you use it for - do you need a specific extension that's in one and not the other (for example VT). I generally tend to find that, except in exceptional circumstances, i'm not actually using all my processor power, so the processor i use is less critical.
On the other hand, many modern OSes, including windows 7 uses spare ram for caching, so you might see a advantage there.
One would need a little more information for a definitive answer. | Going with the i5 cpu would be a better choice it's a faster cpu. On a laptop you can't upgrade or change the cpu you however with the ram you can. So if you went with the i3 you're some what downgrading your option. Ram is super cheap nowadays so it's really not a big deal also it comes down to what you're planning to do so unless you're going to do heavy video editing, music editing and gaming I go with the i5 if I were you. Basic word processing, surfing the net does not require much power so which ever one you decide to go with will do that seemlessly. So always ask yourself that question what i am going to use the computer for down the road remember one thing about laptop there's only 2 things that you can upgrade ram and hardrive that's it. Always think long term. |
327,284 | Can someone explain which will be better, laptop with core i3 processor, 4GB RAM OR core i5 processor, 2GB RAM ? | 2011/08/24 | [
"https://superuser.com/questions/327284",
"https://superuser.com",
"https://superuser.com/users/95076/"
] | It depends really on *which* generation processors, and what you use it for - do you need a specific extension that's in one and not the other (for example VT). I generally tend to find that, except in exceptional circumstances, i'm not actually using all my processor power, so the processor i use is less critical.
On the other hand, many modern OSes, including windows 7 uses spare ram for caching, so you might see a advantage there.
One would need a little more information for a definitive answer. | Memory is a cheaper (and easier) upgrade than processor.
While I agree with the theory most of the other answers get into, I would purchase the i5 system and plan on upgrading the memory down the road if I find it is necessary.
It is highly unlikely that you are purchasing the computer for a static set of tasks. Rather you're looking for something that will do what you think it needs to do today, as well as for what you may come up with for it to do tomorrow, and the next day.
2GB memory is a good minimum. It's kinda like what 128MB of memory was 15 or so years ago. Unless you're running memory-intensive applications right away, you're probably going to get more immediate benefit from the i5 system with 2GB memory. And going forward, as mentioned above, this system will remain capable of more for a longer period of time for less money in upgrades than the i3 system. |
327,284 | Can someone explain which will be better, laptop with core i3 processor, 4GB RAM OR core i5 processor, 2GB RAM ? | 2011/08/24 | [
"https://superuser.com/questions/327284",
"https://superuser.com",
"https://superuser.com/users/95076/"
] | Memory is a cheaper (and easier) upgrade than processor.
While I agree with the theory most of the other answers get into, I would purchase the i5 system and plan on upgrading the memory down the road if I find it is necessary.
It is highly unlikely that you are purchasing the computer for a static set of tasks. Rather you're looking for something that will do what you think it needs to do today, as well as for what you may come up with for it to do tomorrow, and the next day.
2GB memory is a good minimum. It's kinda like what 128MB of memory was 15 or so years ago. Unless you're running memory-intensive applications right away, you're probably going to get more immediate benefit from the i5 system with 2GB memory. And going forward, as mentioned above, this system will remain capable of more for a longer period of time for less money in upgrades than the i3 system. | Based on the information given, this is unanswerable.
However, if we were to assume a modern OS running under a standard workload, 4GB of memory would be better. |
327,284 | Can someone explain which will be better, laptop with core i3 processor, 4GB RAM OR core i5 processor, 2GB RAM ? | 2011/08/24 | [
"https://superuser.com/questions/327284",
"https://superuser.com",
"https://superuser.com/users/95076/"
] | Memory is a cheaper (and easier) upgrade than processor.
While I agree with the theory most of the other answers get into, I would purchase the i5 system and plan on upgrading the memory down the road if I find it is necessary.
It is highly unlikely that you are purchasing the computer for a static set of tasks. Rather you're looking for something that will do what you think it needs to do today, as well as for what you may come up with for it to do tomorrow, and the next day.
2GB memory is a good minimum. It's kinda like what 128MB of memory was 15 or so years ago. Unless you're running memory-intensive applications right away, you're probably going to get more immediate benefit from the i5 system with 2GB memory. And going forward, as mentioned above, this system will remain capable of more for a longer period of time for less money in upgrades than the i3 system. | Does the i5 laptop have empty memory banks or support a larger memory module? If yes, I'd go with that one since memory can be upgraded but CPUs can't. Otherwise, 2GB is quite minimal for Win7, and too small for Vista. Other OSs can survive with 2GB but the more applications you run simultaneously, the slower it gets. |
327,284 | Can someone explain which will be better, laptop with core i3 processor, 4GB RAM OR core i5 processor, 2GB RAM ? | 2011/08/24 | [
"https://superuser.com/questions/327284",
"https://superuser.com",
"https://superuser.com/users/95076/"
] | Memory is a cheaper (and easier) upgrade than processor.
While I agree with the theory most of the other answers get into, I would purchase the i5 system and plan on upgrading the memory down the road if I find it is necessary.
It is highly unlikely that you are purchasing the computer for a static set of tasks. Rather you're looking for something that will do what you think it needs to do today, as well as for what you may come up with for it to do tomorrow, and the next day.
2GB memory is a good minimum. It's kinda like what 128MB of memory was 15 or so years ago. Unless you're running memory-intensive applications right away, you're probably going to get more immediate benefit from the i5 system with 2GB memory. And going forward, as mentioned above, this system will remain capable of more for a longer period of time for less money in upgrades than the i3 system. | Going with the i5 cpu would be a better choice it's a faster cpu. On a laptop you can't upgrade or change the cpu you however with the ram you can. So if you went with the i3 you're some what downgrading your option. Ram is super cheap nowadays so it's really not a big deal also it comes down to what you're planning to do so unless you're going to do heavy video editing, music editing and gaming I go with the i5 if I were you. Basic word processing, surfing the net does not require much power so which ever one you decide to go with will do that seemlessly. So always ask yourself that question what i am going to use the computer for down the road remember one thing about laptop there's only 2 things that you can upgrade ram and hardrive that's it. Always think long term. |
461,503 | So, I was installing some packages via Synaptic. They were for my fan and hot keys. It froze durning installation, so I rebooted it, only to get stuck at the splash screen. I'm guessing it's just not loading the login panel. Any help?
I'm using a Dell Vostro 3450, Ubuntu 14.??
Pressing Crtl - Alt - F1 does nothing at the splash screen. I don't really know how to go into no-graphics mode.
Low-graphics mode seems unresponsive. The mouse does not show up, but it does do some hover effects. I was only able to get past the initial low-graphics warning before it stopped responding. | 2014/05/06 | [
"https://askubuntu.com/questions/461503",
"https://askubuntu.com",
"https://askubuntu.com/users/278012/"
] | Just gone through this myself.
I had to try several different USB sticks before I found one that worked.
I also found that it only worked if I created the installation disk from within an existing Ubuntu installation. | * Did you try to install connected to internet ?
* Did you try to install from USB Stick ? I think its much more stable than usual DVD Driver, especially on old or heavy used computers
Sorry my newbie help, im new but these things solved my problems once. |
461,503 | So, I was installing some packages via Synaptic. They were for my fan and hot keys. It froze durning installation, so I rebooted it, only to get stuck at the splash screen. I'm guessing it's just not loading the login panel. Any help?
I'm using a Dell Vostro 3450, Ubuntu 14.??
Pressing Crtl - Alt - F1 does nothing at the splash screen. I don't really know how to go into no-graphics mode.
Low-graphics mode seems unresponsive. The mouse does not show up, but it does do some hover effects. I was only able to get past the initial low-graphics warning before it stopped responding. | 2014/05/06 | [
"https://askubuntu.com/questions/461503",
"https://askubuntu.com",
"https://askubuntu.com/users/278012/"
] | I've found that unetbootin doesn't wipe the USB drive before installing and it gets confused. On my Windows 7 machine, I open a Command Prompt window with Admin privileges. Type in the following commands:
```
diskpart
list disk
select disk ##
```
(Make sure you select the number from the above list that represents your USB drive! Mine was disk 3 so I used `select disk 3`.)
```
clean
create part primary
exit
```
This wipes the partitions and allows a fresh install. Use Windows File Explorer to format the USB drive with default settings. Then run unetbootin. This solved my issues with installing 14.04 LTS. | * Did you try to install connected to internet ?
* Did you try to install from USB Stick ? I think its much more stable than usual DVD Driver, especially on old or heavy used computers
Sorry my newbie help, im new but these things solved my problems once. |
37,700,883 | I am making a program that converts a number from decimal to binary for my college.
I have written the script and functions in Swift with Xcode and it works very good. But now it works with a calculate button.
I want to remove the button code and return the result on the specific label while the users enters the number on the NSTextField.
How can this be done?
It is for an application for OSX environment.
I have below code on a view file with a convert button, which I want to remove.
```
import Cocoa
class DecimalView: NSViewController {
@IBOutlet weak var decimalNumberText: NSTextField!
@IBOutlet weak var toBinaryLabel: NSTextField!
@IBAction func convertButton(sender: AnyObject) {
let binaryNumber = DecimalToBinary(Int(decimalNumberText.stringValue)!)
toBinaryLabel.stringValue = binaryNumber
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
```
how it should be transformed? | 2016/06/08 | [
"https://Stackoverflow.com/questions/37700883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4752617/"
] | If you are using NSTextField for input then set its delegate to self and use [NSTextFieldDelegate](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSTextFieldDelegate_Protocol/index.html#//apple_ref/swift/intf/c:objc(pl)NSTextFieldDelegate)'s **controlTextDidChange** delegate.
In this delegate you can call your conversion script and functions and display the result on your specific label.
```
import Cocoa
class DecimalView: NSViewController, NSTextFieldDelegate {
@IBOutlet weak var decimalNumberText: NSTextField!
@IBOutlet weak var toBinaryLabel: NSTextField!
func convertNumber() {
let binaryNumber = DecimalToBinary(Int(decimalNumberText.stringValue)!)
toBinaryLabel.stringValue = binaryNumber
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
decimalNumberText.delegate = self
}
override func controlTextDidChange(obj: NSNotification) {
// Call your conversion functions here and display the result on label
if obj.object as! NSTextField == decimalNumberText {
self.convertNumber()
}
}
}
``` | I'm assuming you are using an NSTextField. For this you have to use the and its method `textDidChange:`. In this method just call your functions and set the value to label.
Reference from: [NSTextField value changed](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSTextField_Class/#//apple_ref/occ/instm/NSTextField/textDidChange:) |
39,799,104 | I was trying to Transfer my Access Table Data over to SQL server but I am getting an error which says
>
> Object Variable or With block variable not set
>
>
>
I've already connected my Access database with SQL server but now facing problem transferring data to SQL server with VBA code.
Can you please help me with it?
Here is my code:
```
Public Sub ADOtest()
Dim ADOConn As New ADODB.Connection
Dim ADOCom As New ADODB.Command
On Error Resume Next
ADOConn.ConnectionString = "Driver={SQL Server};Server=IT-TEMP2-8470P\SQLEXPRESS2014;Database=Discrepancy;Trusted_Connection=True;"
ADOConn.Open
Debug.Print ADOConn.State
Dim db As Database
Dim Discrepancy As Database
Set db = Discrepancy
Dim ID As Variant
db.Execute "INSERT INTO [ODBC;DRIVER=SQL Server;SERVER=IT-TEMP2-8470P\SQLEXPRESS2014;DATABASE=Discrepancy].SFTransfersDB ( ID, TO ) SELECT ID,TO FROM SFTransfersDB"
End Sub
```
I am getting error at the 2nd last line:
```
db.Execute "INSERT INTO [ODBC;DRIVER=SQL Server;SERVER=IT-TEMP2-8470P\SQLEXPRESS2014;DATABASE=Discrepancy].SFTransfersDB ( ID, TO ) SELECT ID,TO FROM SFTransfersDB"
``` | 2016/09/30 | [
"https://Stackoverflow.com/questions/39799104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6523744/"
] | It seems you are attempting an ad hoc distributed query. If server permits it, consider executing this statement after your ADO connection. No need for calling Access objects.
```
ADOConn.Execute "INSERT INTO dbo.SFTransfersDB ([ID], [TO])" _
" SELECT [ID], [TO] FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0', " _
"'Data Source=""C:\Path\To\Access\Database.accdb""')...SFTransfersDB;"
``` | You declare two Database variables, but don't initialize them (you don't set them to anything):
```
Dim db As Database
Dim Discrepancy As Database
```
So this
```
Set db = Discrepancy
```
is the same as
```
Set db = Nothing
```
and so when you try to use `db`, you get the error that `db` is not set, which it isn't. |
39,799,104 | I was trying to Transfer my Access Table Data over to SQL server but I am getting an error which says
>
> Object Variable or With block variable not set
>
>
>
I've already connected my Access database with SQL server but now facing problem transferring data to SQL server with VBA code.
Can you please help me with it?
Here is my code:
```
Public Sub ADOtest()
Dim ADOConn As New ADODB.Connection
Dim ADOCom As New ADODB.Command
On Error Resume Next
ADOConn.ConnectionString = "Driver={SQL Server};Server=IT-TEMP2-8470P\SQLEXPRESS2014;Database=Discrepancy;Trusted_Connection=True;"
ADOConn.Open
Debug.Print ADOConn.State
Dim db As Database
Dim Discrepancy As Database
Set db = Discrepancy
Dim ID As Variant
db.Execute "INSERT INTO [ODBC;DRIVER=SQL Server;SERVER=IT-TEMP2-8470P\SQLEXPRESS2014;DATABASE=Discrepancy].SFTransfersDB ( ID, TO ) SELECT ID,TO FROM SFTransfersDB"
End Sub
```
I am getting error at the 2nd last line:
```
db.Execute "INSERT INTO [ODBC;DRIVER=SQL Server;SERVER=IT-TEMP2-8470P\SQLEXPRESS2014;DATABASE=Discrepancy].SFTransfersDB ( ID, TO ) SELECT ID,TO FROM SFTransfersDB"
``` | 2016/09/30 | [
"https://Stackoverflow.com/questions/39799104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6523744/"
] | You declare two Database variables, but don't initialize them (you don't set them to anything):
```
Dim db As Database
Dim Discrepancy As Database
```
So this
```
Set db = Discrepancy
```
is the same as
```
Set db = Nothing
```
and so when you try to use `db`, you get the error that `db` is not set, which it isn't. | Thanks for your suggestions.
I got it correct after all.
I used "Set db = CurrentDb" and it worked perfect. |
39,799,104 | I was trying to Transfer my Access Table Data over to SQL server but I am getting an error which says
>
> Object Variable or With block variable not set
>
>
>
I've already connected my Access database with SQL server but now facing problem transferring data to SQL server with VBA code.
Can you please help me with it?
Here is my code:
```
Public Sub ADOtest()
Dim ADOConn As New ADODB.Connection
Dim ADOCom As New ADODB.Command
On Error Resume Next
ADOConn.ConnectionString = "Driver={SQL Server};Server=IT-TEMP2-8470P\SQLEXPRESS2014;Database=Discrepancy;Trusted_Connection=True;"
ADOConn.Open
Debug.Print ADOConn.State
Dim db As Database
Dim Discrepancy As Database
Set db = Discrepancy
Dim ID As Variant
db.Execute "INSERT INTO [ODBC;DRIVER=SQL Server;SERVER=IT-TEMP2-8470P\SQLEXPRESS2014;DATABASE=Discrepancy].SFTransfersDB ( ID, TO ) SELECT ID,TO FROM SFTransfersDB"
End Sub
```
I am getting error at the 2nd last line:
```
db.Execute "INSERT INTO [ODBC;DRIVER=SQL Server;SERVER=IT-TEMP2-8470P\SQLEXPRESS2014;DATABASE=Discrepancy].SFTransfersDB ( ID, TO ) SELECT ID,TO FROM SFTransfersDB"
``` | 2016/09/30 | [
"https://Stackoverflow.com/questions/39799104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6523744/"
] | It seems you are attempting an ad hoc distributed query. If server permits it, consider executing this statement after your ADO connection. No need for calling Access objects.
```
ADOConn.Execute "INSERT INTO dbo.SFTransfersDB ([ID], [TO])" _
" SELECT [ID], [TO] FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0', " _
"'Data Source=""C:\Path\To\Access\Database.accdb""')...SFTransfersDB;"
``` | Thanks for your suggestions.
I got it correct after all.
I used "Set db = CurrentDb" and it worked perfect. |
4,500,134 | Hello I am a big fan of Git and Hg and have to use them both on many projects. I currently use Posh-Hg, which is a powershell plugin that places the current branch and outstanding commit right in your powershell. Posh-Git operates in a similar manner except for Git. Has anyone successfully gotten the two powershell scripts to play nice together?
<http://poshhg.codeplex.com/>
<http://github.com/dahlbyk/posh-git>
 | 2010/12/21 | [
"https://Stackoverflow.com/questions/4500134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86411/"
] | Try this one in your profile script:
```
function isCurrentDirectoryARepository($type) {
if ((Test-Path $type) -eq $TRUE) {
return $TRUE
}
# Test within parent dirs
$checkIn = (Get-Item .).parent
while ($checkIn -ne $NULL) {
$pathToTest = $checkIn.fullname + '/' + $type;
if ((Test-Path $pathToTest) -eq $TRUE) {
return $TRUE
} else {
$checkIn = $checkIn.parent
}
}
return $FALSE
}
# Posh-Hg and Posh-git prompt
. $ProfileRoot\Modules\posh-hg\profile.example.ps1
. $ProfileRoot\Modules\posh-git\profile.example.ps1
function prompt(){
# Reset color, which can be messed up by Enable-GitColors
$Host.UI.RawUI.ForegroundColor = $GitPromptSettings.DefaultForegroundColor
Write-Host($pwd) -nonewline
if (isCurrentDirectoryARepository(".git")) {
# Git Prompt
$Global:GitStatus = Get-GitStatus
Write-GitStatus $GitStatus
} elseif (isCurrentDirectoryARepository(".hg")) {
# Mercurial Prompt
$Global:HgStatus = Get-HgStatus
Write-HgStatus $HgStatus
}
return "> "
}
``` | Please note, that issue is now fixed. Assuming that you have last versions of the Posh-Hg and Posh-Git, your profile should include only.
```
# Posh-Hg and Posh-git prompt
. $ProfileRoot\Modules\posh-hg\profile.example.ps1
. $ProfileRoot\Modules\posh-git\profile.example.ps1
``` |
4,500,134 | Hello I am a big fan of Git and Hg and have to use them both on many projects. I currently use Posh-Hg, which is a powershell plugin that places the current branch and outstanding commit right in your powershell. Posh-Git operates in a similar manner except for Git. Has anyone successfully gotten the two powershell scripts to play nice together?
<http://poshhg.codeplex.com/>
<http://github.com/dahlbyk/posh-git>
 | 2010/12/21 | [
"https://Stackoverflow.com/questions/4500134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86411/"
] | Try this one in your profile script:
```
function isCurrentDirectoryARepository($type) {
if ((Test-Path $type) -eq $TRUE) {
return $TRUE
}
# Test within parent dirs
$checkIn = (Get-Item .).parent
while ($checkIn -ne $NULL) {
$pathToTest = $checkIn.fullname + '/' + $type;
if ((Test-Path $pathToTest) -eq $TRUE) {
return $TRUE
} else {
$checkIn = $checkIn.parent
}
}
return $FALSE
}
# Posh-Hg and Posh-git prompt
. $ProfileRoot\Modules\posh-hg\profile.example.ps1
. $ProfileRoot\Modules\posh-git\profile.example.ps1
function prompt(){
# Reset color, which can be messed up by Enable-GitColors
$Host.UI.RawUI.ForegroundColor = $GitPromptSettings.DefaultForegroundColor
Write-Host($pwd) -nonewline
if (isCurrentDirectoryARepository(".git")) {
# Git Prompt
$Global:GitStatus = Get-GitStatus
Write-GitStatus $GitStatus
} elseif (isCurrentDirectoryARepository(".hg")) {
# Mercurial Prompt
$Global:HgStatus = Get-HgStatus
Write-HgStatus $HgStatus
}
return "> "
}
``` | FYI - there's a sweet Chocolatey package called [Posh-GIT-HG](http://chocolatey.org/packages/Posh-GIT-HG) that does exactly what the [answer](https://stackoverflow.com/questions/4500134/posh-git-and-posh-hg-together/4845935#4845935) above suggests, but has the added benefit of potentially staying in sync with the latest versions of posh-git and posh-hg. |
4,500,134 | Hello I am a big fan of Git and Hg and have to use them both on many projects. I currently use Posh-Hg, which is a powershell plugin that places the current branch and outstanding commit right in your powershell. Posh-Git operates in a similar manner except for Git. Has anyone successfully gotten the two powershell scripts to play nice together?
<http://poshhg.codeplex.com/>
<http://github.com/dahlbyk/posh-git>
 | 2010/12/21 | [
"https://Stackoverflow.com/questions/4500134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86411/"
] | Please note, that issue is now fixed. Assuming that you have last versions of the Posh-Hg and Posh-Git, your profile should include only.
```
# Posh-Hg and Posh-git prompt
. $ProfileRoot\Modules\posh-hg\profile.example.ps1
. $ProfileRoot\Modules\posh-git\profile.example.ps1
``` | FYI - there's a sweet Chocolatey package called [Posh-GIT-HG](http://chocolatey.org/packages/Posh-GIT-HG) that does exactly what the [answer](https://stackoverflow.com/questions/4500134/posh-git-and-posh-hg-together/4845935#4845935) above suggests, but has the added benefit of potentially staying in sync with the latest versions of posh-git and posh-hg. |
64,589,956 | I'm trying to malloc/realloc memory for an array of trace\_t structs.
```
typedef struct {
step_t *head; // pointer to the step in the head of the trace
step_t *tail; // pointer to the step in the tail of the trace
} trace_t;
```
The code runs fine (i think) but my compiler outputted a "dereference of undefined pointer value" warning. What does this mean? On the line that is causing the error I'm only trying to set the head and tail pointers of each trace\_t in the trace\_t array to NULL
```
trace_t**
make_trace_array(trace_t** trace_arr, int request, int limit) {
int i;
if (request==MALLOC) {
trace_arr = (trace_t**)malloc(limit*sizeof(*trace_arr));
assert(trace_arr!=NULL);
for (i=0; i<limit; i++) {
trace_arr[i]->head = trace_arr[i]->tail = NULL; <------------- warning
}
return trace_arr;
} else if (request==REALLOC) {
trace_arr = (trace_t**)realloc((trace_t**)trace_arr, (limit*2)*sizeof(*trace_arr));
assert(trace_arr!=NULL);
// may b bug
for (i=limit; i<limit*2; i++) {
trace_arr[i]->head = trace_arr[i]->tail = NULL; <------------- warning
}
return trace_arr;
}
printf("Invalid request");
return NULL;
}
``` | 2020/10/29 | [
"https://Stackoverflow.com/questions/64589956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13238932/"
] | It means that the pointer produced by this expression
```
trace_arr[i]
```
has indeterminate value.
That is you did not initialized the dynamically allocated array pointed to by the pointer `trace_arr`.
In for loops like for example this
```
for (i=0; i<limit; i++) {
trace_arr[i]->head = trace_arr[i]->tail = NULL; <------------- warning
}
}
```
you need insert a memory allocation for elements `trace_arr[i]`.
Something like
```
trace_arr[i] = malloc( sizeof( trace_t ) );
```
Pay attention to that the function is unsafe. For example the function realloc used in this statement
```
trace_arr = (trace_t**)realloc((trace_t**)trace_arr, (limit*2)*sizeof(*trace_arr));
```
can return a null-pointer. In this case after the assignment you will lost the original pointer to the previously allocated memory.
A better approach is declare the function the following way
```
int make_trace_array(trace_t ***trace_arr, int request, int limit);
```
That is the function will return either success or failure and the original poiner will be passed to the function by value. Within function you have to check whether a call of malloc or realloc was successfull. | Assigning a value to `trace_arr` does not assign any value to `trace_arr[i]` but you use `trace_arr[i]` in `trace_arr[i]->head = …` |
64,589,956 | I'm trying to malloc/realloc memory for an array of trace\_t structs.
```
typedef struct {
step_t *head; // pointer to the step in the head of the trace
step_t *tail; // pointer to the step in the tail of the trace
} trace_t;
```
The code runs fine (i think) but my compiler outputted a "dereference of undefined pointer value" warning. What does this mean? On the line that is causing the error I'm only trying to set the head and tail pointers of each trace\_t in the trace\_t array to NULL
```
trace_t**
make_trace_array(trace_t** trace_arr, int request, int limit) {
int i;
if (request==MALLOC) {
trace_arr = (trace_t**)malloc(limit*sizeof(*trace_arr));
assert(trace_arr!=NULL);
for (i=0; i<limit; i++) {
trace_arr[i]->head = trace_arr[i]->tail = NULL; <------------- warning
}
return trace_arr;
} else if (request==REALLOC) {
trace_arr = (trace_t**)realloc((trace_t**)trace_arr, (limit*2)*sizeof(*trace_arr));
assert(trace_arr!=NULL);
// may b bug
for (i=limit; i<limit*2; i++) {
trace_arr[i]->head = trace_arr[i]->tail = NULL; <------------- warning
}
return trace_arr;
}
printf("Invalid request");
return NULL;
}
``` | 2020/10/29 | [
"https://Stackoverflow.com/questions/64589956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13238932/"
] | You want an array of structs, but you handle it like an array of pointers.
You need to get rid of one level of indirection.
This could look as follows (not compiled):
```
trace_t*
make_trace_array(trace_t** trace_arr, int request, int limit) {
int i;
assert(trace_arr != NULL);
if (request==MALLOC) {
trace_t *arr = malloc(limit*sizeof(*arr));
assert(arr!=NULL);
for (i=0; i<limit; i++) {
arr[i].head = arr[i].tail = NULL;
}
*trace_arr = arr;
return arr;
} else if (request==REALLOC) {
trace_t *arr = realloc(*trace_arr, (limit*2)*sizeof(*arr));
assert(arr!=NULL);
for (i=limit; i<limit*2; i++) {
arr[i].head = arr[i].tail = NULL;
}
*trace_arr = arr;
return arr;
}
printf("Invalid request");
return NULL;
}
``` | Assigning a value to `trace_arr` does not assign any value to `trace_arr[i]` but you use `trace_arr[i]` in `trace_arr[i]->head = …` |
5,400,060 | I am in the process of creating an [AICC](http://www.aicc.org) (Aviation Industry CBT Committee) compliant LMS using Classic ASP. Does anyone have any experience with this? | 2011/03/23 | [
"https://Stackoverflow.com/questions/5400060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264852/"
] | I haven't used `glPolygonOffset`, but I just read up on it in the [official FAQ](http://www.opengl.org/resources/faq/technical/polygonoffset.htm) -- required reading if you haven't already seen this. There is also the [man page](http://www.opengl.org/sdk/docs/man/xhtml/glPolygonOffset.xml).
According to that reference, the offset is calculated *after* the normal Z calculations, but applied *before* the depth test and before being written to the depth buffer.
I can think of two issues. Firstly, the FAQ recommends you use `glPolygonOffset(1,1)`, not `(0,1)`. The first "factor" argument is multiplied by the slope of the polygon and added to the offset. This is apparently important for "edge-on" polygons. If the polygon is facing the camera, it doesn't matter, but if it is at an angle, the amount you need to push it forward increases with the angle.
Secondly, are you enabling the offset for just one of the polygons? If you have it enabled for both (or forget to disable it), then it will apply to both polygons, and have a net effect of zero.
Thirdly, I suspected that your depth buffer is too large (given that depth buffers have a hyperbolic scale which favours objects close to the camera). I'm not so sure about this, given that `glPolygonOffset` is supposed to work with depth values, not Z values (so the scale of the depth buffer shouldn't be a factor here). You might want to try it with a shorter depth buffer (maybe 1000) and see if that makes a difference. | You can try to set one polygon offset positive one offset negative, I bet that will work.
glPolygonOffset(0,1) and glPolygonOffset(0,-1) |
458,153 | I am using a **Conda** *Python* installation and **Jupyter** to work with a script producing a LaTeX file I want to compile. These are the relevant code lines:
```
import subprocess
xelatex= "/usr/local/texlive/2018/bin/x86_64-darwin/xelatex"
subprocess.check_call([xelatex, '-shell-escape', '-file-line-error', '-interaction=nonstopmode', '-synctex=1', my_folder+'/output_file.tex'])
```
Unfortunately, *the LaTeX source file does not get compiled* and Python returns a non-zero exit status along the following lines:
```
---------------------------------------------------------------------------
CalledProcessError Traceback (most recent call last)
<ipython-input-26-fc4edbf90d41> in <module>
1 import subprocess
2 xelatex= "/usr/local/texlive/2018/bin/x86_64-darwin/xelatex"
----> 3 subprocess.check_call([xelatex, '-shell-escape', '-file-line-error', '-interaction=nonstopmode', '-synctex=1', dir_AED+'/registro_lezioni.tex'])
~/anaconda3/lib/python3.6/subprocess.py in check_call(*popenargs, **kwargs)
289 if cmd is None:
290 cmd = popenargs[0]
--> 291 raise CalledProcessError(retcode, cmd)
292 return 0
293
CalledProcessError: Command '['/usr/local/texlive/2018/bin/x86_64-darwin/xelatex', '-shell-escape', '-file-line-error', '-interaction=nonstopmode', '-synctex=1', 'my_folder+'/output_file.tex']' returned non-zero exit status 1.
```
I have a **Tex Live 2018** installation on my Mac that works smoothly with many other apps:
```
Last login: Sat Nov 3 07:39:44 on ttys000
Restored session: Sat Nov 3 07:33:30 CET 2018MacBook-Pro:~ m*****$ xelatex
This is XeTeX, Version 3.14159265-2.6-0.99999 (TeX Live 2018) (preloaded format=xelatex) restricted \write18 enabled.
**
```
Using any other LaTeX-based app, like Texpad, *the source file gets compiled with no errors*. I went to the Conda terminal window and the problem seems to be that the LaTeX compiler cannot find a ancillary file:
```
ABD: EveryShipout initializing macros
(/usr/local/texlive/2018/texmf-dist/tex/latex/translator/translator-basic-dicti
onary-English.dict)
(/usr/local/texlive/2018/texmf-dist/tex/latex/siunitx/siunitx-abbreviations.cfg
) (/usr/local/texlive/2018/texmf-dist/tex/latex/wasysym/uwasy.fd)
! LaTeX Error: File `fragment.tex' not found.
```
Nevertheless, the file **fragment.tex** does live in the same folder, but the LaTeX compiler cannot find it.
In sum, *I need to instruct the LaTeX compiler to look for files in the same folder where the main source file is located*. | 2018/11/03 | [
"https://tex.stackexchange.com/questions/458153",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/75937/"
] | Welcome to TeX.SE.! As far as I know, a `.pdf` or `.dvi` file can not have such a functionality (for whole pages). But it can have it for comments... something that I suppose is not enough for you. If you open any pdf (or dvi) by using any viewer of your system, you will see that all the pages are visible. So, the I don't think you can do it with just a pdf or dvi file. What I think can work for you, is to create the other pages in a site (a free site of wordpress or a google site would be ok for it) and add in your pdf hyperlinks to this site's hidden pages (that the user can't find through navigation in the page -this is possible in both wordpress sites and google sites-)
An example of a latex code using this functionality, is just any simple (or complicated) template for your CV and the links would work with:
1. `\usepackage{hyperref}` in your preamble, and
2. `\href{www.<YourPage>.wordpress.com/<HiddenPageNonFromNavigation>/}{My Publications}` where "My Publications" is the words that will appear in the pdf file and will drive the user in your "Hidden Page".
The problem is that the reader has to read online this pdf in order to "find" your hidden links, but I think it is the only way.
PS: Hyperlinks to other pdfs could be possible too as a second thought and you could sent a zipped file with all the pdfs, but then the user could open them (and may be could chose one of them as his first choice). You could just use dummy names for these pdfs and a clear name for your main file (preferable a name starting with `0` or `1` in order to be shown as first file in most folder settings of any operating system) | As other answers pointed out there is no way to do what you ask exactly.
As an alternative, you could have some "optional" sections in your resume, and compile both a long and a short version (with/without the optional sections). This way you can choose which version to send depending on who you send it to, or send both versions and let the reader decide which one they want to read.
A simple way to achieve this is to define a new command (or environment) for optional sections:
```
\newcommand{\optional}[1]{#1}
%\newcommand{\optional}[1]{}
```
Use this command for the optional parts, e.g.:
```
\optional{
...
These details won't appear in the short version
...
}
```
To compile the short version, manually change the definition of the command so that it doesn't show the content:
```
%\newcommand{\optional}[1]{#1}
\newcommand{\optional}[1]{}
```
Of course this is not a very sophisticated approach, but I found it convenient for my resume. |
458,153 | I am using a **Conda** *Python* installation and **Jupyter** to work with a script producing a LaTeX file I want to compile. These are the relevant code lines:
```
import subprocess
xelatex= "/usr/local/texlive/2018/bin/x86_64-darwin/xelatex"
subprocess.check_call([xelatex, '-shell-escape', '-file-line-error', '-interaction=nonstopmode', '-synctex=1', my_folder+'/output_file.tex'])
```
Unfortunately, *the LaTeX source file does not get compiled* and Python returns a non-zero exit status along the following lines:
```
---------------------------------------------------------------------------
CalledProcessError Traceback (most recent call last)
<ipython-input-26-fc4edbf90d41> in <module>
1 import subprocess
2 xelatex= "/usr/local/texlive/2018/bin/x86_64-darwin/xelatex"
----> 3 subprocess.check_call([xelatex, '-shell-escape', '-file-line-error', '-interaction=nonstopmode', '-synctex=1', dir_AED+'/registro_lezioni.tex'])
~/anaconda3/lib/python3.6/subprocess.py in check_call(*popenargs, **kwargs)
289 if cmd is None:
290 cmd = popenargs[0]
--> 291 raise CalledProcessError(retcode, cmd)
292 return 0
293
CalledProcessError: Command '['/usr/local/texlive/2018/bin/x86_64-darwin/xelatex', '-shell-escape', '-file-line-error', '-interaction=nonstopmode', '-synctex=1', 'my_folder+'/output_file.tex']' returned non-zero exit status 1.
```
I have a **Tex Live 2018** installation on my Mac that works smoothly with many other apps:
```
Last login: Sat Nov 3 07:39:44 on ttys000
Restored session: Sat Nov 3 07:33:30 CET 2018MacBook-Pro:~ m*****$ xelatex
This is XeTeX, Version 3.14159265-2.6-0.99999 (TeX Live 2018) (preloaded format=xelatex) restricted \write18 enabled.
**
```
Using any other LaTeX-based app, like Texpad, *the source file gets compiled with no errors*. I went to the Conda terminal window and the problem seems to be that the LaTeX compiler cannot find a ancillary file:
```
ABD: EveryShipout initializing macros
(/usr/local/texlive/2018/texmf-dist/tex/latex/translator/translator-basic-dicti
onary-English.dict)
(/usr/local/texlive/2018/texmf-dist/tex/latex/siunitx/siunitx-abbreviations.cfg
) (/usr/local/texlive/2018/texmf-dist/tex/latex/wasysym/uwasy.fd)
! LaTeX Error: File `fragment.tex' not found.
```
Nevertheless, the file **fragment.tex** does live in the same folder, but the LaTeX compiler cannot find it.
In sum, *I need to instruct the LaTeX compiler to look for files in the same folder where the main source file is located*. | 2018/11/03 | [
"https://tex.stackexchange.com/questions/458153",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/75937/"
] | One solution could be `xr-hyper`:
[](https://i.stack.imgur.com/c0pVV.png)
curriculum.tex:
```
\documentclass[twocolumn]{article}
\usepackage{xr-hyper}
\usepackage[colorlinks,allcolors=blue]{hyperref}
\externaldocument{001}
\externaldocument{002}
\usepackage{nameref}
\parindent0pt
\begin{document}
\section*{\em\centering Curriculum vitae}
\ref{pub}. \nameref{pub} \dotfill \pageref{pub}\par
\ref{books}. \nameref{books}\dotfill \pageref{books}\par
\ref{jobs}. \nameref{jobs} \dotfill \pageref{jobs}\par
\end{document}
```
001.tex:
```
\documentclass{article}
\usepackage{hyperref}
\usepackage{lipsum}
\begin{document}
\section{Publications}\label{pub}\lipsum[1-20]
\subsection{Books}\label{books}
\lipsum[21-30]
\end{document}
```
002.tex:
```
\documentclass{article}
\usepackage{hyperref}
\setcounter{page}{23}
\setcounter{section}{1}
\begin{document}
\section{Experience}\label{jobs} Lore ipsum ...
\end{document}
```
Note that you must compile main document at least twice but after compiling each child document.
Obviously, this way anyone could see that there are child files (001.pdf, 002.pdf, etc.) in the directory. You could try to hidden them a bit, using a subdirectory for child files (warning: not tested) or use invisible/hidden filenames or even hiden subfolders, but consider the thymaro's comments: *Hide the merits ... for what? surely, there's something fishy here. Where is the trash icon?* | As other answers pointed out there is no way to do what you ask exactly.
As an alternative, you could have some "optional" sections in your resume, and compile both a long and a short version (with/without the optional sections). This way you can choose which version to send depending on who you send it to, or send both versions and let the reader decide which one they want to read.
A simple way to achieve this is to define a new command (or environment) for optional sections:
```
\newcommand{\optional}[1]{#1}
%\newcommand{\optional}[1]{}
```
Use this command for the optional parts, e.g.:
```
\optional{
...
These details won't appear in the short version
...
}
```
To compile the short version, manually change the definition of the command so that it doesn't show the content:
```
%\newcommand{\optional}[1]{#1}
\newcommand{\optional}[1]{}
```
Of course this is not a very sophisticated approach, but I found it convenient for my resume. |
56,466,566 | I am trying to scrape a website for deals, specifically when a product is 100% off.
How can I find all span tags within this page, if any, that have a value of -100%, for example `<span>-100%</span>`.
If one of these is found how can I get the parent a tag that it is nested in.
I am using python 3.x and beautiful soup.
Here is the code I am using now:
```
from bs4 import BeautifulSoup
import urllib.request
link = 'https://store.steampowered.com/search/?sort_by=Price_ASC&ignore_preferences=1&page=524'
html = urllib.request.urlopen(link)
soup = BeautifulSoup(html, "html.parser")
parents = [element.parent for element in soup.find_all("span", string="-80%")]
print(parents)
``` | 2019/06/05 | [
"https://Stackoverflow.com/questions/56466566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8142205/"
] | Perhaps you should be using destSheet rather than Activesheet, since Activesheet isn't defined. Otherwise, you should prefix Activesheet with objExcelApp, thus:
```
objExcelApp.Activesheet
``` | Since you're running this in Word, VBA only "knows" things that belong to the Word *object model* unless the code specifically indicates a different object model is the source. Word knows nothing about "Sheets" - only Excel knows what `ActiveSheet` is.
Even though the code you show us doesn't call the procedure `PrintFirstColumnOnActiveSheetToSheetName()`, where `ActiveSheet` is used, VBA *sees* it when it compiles the code. So you need to pass a reference to the Excel application to this procedure and use it. For example:
```
Public Sub PrintFirstColumnOnActiveSheetToSheetName(objExcel as Object)
objExcel.ActiveSheet.Name = objExcel.ActiveSheet.Range("A1")
End Sub
```
To call this elsewhere in your code it would look something like the following line. Notice that the variable names for the same object do not need to be the same in different procedures - they can be, but it's not necessary. VBA "remembers" that the Excel application started previously is what's been passed to another procedure.
```
PrintFirstColumnOnActiveSheetToSheetName objExcelApp
``` |
39,465,354 | I've just create a new table in my sqlserver name exporttable
now I'm trying to push out using cmd bcp but om getting this following error:
>
> SQLState = S1000, NativeError = 0 Error = [Microsoft][ODBC Driver 13
> for SQL Server]Unable to open BCP host data-file
>
>
>
Here is my path:
```
C:\Users\Serge>BCP Testing.bdo.Exporttable out "C:\Users\Serge\Desktop" -C -T
```
anyone can help ?
After trying Shnugos suggestion to add a filename I got this error:
>
> SQLState = S0002, NativeError = 208 Error = [Microsoft][ODBC Driver 13
> for SQL Server][SQL Server]Invalid object name
> 'Testing.bdo.ExportTable'. SQLState = 37000, NativeError = 11529 Error
> = [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The metadata could not be determined because every code path results in an error;
> see previous errors for some of these. –
>
>
> | 2016/09/13 | [
"https://Stackoverflow.com/questions/39465354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5998444/"
] | From the error I take, that the data file cannot be opened:
```
C:\Users\Serge>BCP Testing.bdo.Exporttable out "C:\Users\Serge\Desktop\MyFile.txt" -C -T
```
I think, you have to add a filename behind the `\Desktop`. *Desktop* is an existing directory and cannot be opened as file ...
And - btw - it might be necessary to add `-S Servername`...
UPDATE
------
Found this [here](http://www.sqlservercentral.com/Forums/Topic237238-8-1.aspx)
>
> Whenever I get this message, it's because of one of three things:
>
>
> 1) The path/filename is incorrect (check your typing / spelling)
>
>
> 2) The file does not exist. (make sure the file is where you expect it
> to be)
>
>
> 3) The file is already open by some other app. (close the other app to
> release the file)
>
>
> For 1) and 2) - remember that paths are relative to where bcp is
> executing. Make sure that bcp.exe can access the file/path from it's
> context.
>
>
> /Kenneth
>
>
> | I know this is old, but you also appear to have the schema spelled wrong.
C:\Users\Serge>BCP Testing.**bdo**.Exporttable out "C:\Users\Serge\Desktop" -C -T
s/b
C:\Users\Serge>BCP Testing.**dbo**.Exporttable out "C:\Users\Serge\Desktop" -C -T |
39,465,354 | I've just create a new table in my sqlserver name exporttable
now I'm trying to push out using cmd bcp but om getting this following error:
>
> SQLState = S1000, NativeError = 0 Error = [Microsoft][ODBC Driver 13
> for SQL Server]Unable to open BCP host data-file
>
>
>
Here is my path:
```
C:\Users\Serge>BCP Testing.bdo.Exporttable out "C:\Users\Serge\Desktop" -C -T
```
anyone can help ?
After trying Shnugos suggestion to add a filename I got this error:
>
> SQLState = S0002, NativeError = 208 Error = [Microsoft][ODBC Driver 13
> for SQL Server][SQL Server]Invalid object name
> 'Testing.bdo.ExportTable'. SQLState = 37000, NativeError = 11529 Error
> = [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The metadata could not be determined because every code path results in an error;
> see previous errors for some of these. –
>
>
> | 2016/09/13 | [
"https://Stackoverflow.com/questions/39465354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5998444/"
] | If you are running BCP through xp\_cmdshell, run the following-->
xp\_cmdshell 'whoami';
GO
--Make sure whatever user value you get back has full access to the file in question | I know this is old, but you also appear to have the schema spelled wrong.
C:\Users\Serge>BCP Testing.**bdo**.Exporttable out "C:\Users\Serge\Desktop" -C -T
s/b
C:\Users\Serge>BCP Testing.**dbo**.Exporttable out "C:\Users\Serge\Desktop" -C -T |
39,465,354 | I've just create a new table in my sqlserver name exporttable
now I'm trying to push out using cmd bcp but om getting this following error:
>
> SQLState = S1000, NativeError = 0 Error = [Microsoft][ODBC Driver 13
> for SQL Server]Unable to open BCP host data-file
>
>
>
Here is my path:
```
C:\Users\Serge>BCP Testing.bdo.Exporttable out "C:\Users\Serge\Desktop" -C -T
```
anyone can help ?
After trying Shnugos suggestion to add a filename I got this error:
>
> SQLState = S0002, NativeError = 208 Error = [Microsoft][ODBC Driver 13
> for SQL Server][SQL Server]Invalid object name
> 'Testing.bdo.ExportTable'. SQLState = 37000, NativeError = 11529 Error
> = [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The metadata could not be determined because every code path results in an error;
> see previous errors for some of these. –
>
>
> | 2016/09/13 | [
"https://Stackoverflow.com/questions/39465354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5998444/"
] | Run: EXEC master..xp\_cmdshell 'DIR C:\Users\Serge\Desktop', this will show if you have access to the path.
Remember if you are accessing SQL remotely or over a network, the output ie. "C:\Users\Serge\Desktop" will be the C drive on the SQL Server, not your remote PC you are working on. | I know this is old, but you also appear to have the schema spelled wrong.
C:\Users\Serge>BCP Testing.**bdo**.Exporttable out "C:\Users\Serge\Desktop" -C -T
s/b
C:\Users\Serge>BCP Testing.**dbo**.Exporttable out "C:\Users\Serge\Desktop" -C -T |
29,642,560 | I usually do a project and deploy it on the client machine, but all the Ruby/WATIR scripts are clearly visible to everyone. Is there any way to hide my code? Or is there any way I can secure my code? Or Is there any way to lock a folder through Ruby? | 2015/04/15 | [
"https://Stackoverflow.com/questions/29642560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4091011/"
] | You could use jRuby and create a JAR using [Warbler](https://github.com/jruby/warbler) but that will only stop non-geek users. [Here](https://sqa.stackexchange.com/questions/5364/watir-webdriver-in-conjunction-with-java) a link about using watir in jRuby
Converting the script to an executable file like with [Ocra](http://rubyonwindows.blogspot.be/2009/05/ocra-one-click-ruby-application-builder.html) is also an option.
Securing the script and let it run in another security context could work.
But what I would do is make it a web-app that can be run anywhere while nobody can see the source code. With a nice framework like [Sinatra](http://www.sinatrarb.com/) that shouldn't be that hard. | Code obfuscation is one option. You can use tools like [RubyScript2Exe](http://www.erikveen.dds.nl/rubyscript2exe/) or [AllInOneRuby](http://www.erikveen.dds.nl/allinoneruby/index.html) to obfuscate your code or make them difficult to understand. However these tools have their own flaws which are nicely discussed [here](https://stackoverflow.com/a/2123468/3035830). |
20,694,959 | I'm facing a problem with my Async task. I have some normal operations to accomplish in the background and view results after it completes however the UI freezes although my code inside the doinbackground block. Please help me!
Hereunder my code.
```
class DownloadFileFromURL extends AsyncTask<String, Void, String> {
/**
* Before starting background thread Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(Interface.this, null, "Loading...", true);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
//
// Toast.makeText(getApplicationContext(), "Executing",
// 3000).show();
runOnUiThread(new Runnable() {
public void run() {
Calculate();
}
});
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
}
/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
pd.dismiss();
}
}
private void Calculate()
{
curs = mDb.query(MyDbHelper.TABLE_NAME, columns, MyDbHelper.COL_Common
+ "=" + "?", new String[] { From[xxxto] + From[xxxfrom] },
null, null, null);
cursD = mDb.query(MyDbHelper.TABLE_NAME, columns, MyDbHelper.COL_Common
+ "=" + "?", new String[] { From[xxxfrom] + From[xxxto] },
null, null, null);
curs.moveToFirst();
cursD.moveToFirst();
double selection = curs.getDouble(curs
.getColumnIndex(MyDbHelper.COL_Currone));
double selection2 = cursD.getDouble(cursD
.getColumnIndex(MyDbHelper.COL_Currone));
Long myNum = Long.parseLong(valval.getText().toString().trim());
double myNum3 = Double.parseDouble(new DecimalFormat("#.######")
.format(myNum * selection2));
valval2.setText(String.valueOf(myNum3));
/*
Cursor B = mDb
.query(MyDbHelper.TABLE_NAME, columns, MyDbHelper.COL_CurrFavor
+ "=? And " + MyDbHelper.COL_Currsecond + "=?",
new String[] { "YES", "EUR" }, null, null, null);
*/
Cursor B = mDb.rawQuery("select * from "
+ MyDbHelper.TABLE_NAME + " where " + MyDbHelper.COL_CurrFavor + " = ? AND "
+ MyDbHelper.COL_Currsecond + " = ?", new String[] { "YES", "EUR" });
for (int s = 0; s < 4 - 1; s++)
{
B.moveToPosition(s);
String ZVZV = B.getString(0);
int BSBS = B.getInt(9);
Cursor curcur = mDb.query(MyDbHelper.TABLE_NAME, columns,
MyDbHelper.COL_Common + "=" + "?",
new String[] { From[xxxfrom] + From[BSBS - 1] }, null,
null, null);
curcur.moveToFirst();
double calcal = curcur.getDouble(6);
ContentValues args = new ContentValues();
double formattedNumber = Double.parseDouble(new DecimalFormat(
"#.######").format(myNum * calcal));
args.put(MyDbHelper.COL_Currsum, formattedNumber);
mDb.update(MyDbHelper.TABLE_NAME, args, "_id =" + ZVZV, null);
}
cursm.requery();
}
```
Here is the error in the Logcat :
>
> 12-20 04:41:38.469: E/AndroidRuntime(440): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
>
>
>
Also I run it using : new DownloadFileFromURL2().execute(""); | 2013/12/20 | [
"https://Stackoverflow.com/questions/20694959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332606/"
] | **Do not do not do not** do this in `AsyncTask`
```
runOnUiThread(new Runnable() {
public void run() {
```
every method in `AsyncTask` runs on the `UI Thread` except for `doInBackground()`. Do your work in `doInBackground()` (your calculations, network operations, and such) then get a result from that and update the `UI` in `onProgressUpdate()` by calling `publishProgress()` or, if the background work is completely finished, return a result to `onPostExecute()` and you can update there.
If that doesn't solve your current problem then post how you call the task...hopefully not with `.get()`.
**Edit**
Also, you should look at the Docs again, you aren't actually passing anything to `doInBackground()` but an empty `String` in `.execute()`
```
new DownloadFileFromURL2().execute("");
```
so you could change the first `param` of the declaration to `Void`
```
class DownloadFileFromURL extends AsyncTask<Void, Void, String> {
```
and not pass it anything
```
new DownloadFileFromURL2().execute();
```
unless you were planning on updating this later. You also aren't passing `onPostExecute()` anything from `doInBackground()` with
```
return null;
```
so you could change the `params` it takes. So now we have
```
class DownloadFileFromURL extends AsyncTask<Void, Void, Void> {
```
and
```
@Override
protected void onPostExecute(Void result) {
```
and again you have your `onProgressUpdate()` taking no `params` in your task class declaration (second `param`)
```
class DownloadFileFromURL extends AsyncTask<Void, Void, Void> {
```
so it should look like
```
protected void onProgressUpdate(Void... progress) {
// setting progress percentage
}
```
Of course those all depend on what you plan on passing them which you will need to pass something to update the `UI` after getting results from your `Calculate()` method. | This is where you are doing it wrong.
```
runOnUiThread(new Runnable() {
public void run() {
Calculate();
}
});
```
Here you are calling the `Calculate()` method in the UI thread again. That's why your app freezes. Just call `Calculate()` inside `doInBackground()`. |
20,694,959 | I'm facing a problem with my Async task. I have some normal operations to accomplish in the background and view results after it completes however the UI freezes although my code inside the doinbackground block. Please help me!
Hereunder my code.
```
class DownloadFileFromURL extends AsyncTask<String, Void, String> {
/**
* Before starting background thread Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(Interface.this, null, "Loading...", true);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
//
// Toast.makeText(getApplicationContext(), "Executing",
// 3000).show();
runOnUiThread(new Runnable() {
public void run() {
Calculate();
}
});
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
}
/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
pd.dismiss();
}
}
private void Calculate()
{
curs = mDb.query(MyDbHelper.TABLE_NAME, columns, MyDbHelper.COL_Common
+ "=" + "?", new String[] { From[xxxto] + From[xxxfrom] },
null, null, null);
cursD = mDb.query(MyDbHelper.TABLE_NAME, columns, MyDbHelper.COL_Common
+ "=" + "?", new String[] { From[xxxfrom] + From[xxxto] },
null, null, null);
curs.moveToFirst();
cursD.moveToFirst();
double selection = curs.getDouble(curs
.getColumnIndex(MyDbHelper.COL_Currone));
double selection2 = cursD.getDouble(cursD
.getColumnIndex(MyDbHelper.COL_Currone));
Long myNum = Long.parseLong(valval.getText().toString().trim());
double myNum3 = Double.parseDouble(new DecimalFormat("#.######")
.format(myNum * selection2));
valval2.setText(String.valueOf(myNum3));
/*
Cursor B = mDb
.query(MyDbHelper.TABLE_NAME, columns, MyDbHelper.COL_CurrFavor
+ "=? And " + MyDbHelper.COL_Currsecond + "=?",
new String[] { "YES", "EUR" }, null, null, null);
*/
Cursor B = mDb.rawQuery("select * from "
+ MyDbHelper.TABLE_NAME + " where " + MyDbHelper.COL_CurrFavor + " = ? AND "
+ MyDbHelper.COL_Currsecond + " = ?", new String[] { "YES", "EUR" });
for (int s = 0; s < 4 - 1; s++)
{
B.moveToPosition(s);
String ZVZV = B.getString(0);
int BSBS = B.getInt(9);
Cursor curcur = mDb.query(MyDbHelper.TABLE_NAME, columns,
MyDbHelper.COL_Common + "=" + "?",
new String[] { From[xxxfrom] + From[BSBS - 1] }, null,
null, null);
curcur.moveToFirst();
double calcal = curcur.getDouble(6);
ContentValues args = new ContentValues();
double formattedNumber = Double.parseDouble(new DecimalFormat(
"#.######").format(myNum * calcal));
args.put(MyDbHelper.COL_Currsum, formattedNumber);
mDb.update(MyDbHelper.TABLE_NAME, args, "_id =" + ZVZV, null);
}
cursm.requery();
}
```
Here is the error in the Logcat :
>
> 12-20 04:41:38.469: E/AndroidRuntime(440): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
>
>
>
Also I run it using : new DownloadFileFromURL2().execute(""); | 2013/12/20 | [
"https://Stackoverflow.com/questions/20694959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1332606/"
] | **Do not do not do not** do this in `AsyncTask`
```
runOnUiThread(new Runnable() {
public void run() {
```
every method in `AsyncTask` runs on the `UI Thread` except for `doInBackground()`. Do your work in `doInBackground()` (your calculations, network operations, and such) then get a result from that and update the `UI` in `onProgressUpdate()` by calling `publishProgress()` or, if the background work is completely finished, return a result to `onPostExecute()` and you can update there.
If that doesn't solve your current problem then post how you call the task...hopefully not with `.get()`.
**Edit**
Also, you should look at the Docs again, you aren't actually passing anything to `doInBackground()` but an empty `String` in `.execute()`
```
new DownloadFileFromURL2().execute("");
```
so you could change the first `param` of the declaration to `Void`
```
class DownloadFileFromURL extends AsyncTask<Void, Void, String> {
```
and not pass it anything
```
new DownloadFileFromURL2().execute();
```
unless you were planning on updating this later. You also aren't passing `onPostExecute()` anything from `doInBackground()` with
```
return null;
```
so you could change the `params` it takes. So now we have
```
class DownloadFileFromURL extends AsyncTask<Void, Void, Void> {
```
and
```
@Override
protected void onPostExecute(Void result) {
```
and again you have your `onProgressUpdate()` taking no `params` in your task class declaration (second `param`)
```
class DownloadFileFromURL extends AsyncTask<Void, Void, Void> {
```
so it should look like
```
protected void onProgressUpdate(Void... progress) {
// setting progress percentage
}
```
Of course those all depend on what you plan on passing them which you will need to pass something to update the `UI` after getting results from your `Calculate()` method. | You are calling Calculate() on UI thread.Which will definitely freezes the UI .
Remove all the Ui stuff from calculate() and call it directly inside Async. |
12,287,189 | This sounds very backwards, but I want to take existing CSS classes and make them inline in the element itself (The css styles and the html elements are in the same file). There is a reason for this, for which I will not go into detail.
Example:
```
<html>
<style type="text/css">
.p1 { height: 10px; }
</style>
<body>
<p class="p1">...</p> <!-- Remove class="p1" and replace with style="height: 10px;" -->
<p class="p1">...</p>
<p class="p1">...</p>
</body>
</html>
```
Keep in mind there can be *many* CSS classes, and many can belong to a single element.
**Edit:** The reason I'm doing this is because (based on our client) we want to generate PDF documents from an HTML template. The PDF tool we use does not work well with *external* CSS classes. | 2012/09/05 | [
"https://Stackoverflow.com/questions/12287189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/175057/"
] | You are looking for [Premailer](http://premailer.dialect.ca/) ([The source available as well](https://github.com/alexdunae/premailer/)) - it is a Ruby library that does just that (inlines CSS for HTML email - but the output isn't specific to HTML email - it should work just fine with your PDF document generator as well).
There is also [`lamson.html.HtmlMail`](http://lamsonproject.org/docs/html_email_generation.html) if you are using Python and there are a variety of Node.js libraries available to do the same thing. | MailChimp has a page for this in their labs, the CSS Inliner -
<http://beaker.mailchimp.com/inline-css>
It does leave the class, however. |
62,456,117 | Trying to do Fermat's Little Theorem and noticed it wasn't working in C so I tried it in Python and it worked fine.
**Fermat's Little Theorem**
>
> <https://mathworld.wolfram.com/FermatsLittleTheorem.html>
>
>
>
The answer is supposed to give me a 1 but I'm getting 13.
**Python exponent(working)**
```
prime_num = 13**(17-1)
>665416609183179841
prime_num%17 = 1
```
**C exponent(not working)**
```
double prime_num = pow(13,17-1)
>665416609183179904
fmod(prime_num,17) = 13
``` | 2020/06/18 | [
"https://Stackoverflow.com/questions/62456117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13770686/"
] | In C the pow() function takes and returns double precision floating point values which are approximations.
In Python the \*\* operator does the operation using Python integers, grow in size (memory used to hold the value). If you forced the numbers to be floating points before the operation you'd probably get the same results.
In C you could try writing a different power function that worked with uint64\_t (unsigned long long) and see if that works. | The problem was I should've been using `powl()` which returns a long double instead of a double and I also should've been using `fmodl()` which returns the remainder that has a long double type.
C code working
```
long double prime_num = powl(13,17-1);
>665416609183179841
fmodl(primen_num,17);
>1
``` |
62,456,117 | Trying to do Fermat's Little Theorem and noticed it wasn't working in C so I tried it in Python and it worked fine.
**Fermat's Little Theorem**
>
> <https://mathworld.wolfram.com/FermatsLittleTheorem.html>
>
>
>
The answer is supposed to give me a 1 but I'm getting 13.
**Python exponent(working)**
```
prime_num = 13**(17-1)
>665416609183179841
prime_num%17 = 1
```
**C exponent(not working)**
```
double prime_num = pow(13,17-1)
>665416609183179904
fmod(prime_num,17) = 13
``` | 2020/06/18 | [
"https://Stackoverflow.com/questions/62456117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13770686/"
] | You need to use long long if you want the precision. The problem is there is no pow so it is down to simple multiplication.
```
long long n, val;
int ii;
n = 13LL;
val = n;
for (ii = 2; ii < 17; ++ii)
val *= n;
printf("%lld\n", val);
printf("%lld\n", val % 17LL);
``` | The problem was I should've been using `powl()` which returns a long double instead of a double and I also should've been using `fmodl()` which returns the remainder that has a long double type.
C code working
```
long double prime_num = powl(13,17-1);
>665416609183179841
fmodl(primen_num,17);
>1
``` |
49,910,180 | I just learned about pointers in c++, and my instructor told to create a doubly linked list with a for loop. However, the only example I was given was
```
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
DL_List mylist;
if (mylist.empty())
mylist.insert(n1, mylist.head);
mylist.insert(n2, n1);
mylist.insert(n3, n2);
mylist.insert(n4, n3);
mylist.insert(n5, n4);
mylist.display();
```
I have no idea how to set a for loop for this because I don't know how to name them in the loop, or how I would connect them. | 2018/04/18 | [
"https://Stackoverflow.com/questions/49910180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9666782/"
] | I would just put the class and its input in a tuple:
```
input_data = {...}
my_list = [
{"a": (Class1, input_data)},
{"b": (Class2, input_data)},
{"c": (Class3, input_data)}
]
```
Then when I want to instantiate:
```
tup = my_list[0]["a"]
instantiated_class = tup[0](tup[1])
``` | I feel that you are looking for a dictionary with multiple items, not a list of single-item dictionaries.
You can initialize the dictionary with class constructors rather than class objects and create objects later:
```
input_data = {...}
my_dict = {
"a": Class1,
"b": Class2,
"c": Class3
}
def get_item(d, key, data = input_data):
if isinstance(d[key], type):
d[key] = d[key](data)
return d[key]
```
Later:
```
get_item(my_dict, "a") # Returns a Class1 instance
```
Perhaps you can even derive a new "smart" dictionary from `dict` and redefine its `__getitem__` to instantiate objects when they are accessed for the first time. |
49,910,180 | I just learned about pointers in c++, and my instructor told to create a doubly linked list with a for loop. However, the only example I was given was
```
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
DL_List mylist;
if (mylist.empty())
mylist.insert(n1, mylist.head);
mylist.insert(n2, n1);
mylist.insert(n3, n2);
mylist.insert(n4, n3);
mylist.insert(n5, n4);
mylist.display();
```
I have no idea how to set a for loop for this because I don't know how to name them in the loop, or how I would connect them. | 2018/04/18 | [
"https://Stackoverflow.com/questions/49910180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9666782/"
] | I would just put the class and its input in a tuple:
```
input_data = {...}
my_list = [
{"a": (Class1, input_data)},
{"b": (Class2, input_data)},
{"c": (Class3, input_data)}
]
```
Then when I want to instantiate:
```
tup = my_list[0]["a"]
instantiated_class = tup[0](tup[1])
``` | It sounds like you need a generator. A generator creates each element as needed when you're iterating over it (the downside is, you can't iterate over the generator again; once you've "used" an element, it's gone). `range` in Python is a (somewhat special) example of a generator. I'm not sure how you're going to pull out the single/few items you need from your list, though - will you just need the first few, or do you access them by index? Here's a generator example you could use if you're just going to use the first items from your list:
```
class C1:
def __init__(*args):
print("C1 init")
class C2:
def __init__(*args):
print("C2 init")
class C3:
def __init__(*args):
print("C3 init")
classes = [C1, C2, C3]
keys = 'abc'
data = [3, 5]
gen = ({keys[i]: classes[i](*data)} for i in range(len(keys)))
# each time you want an element out:
new_dict = next(gen)
```
If you want to be able to get the items out by index instead, other answers will probably work better. |
49,910,180 | I just learned about pointers in c++, and my instructor told to create a doubly linked list with a for loop. However, the only example I was given was
```
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
DL_List mylist;
if (mylist.empty())
mylist.insert(n1, mylist.head);
mylist.insert(n2, n1);
mylist.insert(n3, n2);
mylist.insert(n4, n3);
mylist.insert(n5, n4);
mylist.display();
```
I have no idea how to set a for loop for this because I don't know how to name them in the loop, or how I would connect them. | 2018/04/18 | [
"https://Stackoverflow.com/questions/49910180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9666782/"
] | I would just put the class and its input in a tuple:
```
input_data = {...}
my_list = [
{"a": (Class1, input_data)},
{"b": (Class2, input_data)},
{"c": (Class3, input_data)}
]
```
Then when I want to instantiate:
```
tup = my_list[0]["a"]
instantiated_class = tup[0](tup[1])
``` | You can turn them into functions that return the desired object and which you only evaluate as needed.
```
my_list = [
{"a": lambda: Class1(input_data)},
{"b": lambda: Class2(input_data)},
{"c": lambda: Class3(input_data)}
]
c1 = my_list[0]["a"]()
``` |
49,910,180 | I just learned about pointers in c++, and my instructor told to create a doubly linked list with a for loop. However, the only example I was given was
```
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
DL_List mylist;
if (mylist.empty())
mylist.insert(n1, mylist.head);
mylist.insert(n2, n1);
mylist.insert(n3, n2);
mylist.insert(n4, n3);
mylist.insert(n5, n4);
mylist.display();
```
I have no idea how to set a for loop for this because I don't know how to name them in the loop, or how I would connect them. | 2018/04/18 | [
"https://Stackoverflow.com/questions/49910180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9666782/"
] | I would just put the class and its input in a tuple:
```
input_data = {...}
my_list = [
{"a": (Class1, input_data)},
{"b": (Class2, input_data)},
{"c": (Class3, input_data)}
]
```
Then when I want to instantiate:
```
tup = my_list[0]["a"]
instantiated_class = tup[0](tup[1])
``` | You could subclass `dict` along the lines (bare minimum, you may have to override more methods for a smooth experience):
```
>>> class delayed_dict(dict):
... def __init__(self, backstore):
... super().__init__()
... self._backstore=backstore
... def __getitem__(self, key):
... if not key in self:
... fun, *args = self._backstore[key]
... self[key] = fun(*args)
... return super().__getitem__(key)
```
Applied to your example:
```
>>> input_data = (1, 2, 3)
>>> Class1 = list
>>> Class2 = tuple
>>> Class3 = dict.fromkeys
>>>
>>> my_list = [
... {"a": (Class1, input_data)},
... {"b": (Class2, input_data)},
... {"c": (Class3, input_data)}
... ]
>>>
>>> lazy = list(map(delayed_dict, my_list))
>>>
>>> lazy
[{}, {}, {}]
>>>
>>> x = lazy[1]['b']
>>> x is lazy[1]['b']
True
>>> x
(1, 2, 3)
>>> lazy
[{}, {'b': (1, 2, 3)}, {}]
``` |
49,910,180 | I just learned about pointers in c++, and my instructor told to create a doubly linked list with a for loop. However, the only example I was given was
```
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
DL_List mylist;
if (mylist.empty())
mylist.insert(n1, mylist.head);
mylist.insert(n2, n1);
mylist.insert(n3, n2);
mylist.insert(n4, n3);
mylist.insert(n5, n4);
mylist.display();
```
I have no idea how to set a for loop for this because I don't know how to name them in the loop, or how I would connect them. | 2018/04/18 | [
"https://Stackoverflow.com/questions/49910180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9666782/"
] | I feel that you are looking for a dictionary with multiple items, not a list of single-item dictionaries.
You can initialize the dictionary with class constructors rather than class objects and create objects later:
```
input_data = {...}
my_dict = {
"a": Class1,
"b": Class2,
"c": Class3
}
def get_item(d, key, data = input_data):
if isinstance(d[key], type):
d[key] = d[key](data)
return d[key]
```
Later:
```
get_item(my_dict, "a") # Returns a Class1 instance
```
Perhaps you can even derive a new "smart" dictionary from `dict` and redefine its `__getitem__` to instantiate objects when they are accessed for the first time. | It sounds like you need a generator. A generator creates each element as needed when you're iterating over it (the downside is, you can't iterate over the generator again; once you've "used" an element, it's gone). `range` in Python is a (somewhat special) example of a generator. I'm not sure how you're going to pull out the single/few items you need from your list, though - will you just need the first few, or do you access them by index? Here's a generator example you could use if you're just going to use the first items from your list:
```
class C1:
def __init__(*args):
print("C1 init")
class C2:
def __init__(*args):
print("C2 init")
class C3:
def __init__(*args):
print("C3 init")
classes = [C1, C2, C3]
keys = 'abc'
data = [3, 5]
gen = ({keys[i]: classes[i](*data)} for i in range(len(keys)))
# each time you want an element out:
new_dict = next(gen)
```
If you want to be able to get the items out by index instead, other answers will probably work better. |
49,910,180 | I just learned about pointers in c++, and my instructor told to create a doubly linked list with a for loop. However, the only example I was given was
```
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
DL_List mylist;
if (mylist.empty())
mylist.insert(n1, mylist.head);
mylist.insert(n2, n1);
mylist.insert(n3, n2);
mylist.insert(n4, n3);
mylist.insert(n5, n4);
mylist.display();
```
I have no idea how to set a for loop for this because I don't know how to name them in the loop, or how I would connect them. | 2018/04/18 | [
"https://Stackoverflow.com/questions/49910180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9666782/"
] | I feel that you are looking for a dictionary with multiple items, not a list of single-item dictionaries.
You can initialize the dictionary with class constructors rather than class objects and create objects later:
```
input_data = {...}
my_dict = {
"a": Class1,
"b": Class2,
"c": Class3
}
def get_item(d, key, data = input_data):
if isinstance(d[key], type):
d[key] = d[key](data)
return d[key]
```
Later:
```
get_item(my_dict, "a") # Returns a Class1 instance
```
Perhaps you can even derive a new "smart" dictionary from `dict` and redefine its `__getitem__` to instantiate objects when they are accessed for the first time. | You can turn them into functions that return the desired object and which you only evaluate as needed.
```
my_list = [
{"a": lambda: Class1(input_data)},
{"b": lambda: Class2(input_data)},
{"c": lambda: Class3(input_data)}
]
c1 = my_list[0]["a"]()
``` |
49,910,180 | I just learned about pointers in c++, and my instructor told to create a doubly linked list with a for loop. However, the only example I was given was
```
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
DL_List mylist;
if (mylist.empty())
mylist.insert(n1, mylist.head);
mylist.insert(n2, n1);
mylist.insert(n3, n2);
mylist.insert(n4, n3);
mylist.insert(n5, n4);
mylist.display();
```
I have no idea how to set a for loop for this because I don't know how to name them in the loop, or how I would connect them. | 2018/04/18 | [
"https://Stackoverflow.com/questions/49910180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9666782/"
] | I feel that you are looking for a dictionary with multiple items, not a list of single-item dictionaries.
You can initialize the dictionary with class constructors rather than class objects and create objects later:
```
input_data = {...}
my_dict = {
"a": Class1,
"b": Class2,
"c": Class3
}
def get_item(d, key, data = input_data):
if isinstance(d[key], type):
d[key] = d[key](data)
return d[key]
```
Later:
```
get_item(my_dict, "a") # Returns a Class1 instance
```
Perhaps you can even derive a new "smart" dictionary from `dict` and redefine its `__getitem__` to instantiate objects when they are accessed for the first time. | You could subclass `dict` along the lines (bare minimum, you may have to override more methods for a smooth experience):
```
>>> class delayed_dict(dict):
... def __init__(self, backstore):
... super().__init__()
... self._backstore=backstore
... def __getitem__(self, key):
... if not key in self:
... fun, *args = self._backstore[key]
... self[key] = fun(*args)
... return super().__getitem__(key)
```
Applied to your example:
```
>>> input_data = (1, 2, 3)
>>> Class1 = list
>>> Class2 = tuple
>>> Class3 = dict.fromkeys
>>>
>>> my_list = [
... {"a": (Class1, input_data)},
... {"b": (Class2, input_data)},
... {"c": (Class3, input_data)}
... ]
>>>
>>> lazy = list(map(delayed_dict, my_list))
>>>
>>> lazy
[{}, {}, {}]
>>>
>>> x = lazy[1]['b']
>>> x is lazy[1]['b']
True
>>> x
(1, 2, 3)
>>> lazy
[{}, {'b': (1, 2, 3)}, {}]
``` |
49,910,180 | I just learned about pointers in c++, and my instructor told to create a doubly linked list with a for loop. However, the only example I was given was
```
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
DL_List mylist;
if (mylist.empty())
mylist.insert(n1, mylist.head);
mylist.insert(n2, n1);
mylist.insert(n3, n2);
mylist.insert(n4, n3);
mylist.insert(n5, n4);
mylist.display();
```
I have no idea how to set a for loop for this because I don't know how to name them in the loop, or how I would connect them. | 2018/04/18 | [
"https://Stackoverflow.com/questions/49910180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9666782/"
] | You can turn them into functions that return the desired object and which you only evaluate as needed.
```
my_list = [
{"a": lambda: Class1(input_data)},
{"b": lambda: Class2(input_data)},
{"c": lambda: Class3(input_data)}
]
c1 = my_list[0]["a"]()
``` | It sounds like you need a generator. A generator creates each element as needed when you're iterating over it (the downside is, you can't iterate over the generator again; once you've "used" an element, it's gone). `range` in Python is a (somewhat special) example of a generator. I'm not sure how you're going to pull out the single/few items you need from your list, though - will you just need the first few, or do you access them by index? Here's a generator example you could use if you're just going to use the first items from your list:
```
class C1:
def __init__(*args):
print("C1 init")
class C2:
def __init__(*args):
print("C2 init")
class C3:
def __init__(*args):
print("C3 init")
classes = [C1, C2, C3]
keys = 'abc'
data = [3, 5]
gen = ({keys[i]: classes[i](*data)} for i in range(len(keys)))
# each time you want an element out:
new_dict = next(gen)
```
If you want to be able to get the items out by index instead, other answers will probably work better. |
49,910,180 | I just learned about pointers in c++, and my instructor told to create a doubly linked list with a for loop. However, the only example I was given was
```
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
DL_List mylist;
if (mylist.empty())
mylist.insert(n1, mylist.head);
mylist.insert(n2, n1);
mylist.insert(n3, n2);
mylist.insert(n4, n3);
mylist.insert(n5, n4);
mylist.display();
```
I have no idea how to set a for loop for this because I don't know how to name them in the loop, or how I would connect them. | 2018/04/18 | [
"https://Stackoverflow.com/questions/49910180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9666782/"
] | You could subclass `dict` along the lines (bare minimum, you may have to override more methods for a smooth experience):
```
>>> class delayed_dict(dict):
... def __init__(self, backstore):
... super().__init__()
... self._backstore=backstore
... def __getitem__(self, key):
... if not key in self:
... fun, *args = self._backstore[key]
... self[key] = fun(*args)
... return super().__getitem__(key)
```
Applied to your example:
```
>>> input_data = (1, 2, 3)
>>> Class1 = list
>>> Class2 = tuple
>>> Class3 = dict.fromkeys
>>>
>>> my_list = [
... {"a": (Class1, input_data)},
... {"b": (Class2, input_data)},
... {"c": (Class3, input_data)}
... ]
>>>
>>> lazy = list(map(delayed_dict, my_list))
>>>
>>> lazy
[{}, {}, {}]
>>>
>>> x = lazy[1]['b']
>>> x is lazy[1]['b']
True
>>> x
(1, 2, 3)
>>> lazy
[{}, {'b': (1, 2, 3)}, {}]
``` | It sounds like you need a generator. A generator creates each element as needed when you're iterating over it (the downside is, you can't iterate over the generator again; once you've "used" an element, it's gone). `range` in Python is a (somewhat special) example of a generator. I'm not sure how you're going to pull out the single/few items you need from your list, though - will you just need the first few, or do you access them by index? Here's a generator example you could use if you're just going to use the first items from your list:
```
class C1:
def __init__(*args):
print("C1 init")
class C2:
def __init__(*args):
print("C2 init")
class C3:
def __init__(*args):
print("C3 init")
classes = [C1, C2, C3]
keys = 'abc'
data = [3, 5]
gen = ({keys[i]: classes[i](*data)} for i in range(len(keys)))
# each time you want an element out:
new_dict = next(gen)
```
If you want to be able to get the items out by index instead, other answers will probably work better. |
63,419,283 | I UnmarshalXML xml, but I can't get the same result when MarshalXML (see the example below). As you can see the **xs:simpleType** is transformed into a **simpleType** and other differences. How can I make a complete identity? I need to convert arbitrary xml according to certain rules, so I can't use specific tags.
You can view the working code here: <https://play.golang.org/p/QK2AfPsR9ZN>
```
package main
import (
"bytes"
"encoding/xml"
"fmt"
)
var data = []byte(`
<xs:simpleType name="x"></xs:simpleType>
`)
type Node struct {
XMLName xml.Name
Attrs []xml.Attr `xml:",any,attr"`
Content []byte `xml:",innerxml"`
Nodes []Node `xml:",any"`
}
func (n *Node) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
n.Attrs = start.Attr
type node Node
return d.DecodeElement((*node)(n), &start)
}
func (n *Node) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
n.Attrs = start.Attr
type node Node
return e.EncodeElement((*node)(n), start)
}
func main() {
buf := bytes.NewBuffer(data)
dec := xml.NewDecoder(buf)
var n Node
dec.Decode(&n)
output, _ := xml.Marshal(n)
fmt.Println(string(output))
}
```
Output:
```
<simpleType xmlns="xs" name="x" name="x"></simpleType>
``` | 2020/08/14 | [
"https://Stackoverflow.com/questions/63419283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3398921/"
] | You don't need custom marshaling or unmarshaling logic, and you can force this behavior if before marshaling you concatenate the namespace and tag name:
```
n.XMLName.Local = n.XMLName.Space + ":" + n.XMLName.Local
n.XMLName.Space = ""
```
Example input matches output (try it on the [Go Playground](https://play.golang.org/p/4vIcTW0w0Yl)):
```
<xs:simpleType name="x" other="y">Some content</xs:simpleType>
```
Of course if there are child tags, you have to process names of all nodes recursively. Let's write a helper for that:
```
func setName(n *Node) {
n.XMLName.Local = n.XMLName.Space + ":" + n.XMLName.Local
n.XMLName.Space = ""
for i := range n.Nodes {
setName(&n.Nodes[i])
}
}
```
Example XML input:
```
<xs:simpleType name="comma-separated-integer">
<xs:annotation>
<xs:documentation>The comma-separated-integer element.</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:token">
<xs:pattern value="[1-9][0-9]*(, ?[1-9][0-9]*)*"/>
</xs:restriction>
</xs:simpleType>
```
Using the helper:
```
buf := bytes.NewBuffer(data)
dec := xml.NewDecoder(buf)
var n Node
if err := dec.Decode(&n); err != nil {
panic(err)
}
setName(&n)
output, err := xml.Marshal(n)
fmt.Println(string(output))
if err != nil {
panic(err)
}
```
Then output almost matches the input. Try it on the [Go Playground](https://play.golang.org/p/Dnv8u5gnEio).
The problem is: the inner content is duplicated. This is because `Node.Content` is the inner XML content, and child tags are also added as child nodes to `Node.Nodes`. So to get the same output, child nodes doesn't need to be marshalled, `Content` already contains the children.
Remove the duplication by clearning `Nodes`:
```
n.XMLName.Local = n.XMLName.Space + ":" + n.XMLName.Local
n.XMLName.Space = ""
n.Nodes = nil
```
Try this one on the [Go Playground](https://play.golang.org/p/6BycNE6YFdD).
Note: if you intend to manipulate the XML child nodes, this isn't a viable option. Then you may keep the `setName()` helper function, and to remove the duplication, you may zero the `Content` of the nodes that have child nodes:
```
func setName(n *Node) {
n.XMLName.Local = n.XMLName.Space + ":" + n.XMLName.Local
n.XMLName.Space = ""
if len(n.Nodes) != 0 {
n.Content = nil
}
for i := range n.Nodes {
setName(&n.Nodes[i])
}
}
```
Try this one on the [Go Playground](https://play.golang.org/p/c4XCVlSeJja). | In our team we have been using for a few months a fantastic module that expresses XML inspired by Python etrees.
<https://github.com/beevik/etree>
It's simple but very powerful to interpret and manipulate XMLs. |
115,798 | this is my `hook_form_alter` function for set the placeholder attribute and other stuff:
```
function mysubtheme_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'contact_site_form':
$form['tel'] = array(
'#title' => t('Tél'),
'#type' => 'textfield',
'#required' => TRUE,
);
if ($form_id == 'contact_site_form') {
$form['name']['#title'] = t('name/family name');
$form['name']['#attributes']['placeholder'] = t('Enter your name');
}
$order = array(
'1' => 'name',
'2' => 'mail',
'3' => 'tel',
'4' => 'subject',
'5' => 'message',
'6' => 'copy',
);
foreach ($order as $key => $field) {
$form[$field]['#weight'] = $key;
}
break;
}
}
```
why don't set the placeholder attribute for contact field?
`kpr()` for this element shows:
 | 2014/05/30 | [
"https://drupal.stackexchange.com/questions/115798",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/29100/"
] | You probably need to do something like this:
```
$protocol = (!empty($_SERVER['HTTPS'])) ? 'https' : 'http';
$base_url = $protocol . '://mysite.com';
```
...so that Drupal knows which protocol to use depending on how the site was accessed. | I have had luck with:
```
$base_url = '//mysite.com';
```
Also, to maintain the session cookie, I usually add:
```
$conf['https'] = TRUE;
```
which allows for mixed mode. |
115,798 | this is my `hook_form_alter` function for set the placeholder attribute and other stuff:
```
function mysubtheme_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'contact_site_form':
$form['tel'] = array(
'#title' => t('Tél'),
'#type' => 'textfield',
'#required' => TRUE,
);
if ($form_id == 'contact_site_form') {
$form['name']['#title'] = t('name/family name');
$form['name']['#attributes']['placeholder'] = t('Enter your name');
}
$order = array(
'1' => 'name',
'2' => 'mail',
'3' => 'tel',
'4' => 'subject',
'5' => 'message',
'6' => 'copy',
);
foreach ($order as $key => $field) {
$form[$field]['#weight'] = $key;
}
break;
}
}
```
why don't set the placeholder attribute for contact field?
`kpr()` for this element shows:
 | 2014/05/30 | [
"https://drupal.stackexchange.com/questions/115798",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/29100/"
] | You probably need to do something like this:
```
$protocol = (!empty($_SERVER['HTTPS'])) ? 'https' : 'http';
$base_url = $protocol . '://mysite.com';
```
...so that Drupal knows which protocol to use depending on how the site was accessed. | Unfortunately the problem with setting the protocol relative to the accessed URL is that the site only references that when building the cached files and therefore creates all references to files and resources based on what protocol is used when rebuilding the site cache.
So, if you rebuild the cache from https, then all links are https. If you rebuild the site from http, then all links are http.
Rebuilding from https works best, but browsers may still block the secure content and may require users to manually allow the blocked content. |
115,798 | this is my `hook_form_alter` function for set the placeholder attribute and other stuff:
```
function mysubtheme_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'contact_site_form':
$form['tel'] = array(
'#title' => t('Tél'),
'#type' => 'textfield',
'#required' => TRUE,
);
if ($form_id == 'contact_site_form') {
$form['name']['#title'] = t('name/family name');
$form['name']['#attributes']['placeholder'] = t('Enter your name');
}
$order = array(
'1' => 'name',
'2' => 'mail',
'3' => 'tel',
'4' => 'subject',
'5' => 'message',
'6' => 'copy',
);
foreach ($order as $key => $field) {
$form[$field]['#weight'] = $key;
}
break;
}
}
```
why don't set the placeholder attribute for contact field?
`kpr()` for this element shows:
 | 2014/05/30 | [
"https://drupal.stackexchange.com/questions/115798",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/29100/"
] | You probably need to do something like this:
```
$protocol = (!empty($_SERVER['HTTPS'])) ? 'https' : 'http';
$base_url = $protocol . '://mysite.com';
```
...so that Drupal knows which protocol to use depending on how the site was accessed. | This works well for me with several domains on the same Drupal install over CloudFlare:
```
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$base_url = $_SERVER["HTTP_X_FORWARDED_PROTO"] . '://' . $_SERVER['HTTP_HOST'];
} else {
$base_url = 'http://' . $_SERVER['HTTP_HOST'];
}
```
Like this it also works well with CloudFlare flexible SSL. I can access the site both with and without SSL.
(It seems you don't need the Cloudflare module but it wouldn't hurt either to enable it.) |
115,798 | this is my `hook_form_alter` function for set the placeholder attribute and other stuff:
```
function mysubtheme_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'contact_site_form':
$form['tel'] = array(
'#title' => t('Tél'),
'#type' => 'textfield',
'#required' => TRUE,
);
if ($form_id == 'contact_site_form') {
$form['name']['#title'] = t('name/family name');
$form['name']['#attributes']['placeholder'] = t('Enter your name');
}
$order = array(
'1' => 'name',
'2' => 'mail',
'3' => 'tel',
'4' => 'subject',
'5' => 'message',
'6' => 'copy',
);
foreach ($order as $key => $field) {
$form[$field]['#weight'] = $key;
}
break;
}
}
```
why don't set the placeholder attribute for contact field?
`kpr()` for this element shows:
 | 2014/05/30 | [
"https://drupal.stackexchange.com/questions/115798",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/29100/"
] | I have had luck with:
```
$base_url = '//mysite.com';
```
Also, to maintain the session cookie, I usually add:
```
$conf['https'] = TRUE;
```
which allows for mixed mode. | Unfortunately the problem with setting the protocol relative to the accessed URL is that the site only references that when building the cached files and therefore creates all references to files and resources based on what protocol is used when rebuilding the site cache.
So, if you rebuild the cache from https, then all links are https. If you rebuild the site from http, then all links are http.
Rebuilding from https works best, but browsers may still block the secure content and may require users to manually allow the blocked content. |
115,798 | this is my `hook_form_alter` function for set the placeholder attribute and other stuff:
```
function mysubtheme_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'contact_site_form':
$form['tel'] = array(
'#title' => t('Tél'),
'#type' => 'textfield',
'#required' => TRUE,
);
if ($form_id == 'contact_site_form') {
$form['name']['#title'] = t('name/family name');
$form['name']['#attributes']['placeholder'] = t('Enter your name');
}
$order = array(
'1' => 'name',
'2' => 'mail',
'3' => 'tel',
'4' => 'subject',
'5' => 'message',
'6' => 'copy',
);
foreach ($order as $key => $field) {
$form[$field]['#weight'] = $key;
}
break;
}
}
```
why don't set the placeholder attribute for contact field?
`kpr()` for this element shows:
 | 2014/05/30 | [
"https://drupal.stackexchange.com/questions/115798",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/29100/"
] | This works well for me with several domains on the same Drupal install over CloudFlare:
```
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$base_url = $_SERVER["HTTP_X_FORWARDED_PROTO"] . '://' . $_SERVER['HTTP_HOST'];
} else {
$base_url = 'http://' . $_SERVER['HTTP_HOST'];
}
```
Like this it also works well with CloudFlare flexible SSL. I can access the site both with and without SSL.
(It seems you don't need the Cloudflare module but it wouldn't hurt either to enable it.) | Unfortunately the problem with setting the protocol relative to the accessed URL is that the site only references that when building the cached files and therefore creates all references to files and resources based on what protocol is used when rebuilding the site cache.
So, if you rebuild the cache from https, then all links are https. If you rebuild the site from http, then all links are http.
Rebuilding from https works best, but browsers may still block the secure content and may require users to manually allow the blocked content. |
29,484,916 | If I want to print out array of string like:
```
char juices_A[][12] = { "dragonfruit", "waterberry", "sharonfruit", };
```
I can simply use `juices_A[0]`,`juices_A[1]`,`juices_A[3]`, respectively as a pointer to string `"dragonfruit"`, `"waterberry"`, `"sharonfruit"`, and print them out.
But what if I want to print out array of int array like:
```
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
```
I can not simply use `data[0]`,`data[1]`,`data[2]` as pointer to `{ 1, 2, 3 }`, `{ 4, 5, 6 }`, `{ 7, 8, 9 }`, I need to adopt a more complicated way to print them out. I need to use loop inside loop. So I want to know why I can not use pointer in the int situation? I read on book "**Array variables are like pointers..**" so I assume int array variable `data[0],data[1],data[2]` are also like pointers...
```
#include <stdio.h>
int main() {
int i_A = 0;
char juices_A[][12] = { "dragonfruit", "waterberry", "sharonfruit", };
for (; i_A < 3; i_A++)
printf("%s;", juices_A[i_A]);
puts("");
int i_B = 0;
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (; i_B < 3; i_B++) {
int i_C = 0;
for (; i_C < 3; i_C++)
printf("%i,", data[i_B][i_C]);
printf(";");
}
return 0;
}
```
the result is:
```
dragonfruit;waterberry;sharonfruit;
1,2,3,;4,5,6,;7,8,9,;
``` | 2015/04/07 | [
"https://Stackoverflow.com/questions/29484916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4740734/"
] | You can use access arrays like pointers and vice versa.
Here's the output from the program below:
```
dragonfruit;waterberry;sharonfruit;
{ { 1, 2, 3, }, { 4, 5, 6, }, { 7, 8, 9, }, }
```
Here's a modification to your code:
```
#include <stdio.h>
#define ROW_WIDTH 3
#define TABLE_HEIGHT 3
int main(void) {
char *juices[] = { "dragonfruit", "waterberry", "sharonfruit", };
int data[TABLE_HEIGHT][ROW_WIDTH] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (int n = 0; n < ROW_WIDTH; n++)
printf("%s;", juices[n]);
int *ip = (int *)data;
printf("\n{ ");
for (int i = 0; i < TABLE_HEIGHT; i++) {
printf("{ ");
for(int j = 0; j < ROW_WIDTH; j++) {
printf("%d, ", *ip + ((i * ROW_WIDTH) + j));
}
printf("}, ");
}
printf("}\n");
return 0;
}
``` | **Strings:**
```
-------------------------
|h | e | l | l | o | \0 |
-------------------------
|w | o | r | l | d | \0 |
------------------------
```
As you see this array can be stored in a 2D char array
```
char a[2][6];
```
Now `a[i]` gives the starting address of each row and `%s` prints out a string until a `\0` is enountered so you can just pass the address of each row and get the contents of the row. Just like
```
char *p = "hello";
printf("%s\n",p);
```
**Note:**
Again if you want to read the character at a particular location you need to specify `a[row][col]`
Whereas
**Integers:**
```
----------------
|1 | 2 | 3 | 4 |
----------------
|5 | 6 | 7 | 8 |
----------------
```
Now you can have a array like
```
int b[2][4];
```
`b[i]` will give you the starting address of each row but in order to get the value stored in a particular location you need to specify value with `b[row][col]`.
The difference is the sentinel condition for valid C strings is `\0` and is it being used to access each row which is not the case for integers.
>
> so I assume int array variable data[0],data[1],data[2] are also like
> pointers
>
>
>
Yes they are pointers to each row but you need to dereference the pointer to get the value right? So if `data[0]` is a pointer then do `data[0][column]` |
29,484,916 | If I want to print out array of string like:
```
char juices_A[][12] = { "dragonfruit", "waterberry", "sharonfruit", };
```
I can simply use `juices_A[0]`,`juices_A[1]`,`juices_A[3]`, respectively as a pointer to string `"dragonfruit"`, `"waterberry"`, `"sharonfruit"`, and print them out.
But what if I want to print out array of int array like:
```
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
```
I can not simply use `data[0]`,`data[1]`,`data[2]` as pointer to `{ 1, 2, 3 }`, `{ 4, 5, 6 }`, `{ 7, 8, 9 }`, I need to adopt a more complicated way to print them out. I need to use loop inside loop. So I want to know why I can not use pointer in the int situation? I read on book "**Array variables are like pointers..**" so I assume int array variable `data[0],data[1],data[2]` are also like pointers...
```
#include <stdio.h>
int main() {
int i_A = 0;
char juices_A[][12] = { "dragonfruit", "waterberry", "sharonfruit", };
for (; i_A < 3; i_A++)
printf("%s;", juices_A[i_A]);
puts("");
int i_B = 0;
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (; i_B < 3; i_B++) {
int i_C = 0;
for (; i_C < 3; i_C++)
printf("%i,", data[i_B][i_C]);
printf(";");
}
return 0;
}
```
the result is:
```
dragonfruit;waterberry;sharonfruit;
1,2,3,;4,5,6,;7,8,9,;
``` | 2015/04/07 | [
"https://Stackoverflow.com/questions/29484916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4740734/"
] | **Strings:**
```
-------------------------
|h | e | l | l | o | \0 |
-------------------------
|w | o | r | l | d | \0 |
------------------------
```
As you see this array can be stored in a 2D char array
```
char a[2][6];
```
Now `a[i]` gives the starting address of each row and `%s` prints out a string until a `\0` is enountered so you can just pass the address of each row and get the contents of the row. Just like
```
char *p = "hello";
printf("%s\n",p);
```
**Note:**
Again if you want to read the character at a particular location you need to specify `a[row][col]`
Whereas
**Integers:**
```
----------------
|1 | 2 | 3 | 4 |
----------------
|5 | 6 | 7 | 8 |
----------------
```
Now you can have a array like
```
int b[2][4];
```
`b[i]` will give you the starting address of each row but in order to get the value stored in a particular location you need to specify value with `b[row][col]`.
The difference is the sentinel condition for valid C strings is `\0` and is it being used to access each row which is not the case for integers.
>
> so I assume int array variable data[0],data[1],data[2] are also like
> pointers
>
>
>
Yes they are pointers to each row but you need to dereference the pointer to get the value right? So if `data[0]` is a pointer then do `data[0][column]` | ```
#include <stdio.h>
int main()
{
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int *ptr;
int lines = 3;
int columns = 3;
int i;
ptr = &data[0][0];
while (lines-- > 0) {
i = columns;
while (i-- > 0) {
printf("%d ", *ptr);
ptr += 1;
}
putchar('\n');
}
return 0;
}
```
or:
```
#include <stdio.h>
int main()
{
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int *ptr;
int lines = 3;
int columns = 3;
int max = lines * columns;
ptr = &data[0][0];
while (max-- > 0) {
printf("%d ", *ptr);
ptr++;
if (max % columns == 0)
putchar('\n');
}
return 0;
}
``` |
29,484,916 | If I want to print out array of string like:
```
char juices_A[][12] = { "dragonfruit", "waterberry", "sharonfruit", };
```
I can simply use `juices_A[0]`,`juices_A[1]`,`juices_A[3]`, respectively as a pointer to string `"dragonfruit"`, `"waterberry"`, `"sharonfruit"`, and print them out.
But what if I want to print out array of int array like:
```
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
```
I can not simply use `data[0]`,`data[1]`,`data[2]` as pointer to `{ 1, 2, 3 }`, `{ 4, 5, 6 }`, `{ 7, 8, 9 }`, I need to adopt a more complicated way to print them out. I need to use loop inside loop. So I want to know why I can not use pointer in the int situation? I read on book "**Array variables are like pointers..**" so I assume int array variable `data[0],data[1],data[2]` are also like pointers...
```
#include <stdio.h>
int main() {
int i_A = 0;
char juices_A[][12] = { "dragonfruit", "waterberry", "sharonfruit", };
for (; i_A < 3; i_A++)
printf("%s;", juices_A[i_A]);
puts("");
int i_B = 0;
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (; i_B < 3; i_B++) {
int i_C = 0;
for (; i_C < 3; i_C++)
printf("%i,", data[i_B][i_C]);
printf(";");
}
return 0;
}
```
the result is:
```
dragonfruit;waterberry;sharonfruit;
1,2,3,;4,5,6,;7,8,9,;
``` | 2015/04/07 | [
"https://Stackoverflow.com/questions/29484916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4740734/"
] | You can use access arrays like pointers and vice versa.
Here's the output from the program below:
```
dragonfruit;waterberry;sharonfruit;
{ { 1, 2, 3, }, { 4, 5, 6, }, { 7, 8, 9, }, }
```
Here's a modification to your code:
```
#include <stdio.h>
#define ROW_WIDTH 3
#define TABLE_HEIGHT 3
int main(void) {
char *juices[] = { "dragonfruit", "waterberry", "sharonfruit", };
int data[TABLE_HEIGHT][ROW_WIDTH] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (int n = 0; n < ROW_WIDTH; n++)
printf("%s;", juices[n]);
int *ip = (int *)data;
printf("\n{ ");
for (int i = 0; i < TABLE_HEIGHT; i++) {
printf("{ ");
for(int j = 0; j < ROW_WIDTH; j++) {
printf("%d, ", *ip + ((i * ROW_WIDTH) + j));
}
printf("}, ");
}
printf("}\n");
return 0;
}
``` | The `char juices_A[][12] = { "dragonfruit", "waterberry", "sharonfruit" };` whenever the data is accessed it prints till `\0` is reached, as strings are considered only till `\0`. So when we use `juices_A[0]` it points to start of first data till `\0` is reached.But to get an individual char we need to mention both the dimensions of the array.
`char juices_A[1][2]` to access `'t'` in `waterberry`
But this is not the case with `int` as each is considered as separate entity. So we use both dimensions of the array to access it.
Even if we reduce the size of the array like `char juices_A[][12] = { "dragon", "waterberry", "sharonfruit" };` when printed it outputs
`dragon;waterberry;sharonfruit`
But in the case of `int data[3][3] = { { 1, 2}, { 4, 5, 6 }, { 7, 8, 9 } };` it outputs
1,2,**0**,....`
this makes the difference |
29,484,916 | If I want to print out array of string like:
```
char juices_A[][12] = { "dragonfruit", "waterberry", "sharonfruit", };
```
I can simply use `juices_A[0]`,`juices_A[1]`,`juices_A[3]`, respectively as a pointer to string `"dragonfruit"`, `"waterberry"`, `"sharonfruit"`, and print them out.
But what if I want to print out array of int array like:
```
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
```
I can not simply use `data[0]`,`data[1]`,`data[2]` as pointer to `{ 1, 2, 3 }`, `{ 4, 5, 6 }`, `{ 7, 8, 9 }`, I need to adopt a more complicated way to print them out. I need to use loop inside loop. So I want to know why I can not use pointer in the int situation? I read on book "**Array variables are like pointers..**" so I assume int array variable `data[0],data[1],data[2]` are also like pointers...
```
#include <stdio.h>
int main() {
int i_A = 0;
char juices_A[][12] = { "dragonfruit", "waterberry", "sharonfruit", };
for (; i_A < 3; i_A++)
printf("%s;", juices_A[i_A]);
puts("");
int i_B = 0;
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (; i_B < 3; i_B++) {
int i_C = 0;
for (; i_C < 3; i_C++)
printf("%i,", data[i_B][i_C]);
printf(";");
}
return 0;
}
```
the result is:
```
dragonfruit;waterberry;sharonfruit;
1,2,3,;4,5,6,;7,8,9,;
``` | 2015/04/07 | [
"https://Stackoverflow.com/questions/29484916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4740734/"
] | The `char juices_A[][12] = { "dragonfruit", "waterberry", "sharonfruit" };` whenever the data is accessed it prints till `\0` is reached, as strings are considered only till `\0`. So when we use `juices_A[0]` it points to start of first data till `\0` is reached.But to get an individual char we need to mention both the dimensions of the array.
`char juices_A[1][2]` to access `'t'` in `waterberry`
But this is not the case with `int` as each is considered as separate entity. So we use both dimensions of the array to access it.
Even if we reduce the size of the array like `char juices_A[][12] = { "dragon", "waterberry", "sharonfruit" };` when printed it outputs
`dragon;waterberry;sharonfruit`
But in the case of `int data[3][3] = { { 1, 2}, { 4, 5, 6 }, { 7, 8, 9 } };` it outputs
1,2,**0**,....`
this makes the difference | ```
#include <stdio.h>
int main()
{
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int *ptr;
int lines = 3;
int columns = 3;
int i;
ptr = &data[0][0];
while (lines-- > 0) {
i = columns;
while (i-- > 0) {
printf("%d ", *ptr);
ptr += 1;
}
putchar('\n');
}
return 0;
}
```
or:
```
#include <stdio.h>
int main()
{
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int *ptr;
int lines = 3;
int columns = 3;
int max = lines * columns;
ptr = &data[0][0];
while (max-- > 0) {
printf("%d ", *ptr);
ptr++;
if (max % columns == 0)
putchar('\n');
}
return 0;
}
``` |
29,484,916 | If I want to print out array of string like:
```
char juices_A[][12] = { "dragonfruit", "waterberry", "sharonfruit", };
```
I can simply use `juices_A[0]`,`juices_A[1]`,`juices_A[3]`, respectively as a pointer to string `"dragonfruit"`, `"waterberry"`, `"sharonfruit"`, and print them out.
But what if I want to print out array of int array like:
```
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
```
I can not simply use `data[0]`,`data[1]`,`data[2]` as pointer to `{ 1, 2, 3 }`, `{ 4, 5, 6 }`, `{ 7, 8, 9 }`, I need to adopt a more complicated way to print them out. I need to use loop inside loop. So I want to know why I can not use pointer in the int situation? I read on book "**Array variables are like pointers..**" so I assume int array variable `data[0],data[1],data[2]` are also like pointers...
```
#include <stdio.h>
int main() {
int i_A = 0;
char juices_A[][12] = { "dragonfruit", "waterberry", "sharonfruit", };
for (; i_A < 3; i_A++)
printf("%s;", juices_A[i_A]);
puts("");
int i_B = 0;
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (; i_B < 3; i_B++) {
int i_C = 0;
for (; i_C < 3; i_C++)
printf("%i,", data[i_B][i_C]);
printf(";");
}
return 0;
}
```
the result is:
```
dragonfruit;waterberry;sharonfruit;
1,2,3,;4,5,6,;7,8,9,;
``` | 2015/04/07 | [
"https://Stackoverflow.com/questions/29484916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4740734/"
] | You can use access arrays like pointers and vice versa.
Here's the output from the program below:
```
dragonfruit;waterberry;sharonfruit;
{ { 1, 2, 3, }, { 4, 5, 6, }, { 7, 8, 9, }, }
```
Here's a modification to your code:
```
#include <stdio.h>
#define ROW_WIDTH 3
#define TABLE_HEIGHT 3
int main(void) {
char *juices[] = { "dragonfruit", "waterberry", "sharonfruit", };
int data[TABLE_HEIGHT][ROW_WIDTH] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (int n = 0; n < ROW_WIDTH; n++)
printf("%s;", juices[n]);
int *ip = (int *)data;
printf("\n{ ");
for (int i = 0; i < TABLE_HEIGHT; i++) {
printf("{ ");
for(int j = 0; j < ROW_WIDTH; j++) {
printf("%d, ", *ip + ((i * ROW_WIDTH) + j));
}
printf("}, ");
}
printf("}\n");
return 0;
}
``` | ```
#include <stdio.h>
int main()
{
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int *ptr;
int lines = 3;
int columns = 3;
int i;
ptr = &data[0][0];
while (lines-- > 0) {
i = columns;
while (i-- > 0) {
printf("%d ", *ptr);
ptr += 1;
}
putchar('\n');
}
return 0;
}
```
or:
```
#include <stdio.h>
int main()
{
int data[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int *ptr;
int lines = 3;
int columns = 3;
int max = lines * columns;
ptr = &data[0][0];
while (max-- > 0) {
printf("%d ", *ptr);
ptr++;
if (max % columns == 0)
putchar('\n');
}
return 0;
}
``` |
7,157,731 | I'm using the following code to show in-app sms. My app don't have a status bar. (I'm using 320x480 pixels screen in portrait view)
```
if ([MFMessageComposeViewController canSendText])
{
MFMessageComposeViewController* msgController = [[MFMessageComposeViewController alloc] init];
msgController.recipients = [NSArray arrayWithObject:self.globalSMS];
msgController.messageComposeDelegate = self;
[self presentModalViewController:msgController animated:YES];
[msgController release];
}
```
This is working good to display the message view controller. (But status bar comes back, which is not necessary for me to show)
But the problem is that when I click "Cancel" or "Send", after going back to application, I am seeing white space on the top (in position of status bar) of the screen. And status bar is hidden.
Why is it happening when my status bar is set as hidden in app delegate. How to get rid of white space after showing the in-app sms view. | 2011/08/23 | [
"https://Stackoverflow.com/questions/7157731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265341/"
] | I found the answer. We've to set in view controller's viewDidLoad method:
```
self.wantsFullScreenLayout = YES;
``` | The issue is in portrait view. From what I am seeing if the MFMessageComposeViewController loads in landscape the space isn't there. Then if the orientation changes to portrait the layout is corrected and the space isn't present in portrait.
Note When in landscape the MFMessageComposeViewController is presented by sliding from left to right. I believe that the way the view is presented holds to key to fixing the issue. |
7,157,731 | I'm using the following code to show in-app sms. My app don't have a status bar. (I'm using 320x480 pixels screen in portrait view)
```
if ([MFMessageComposeViewController canSendText])
{
MFMessageComposeViewController* msgController = [[MFMessageComposeViewController alloc] init];
msgController.recipients = [NSArray arrayWithObject:self.globalSMS];
msgController.messageComposeDelegate = self;
[self presentModalViewController:msgController animated:YES];
[msgController release];
}
```
This is working good to display the message view controller. (But status bar comes back, which is not necessary for me to show)
But the problem is that when I click "Cancel" or "Send", after going back to application, I am seeing white space on the top (in position of status bar) of the screen. And status bar is hidden.
Why is it happening when my status bar is set as hidden in app delegate. How to get rid of white space after showing the in-app sms view. | 2011/08/23 | [
"https://Stackoverflow.com/questions/7157731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265341/"
] | I found the answer. We've to set in view controller's viewDidLoad method:
```
self.wantsFullScreenLayout = YES;
``` | ```
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
if([MFMessageComposeViewController canSendText]){
controller.body = @"MessageText!!!";
controller.recipients = [NSArray arrayWithObjects:@"123"];
controller.messageComposeDelegate = self;
controller.wantsFullScreenLayout = YES;
[self presentModalViewController:controller animated:YES];
}
``` |
7,157,731 | I'm using the following code to show in-app sms. My app don't have a status bar. (I'm using 320x480 pixels screen in portrait view)
```
if ([MFMessageComposeViewController canSendText])
{
MFMessageComposeViewController* msgController = [[MFMessageComposeViewController alloc] init];
msgController.recipients = [NSArray arrayWithObject:self.globalSMS];
msgController.messageComposeDelegate = self;
[self presentModalViewController:msgController animated:YES];
[msgController release];
}
```
This is working good to display the message view controller. (But status bar comes back, which is not necessary for me to show)
But the problem is that when I click "Cancel" or "Send", after going back to application, I am seeing white space on the top (in position of status bar) of the screen. And status bar is hidden.
Why is it happening when my status bar is set as hidden in app delegate. How to get rid of white space after showing the in-app sms view. | 2011/08/23 | [
"https://Stackoverflow.com/questions/7157731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265341/"
] | Hide the status bar after you modal presented the message controller. Something like this:
```
controller.wantsFullScreenLayout = NO;
[self presentModalViewController:controller animated:YES];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
```
Also Answered here: [MFMessageComposeViewController not properly displayed](https://stackoverflow.com/questions/9927337/mfmessagecomposeviewcontroller-not-properly-displayed/10783751#10783751) | The issue is in portrait view. From what I am seeing if the MFMessageComposeViewController loads in landscape the space isn't there. Then if the orientation changes to portrait the layout is corrected and the space isn't present in portrait.
Note When in landscape the MFMessageComposeViewController is presented by sliding from left to right. I believe that the way the view is presented holds to key to fixing the issue. |
7,157,731 | I'm using the following code to show in-app sms. My app don't have a status bar. (I'm using 320x480 pixels screen in portrait view)
```
if ([MFMessageComposeViewController canSendText])
{
MFMessageComposeViewController* msgController = [[MFMessageComposeViewController alloc] init];
msgController.recipients = [NSArray arrayWithObject:self.globalSMS];
msgController.messageComposeDelegate = self;
[self presentModalViewController:msgController animated:YES];
[msgController release];
}
```
This is working good to display the message view controller. (But status bar comes back, which is not necessary for me to show)
But the problem is that when I click "Cancel" or "Send", after going back to application, I am seeing white space on the top (in position of status bar) of the screen. And status bar is hidden.
Why is it happening when my status bar is set as hidden in app delegate. How to get rid of white space after showing the in-app sms view. | 2011/08/23 | [
"https://Stackoverflow.com/questions/7157731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265341/"
] | Hide the status bar after you modal presented the message controller. Something like this:
```
controller.wantsFullScreenLayout = NO;
[self presentModalViewController:controller animated:YES];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
```
Also Answered here: [MFMessageComposeViewController not properly displayed](https://stackoverflow.com/questions/9927337/mfmessagecomposeviewcontroller-not-properly-displayed/10783751#10783751) | ```
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
if([MFMessageComposeViewController canSendText]){
controller.body = @"MessageText!!!";
controller.recipients = [NSArray arrayWithObjects:@"123"];
controller.messageComposeDelegate = self;
controller.wantsFullScreenLayout = YES;
[self presentModalViewController:controller animated:YES];
}
``` |
553,980 | In a book-length document with `memoir`, I'm getting the following *peculiar output* from this code for the beginning of the index:
```
\renewcommand{\indexname}{Index}
\renewcommand{\preindexhook}{%
\emph{%
For $d$\emph{-ball}, $d$\emph{-bounded set}, $d$\emph{-open set}, $(d,d')$\emph{-continuous map},
etc., see the corresponding entry \emph{ball}, \emph{bounded set}, \emph{open set}, \emph{continuous map}, etc.%
\vskip\onelineskip}%
}
\printindex\cleardoublepage%
```
[](https://i.stack.imgur.com/r7vS8.png)
The surprise is not only that the left- and right-parentheses from `$(d,d')$\emph{-continuous map}` have disappeared, but also that they have been replaced by *-.04em* and *-.15em*, respectively.
The peculiar output occurs no matter whether I use `pdflatex` or `xelatex` (which, as the example below indicates, determines which fonts are used); thus the error occurs with both `newtxtext`/`newtxmath` and `TeX Gyre Termes`/`Tex Gyre Termes Math`.
**Environment of the actual book:**
I'm using MacTeX/TeXLive 2020, with all current updates applied.
Typically, I just run "Typeset" on the root source file `topology.tex` with engine pdflatexmk inside TeXShop.app.
The effect should be the same as successively running:
```
pdflatex topology
bibtex topology
pdflatex topology
pdflatex topology
makeindex topology.nlo -s topology.ist -o topology.nls
makeindex names.idx -s names.ist -o names.ind
makeindex -s topology.ist topology
pdflatex topology
pdflatex topology
```
Here is the beginning of the `.ind` file for the book:
```
\begin{theindex}
\begingroup
\medskip\hfill\large\sffamily\bfseries\ifthenelse{\boolean{colorsecs}}{\color{myseccolor}}{} A\hfill\endgroup\medskip\nopagebreak
\item \idxmark{absolute-value function}, \hyperpage{17},
\hyperpage{323}
\item \idxmark{abstract quotient map}, \hyperpage{419}
```
**Question:** How can that be fixed?
**Failed attempts to fix:**
The following attempts failed to correct the issue:
* `\protect`ing each parenthesis
* `\usepackage{ragged2e)` and changing `\renewcommand{\preindexhook}{...` to `\renewcommand{\preindexhook}{\RaggedRight...`
* replacing `(` and `)`, respectively, with `\lparens` and `\rparens` (from `mathtools`)
* deleting `\,` from `$(d,\,d')$`
**Simple example?**
*I'm unable to reproduce that output in any simple example* short of the entire 600+-page book!
Below is such an example, where the *output is OK*, but with all the relevant code (I hope) and probably some totally irrelevant code (but included "just in case"):
```
% book.tex
\RequirePackage{filecontents}
\begin{filecontents}{book.ist}
% book.ist - MakeIndex style file
% output main entry <entry> as: \item \idxmark{<entry>},
item_0 "\n\\item \\idxmark{"
delim_0 "}, "
% not forgetting the subitem case
item_x1 "} \n \\subitem "
headings_flag 1
heading_prefix "{\\medskip\\hfill\\large\\textsf{\\textbf{"
heading_suffix "}}\\hfill}\\medskip\\nopagebreak\n"
\end{filecontents}
\documentclass{memoir}
\RequirePackage[T2A,T1]{fontenc}
\RequirePackage{amsmath} % avoid \dddot clash
\RequirePackage{mathtools} % load now to avoid unicode-math clash
\RequirePackage{amsthm} % load now to avoid openbox clash
\usepackage{iftex}
\ifTUTeX
\usepackage{fontspec}
\usepackage{polyglossia}
\usepackage{unicode-math}
\setdefaultlanguage[variant=american]{english}
\setotherlanguages{french,german,polish,russian}
\setmainfont{TeX Gyre Termes}[Scale=1.0]
\defaultfontfeatures{Scale=MatchLowercase, Ligatures=TeX}
\setmathfont{TeX Gyre Termes Math}
\newfontfamily{\cyrillicfont}{PT Serif}
\newcommand{\textsi}[1]{\textsc{#1}}
\newfontfamily{\xcheckmarkfont}{LibertinusSerif-Regular.otf}
\else
\usepackage[russian,french,ngerman,polish,main=english]{babel}
\babeltags{russian=russian,french=french,german=ngerman,polish=polish}
\RequirePackage{substitutefont} % to allow non-default Cyrillic
\substitutefont{T2A}{\rmdefault}{Tempora-TLF} % for Cyrillic
\RequirePackage[theoremfont]{newtxtext}
\RequirePackage[vvarbb]{newtxmath}%
\fi
% Additional font series macros
% light series
\DeclareRobustCommand\ltseries
{\not@math@alphabet\ltseries\relax
\fontseries\ltdefault\selectfont}
%
\newcommand{\ltdefault}{l}
%
\DeclareTextFontCommand{\textlt}{\ltseries}
% heavy(bold) series
\DeclareRobustCommand\hbseries
{\not@math@alphabet\hbseries\relax
\fontseries\hbdefault\selectfont}
\newcommand{\hbdefault}{hb}
\DeclareTextFontCommand{\texthb}{\hbseries}
\usepackage{microtype}
\usepackage{ragged2e}
%% PAGE DIMENSIONS
\setstocksize{11in}{8.5in}
\setpagecc{55.25pc}{38pc}{*}
\settypeblocksize{45pc}{28pc}{*}
\setlrmargins{*}{*}{*}
\setulmargins{*}{*}{*}
\checkandfixthelayout
%% PENALTIES
% set \clubpenalty, etc. to distinctive values for use
% in tracing page breaks.
\clubpenalty=9996
\widowpenalty=9999
\brokenpenalty=4991
\predisplaypenalty=10000
\postdisplaypenalty=1549
\displaywidowpenalty=1602
\nouppercaseheads
\makepagestyle{mypage}
\makeheadrule{mypage}{\textwidth}{\normalrulethickness}
\makeevenhead{mypage}{\bfseries\sffamily\thepage}{}{\bfseries\sffamily\leftmark}
\makeoddhead{mypage}{\bfseries\sffamily\rightmark}{}{\bfseries\sffamily\thepage}
\addtopsmarks{mypage}{}{%
% insert "Chapter\space" & "Section\space" if desired as 4th argument:
\createmark{chapter}{left}{shownumber}{}{\enspace}
\createmark{section}{right}{shownumber}{}{\enspace}
}
\makepsmarks{mypage}{%
\createmark{chapter}{both}{shownumber}{}{\enspace} % use both not left
\createmark{section}{right}{shownumber}{}{\enspace}
\createplainmark{toc}{both}{\contentsname}
\createplainmark{shorttableofconents}{both}{\shorttocname}
\createplainmark{longtableofcontents}{both}{\longtocname}
\createplainmark{lof}{both}{\listfigurename}
\createplainmark{lot}{both}{\listtablename}
\createplainmark{bib}{both}{\bibname}
\createplainmark{index}{both}{\indexname}
\createplainmark{glossary}{both}{\glossaryname}
\createplainmark{nomenclature}{both}{\nomname}
}
\providecommand\gobbleone[1]{}
\newcommand{\idxmark}[1]{{\let\gobbleone\relax\markboth{\sffamily\bfseries#1}{\sffamily\bfseries#1}}#1}
\makepagestyle{index}
\makeheadrule{index}{\textwidth}{\normalrulethickness}
% Fix for babel error by daleif (Lars Madsen}
% https://tex.stackexchange.com/a/501483/13492
\makeevenhead{index}%
{\let\gobbleone\relax\sffamily\bfseries\rightmark}%
{\sffamily\bfseries\MakeTextUppercase{\indexname}}%
{\let\gobbleone\relax\sffamily\bfseries\leftmark}
\makeoddhead{index}%
{\let\gobbleone\relax\sffamily\bfseries\rightmark}%
{\sffamily\bfseries\MakeTextUppercase{\indexname}}%
{\let\gobbleone\relax\sffamily\bfseries\leftmark}
\makeevenfoot{index}{}{\sffamily\thepage}{}
\makeoddfoot{index}{}{\sffamily\thepage}{}
\makechapterstyle{mychapter}{%
\renewcommand{\chapnamefont}{\sffamily\bfseries}
\renewcommand{\chapnumfont}{\fontsize{58}{64}\selectfont\sffamily\bfseries}
\renewcommand{\chaptitlefont}{\Huge\sffamily\bfseries}
%
\settoheight{\midchapskip}{\chapnumfont 1}
\setlength{\midchapskip}{0pt}
\setlength{\afterchapskip}{48pt}
%
\renewcommand{\printchaptername}{%
\chapnamefont\centering\MakeUppercase{\@chapapp}\par}
%
\renewcommand*{\printchapternum}{%
\vskip -8pt\centering \chapnumfont\thechapter} % or omit the vskip?
%
\renewcommand{\afterchapternum}{%
\par\nobreak\vskip \midchapskip%
\centering\rule{0.825\textwidth}{\normalrulethickness}%
\newline}
\renewcommand{\printchaptertitle}[1]{\centering\chaptitlefont ##1}
}
\chapterstyle{mychapter}
\usepackage{blindtext}
\makeindex
\begin{document}
\mainmatter
\pagestyle{mypage}
\Blindtext[1]
Alpaca\index{abc}
Zebra\index{zombie}% to fill up index page...
\index{a}\index{aa}\index{aaa}\index{aaaa}\index{aaaaa}\index{aaaaaa}\index{aaaaaaa}\index{aaaaaaaa}
\index{b}\index{bb}\index{bbb}\index{bbbb}\index{bbbbb}\index{bbbbbb}\index{bbbbbbb}\index{bbbbbbbb}
\index{c}\index{cc}\index{ccc}\index{cccc}\index{ccccc}\index{cccccc}\index{ccccccc}\index{cccccccc}
\index{d}\index{dd}\index{ddd}\index{dddd}\index{ddddd}\index{dddddd}\index{ddddddd}\index{dddddddd}
\index{e}\index{ee}\index{eee}\index{eeee}\index{eeeee}\index{eeeeee}\index{eeeeeee}\index{eeeeeeee}
\index{f}\index{ff}\index{fff}\index{ffff}\index{fffff}\index{ffffff}\index{fffffff}\index{ffffffff}
\index{g}\index{gg}\index{ggg}
\index{abcdefghijklmnopqustuvwxyzabcdef}
\index{zbcdefghijklmnopqustuvwxyzabcdef}
\backmatter
\pagestyle{index}
\setlength{\columnsep}{1em}
\renewcommand{\indexname}{Index}
\renewcommand{\preindexhook}{%
\emph{%
For $d$\emph{-ball}, $d$\emph{-bounded set}, $d$\emph{-open set}, $(d,\,d')$\emph{-continuous map},
etc., see the corresponding entry \emph{ball}, \emph{bounded set}, \emph{open set}, \emph{continuous map}, etc.%
\vskip\onelineskip}%
}
\printindex\cleardoublepage%
\end{document}
```
**Added:**
I also tried in the "simple example" above replacing the preamble by the actual preamble of my book-length document (actually, an inputted `.tex` file which contains a bunch of `\usepackage` commands for the several files constituting my preamble — a total of 16 files with some 120K). But still that does not cause the peculiar problem!
**Possible work-around:**
The following work-around seems to cure the problem. But I'm unhappy about the way that I had to fake the pair of parentheses, which really ought to be inside the inline math!
```
\renewcommand{\preindexhook}{%
\emph{%
For $d$\emph{-ball}, $d$\emph{-bounded set}, $d$\emph{-open set}, \emph{(}$d,d'$\emph{)\hspace{2pt}-continuous map},
etc.,
see the corresponding entry \emph{ball}, \emph{bounded set}, \emph{open set}, \emph{continuous map}, etc.%
\vskip\onelineskip}%
}
``` | 2020/07/17 | [
"https://tex.stackexchange.com/questions/553980",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/13492/"
] | It is a bug in embrac, in one place it uses `#4` instead of `#3`. Try this and notify the author:
```
\usepackage{embrac}
\ExplSyntaxOn
\cs_set_protected:Npn \__embrac_replace:Nnnnn #1#2#3#4#5
{
\tl_replace_all:Nnn #1 {#3}
{
\mode_if_math:TF
{#3} %<---instead of #4
{
\embrac_nobreak:
\embrac_kern:n {#2}
\embrac_nobreak:
\embrac_braces_format:n {#3}
\embrac_nobreak:
\embrac_kern:n {#4}
#5
}
}
}
\ExplSyntaxOff
``` | This is not an answer to the problem, but rather a short write up of the actual problem. It is not related to `memoir` or `\preindexhook`, it boils down to a problem with the `embrac` package that @murray loads deep deep down in their many setup files.
Here is a super short MWE that displays the problem.
```
\documentclass{article}
\usepackage{embrac}
\begin{document}
\emph{$(d,d')$}
\end{document}
```
On my fully up to date TeXLive 2020 I get
[](https://i.stack.imgur.com/gsgnF.png)
which is strange as the `embrac` history mentions that v0.5 was made to not mess with math. But perhaps `expl3` was changed.
```
*File List*
article.cls 2019/12/20 v1.4l Standard LaTeX document class
size10.clo 2019/12/20 v1.4l Standard LaTeX file (size option)
embrac.sty 2019/12/31 v0.9 Upright Brackets in Emphasized Text
expl3.sty 2020-07-17 L3 programming layer (loader)
l3backend-pdfmode.def 2020-06-29 L3 backend support: PDF mode
xparse.sty 2020-05-15 L3 Experimental document command parser
xparse-generic.tex
l3keys2e.sty 2020-05-15 LaTeX2e option processing using LaTeX3 keys
``` |
17,137,171 | Here's one I've come close to figuring out, but never really did.
The code listed below is supposed to draw a green circle as soon as it sees its first click. It doesn't. Subsequent clicks draw lines that connect the current clicked point with the previous one, in red. The code fails for the first click and works on all subsequent ones. Why doesn't the first click display? It runs!
What am I doing wrong?
The code should compile on any current JDE.
TIA
```
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
class Demo extends JFrame
implements ActionListener, ListSelectionListener, MouseListener {
int clkCt = 0, // Count of the number of clicks we've done.
oldX, // Penultimate X value
oldY, // Penultimate X value
scrH, // Height of the drawing canvas.
scrW; // Width of the drawing canvas.
JFrame f; // Holder for the drawing canvas.
JLabel ctL; // Displays the number of clicks we've done.
JPanel canvas; // The drawing canvas.
public void demoLines() {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
scrH = (int) ((double) d.height * 0.75);
scrW = (int) ((double) d.width * 0.75);
oldX = scrH / 2;
oldY = oldX;
// Create and set up the window.
f = new JFrame("Multi Click Demo");
f.getContentPane().setLayout(null);
int h = scrH / 5;
f.setBounds(h, h, scrW, scrH);
// Create a panel
canvas = new JPanel();
canvas.setBackground(Color.black);
canvas.setForeground(Color.red);
canvas.setLayout(null);
canvas.setBounds(0, 0, scrW, scrH);
canvas.setPreferredSize(new Dimension(scrW, scrH));
canvas.addMouseListener(this);
f.getContentPane().add(canvas);
// Create the exit button.
JButton exit = new JButton("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
goAway();
}
});
exit.setBackground(Color.black);
exit.setForeground(Color.red);
exit.setBounds(0, 0, (scrW / 15), (scrH / 15));
canvas.add(exit); //*/
// Create the label for the click count.
ctL = new JLabel("None Yet");
ctL.setBackground(Color.black);
ctL.setForeground(Color.red);
ctL.setBounds((scrH / 15), (scrH * 13 / 15), (scrW / 15), (scrH / 15));
canvas.add(ctL);
f.getContentPane().add(canvas);
f.setVisible(true);
Graphics g = canvas.getGraphics();
if (g == null) {
System.out.println("No graphics for canvas!");
} else {
canvas.revalidate(); // This didn't help.
paintComponent(g, (oldX + oldX / 2), (oldY + oldY / 2));
}
}
void goAway() {
f.setVisible(false);
f.dispose();
}
public void mouseClicked(MouseEvent m) {
// Where was the mouse clicked?
int clkdBtn = m.getButton(),
x = m.getX(),
y = m.getY();
Graphics g = canvas.getGraphics();
paintComponent(g, x, y);
}
public void paintComponent(Graphics g,
int x,
int y) {
// This always runs.
ctL.setText(clkCt + "");
if (clkCt == 0) {
// This never displays!
g.setColor(Color.green);
int r = scrH * 4 / 5;
g.drawOval((scrH / 10), (scrH / 10), r, r);
}
g.setColor(Color.red);
g.drawLine(oldX, oldY, x, y);
oldX = x;
oldY = y;
clkCt++;
}
public void actionPerformed(ActionEvent event) { }
public void valueChanged(ListSelectionEvent event) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public static void main(String[] s) {
Demo m = new Demo();
m.demoLines();
}
}
``` | 2013/06/16 | [
"https://Stackoverflow.com/questions/17137171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1333380/"
] | remove the following lines from `demolines()`
```
Graphics g = canvas.getGraphics();
if (g == null) {
System.out.println("No graphics for canvas!");
} else {
canvas.revalidate(); // This didn't help.
paintComponent(g, (oldX + oldX / 2), (oldY + oldY / 2));
}
```
and add `canvas.addMouseListener(this);` in the end of the function | You should always call `super.paintComponent()` as the first line when you override `paintComponent()`. |
17,137,171 | Here's one I've come close to figuring out, but never really did.
The code listed below is supposed to draw a green circle as soon as it sees its first click. It doesn't. Subsequent clicks draw lines that connect the current clicked point with the previous one, in red. The code fails for the first click and works on all subsequent ones. Why doesn't the first click display? It runs!
What am I doing wrong?
The code should compile on any current JDE.
TIA
```
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
class Demo extends JFrame
implements ActionListener, ListSelectionListener, MouseListener {
int clkCt = 0, // Count of the number of clicks we've done.
oldX, // Penultimate X value
oldY, // Penultimate X value
scrH, // Height of the drawing canvas.
scrW; // Width of the drawing canvas.
JFrame f; // Holder for the drawing canvas.
JLabel ctL; // Displays the number of clicks we've done.
JPanel canvas; // The drawing canvas.
public void demoLines() {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
scrH = (int) ((double) d.height * 0.75);
scrW = (int) ((double) d.width * 0.75);
oldX = scrH / 2;
oldY = oldX;
// Create and set up the window.
f = new JFrame("Multi Click Demo");
f.getContentPane().setLayout(null);
int h = scrH / 5;
f.setBounds(h, h, scrW, scrH);
// Create a panel
canvas = new JPanel();
canvas.setBackground(Color.black);
canvas.setForeground(Color.red);
canvas.setLayout(null);
canvas.setBounds(0, 0, scrW, scrH);
canvas.setPreferredSize(new Dimension(scrW, scrH));
canvas.addMouseListener(this);
f.getContentPane().add(canvas);
// Create the exit button.
JButton exit = new JButton("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
goAway();
}
});
exit.setBackground(Color.black);
exit.setForeground(Color.red);
exit.setBounds(0, 0, (scrW / 15), (scrH / 15));
canvas.add(exit); //*/
// Create the label for the click count.
ctL = new JLabel("None Yet");
ctL.setBackground(Color.black);
ctL.setForeground(Color.red);
ctL.setBounds((scrH / 15), (scrH * 13 / 15), (scrW / 15), (scrH / 15));
canvas.add(ctL);
f.getContentPane().add(canvas);
f.setVisible(true);
Graphics g = canvas.getGraphics();
if (g == null) {
System.out.println("No graphics for canvas!");
} else {
canvas.revalidate(); // This didn't help.
paintComponent(g, (oldX + oldX / 2), (oldY + oldY / 2));
}
}
void goAway() {
f.setVisible(false);
f.dispose();
}
public void mouseClicked(MouseEvent m) {
// Where was the mouse clicked?
int clkdBtn = m.getButton(),
x = m.getX(),
y = m.getY();
Graphics g = canvas.getGraphics();
paintComponent(g, x, y);
}
public void paintComponent(Graphics g,
int x,
int y) {
// This always runs.
ctL.setText(clkCt + "");
if (clkCt == 0) {
// This never displays!
g.setColor(Color.green);
int r = scrH * 4 / 5;
g.drawOval((scrH / 10), (scrH / 10), r, r);
}
g.setColor(Color.red);
g.drawLine(oldX, oldY, x, y);
oldX = x;
oldY = y;
clkCt++;
}
public void actionPerformed(ActionEvent event) { }
public void valueChanged(ListSelectionEvent event) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public static void main(String[] s) {
Demo m = new Demo();
m.demoLines();
}
}
``` | 2013/06/16 | [
"https://Stackoverflow.com/questions/17137171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1333380/"
] | >
> What am I doing wrong?
>
>
>
You're using `getGraphics` for custom painting. Any previous painting will be lost when a `repaint` is called. Instead move all the custom painting functionality to a new class based on `JComponent` or `JPanel` and override [paintComponent](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#paintComponent%28java.awt.Graphics%29) there. Remember to invoke `super.paintComponent(g)`.
See [Custom Painting Approaches](http://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/) for solutions for drawing multiple components from within `paintComponent`. You can build a `List<Shape>` of custom drawable components, iterate through the list from within the method, and use `drawLine` or `drawOval` as appropriate. | You should always call `super.paintComponent()` as the first line when you override `paintComponent()`. |
17,137,171 | Here's one I've come close to figuring out, but never really did.
The code listed below is supposed to draw a green circle as soon as it sees its first click. It doesn't. Subsequent clicks draw lines that connect the current clicked point with the previous one, in red. The code fails for the first click and works on all subsequent ones. Why doesn't the first click display? It runs!
What am I doing wrong?
The code should compile on any current JDE.
TIA
```
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
class Demo extends JFrame
implements ActionListener, ListSelectionListener, MouseListener {
int clkCt = 0, // Count of the number of clicks we've done.
oldX, // Penultimate X value
oldY, // Penultimate X value
scrH, // Height of the drawing canvas.
scrW; // Width of the drawing canvas.
JFrame f; // Holder for the drawing canvas.
JLabel ctL; // Displays the number of clicks we've done.
JPanel canvas; // The drawing canvas.
public void demoLines() {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
scrH = (int) ((double) d.height * 0.75);
scrW = (int) ((double) d.width * 0.75);
oldX = scrH / 2;
oldY = oldX;
// Create and set up the window.
f = new JFrame("Multi Click Demo");
f.getContentPane().setLayout(null);
int h = scrH / 5;
f.setBounds(h, h, scrW, scrH);
// Create a panel
canvas = new JPanel();
canvas.setBackground(Color.black);
canvas.setForeground(Color.red);
canvas.setLayout(null);
canvas.setBounds(0, 0, scrW, scrH);
canvas.setPreferredSize(new Dimension(scrW, scrH));
canvas.addMouseListener(this);
f.getContentPane().add(canvas);
// Create the exit button.
JButton exit = new JButton("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
goAway();
}
});
exit.setBackground(Color.black);
exit.setForeground(Color.red);
exit.setBounds(0, 0, (scrW / 15), (scrH / 15));
canvas.add(exit); //*/
// Create the label for the click count.
ctL = new JLabel("None Yet");
ctL.setBackground(Color.black);
ctL.setForeground(Color.red);
ctL.setBounds((scrH / 15), (scrH * 13 / 15), (scrW / 15), (scrH / 15));
canvas.add(ctL);
f.getContentPane().add(canvas);
f.setVisible(true);
Graphics g = canvas.getGraphics();
if (g == null) {
System.out.println("No graphics for canvas!");
} else {
canvas.revalidate(); // This didn't help.
paintComponent(g, (oldX + oldX / 2), (oldY + oldY / 2));
}
}
void goAway() {
f.setVisible(false);
f.dispose();
}
public void mouseClicked(MouseEvent m) {
// Where was the mouse clicked?
int clkdBtn = m.getButton(),
x = m.getX(),
y = m.getY();
Graphics g = canvas.getGraphics();
paintComponent(g, x, y);
}
public void paintComponent(Graphics g,
int x,
int y) {
// This always runs.
ctL.setText(clkCt + "");
if (clkCt == 0) {
// This never displays!
g.setColor(Color.green);
int r = scrH * 4 / 5;
g.drawOval((scrH / 10), (scrH / 10), r, r);
}
g.setColor(Color.red);
g.drawLine(oldX, oldY, x, y);
oldX = x;
oldY = y;
clkCt++;
}
public void actionPerformed(ActionEvent event) { }
public void valueChanged(ListSelectionEvent event) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public static void main(String[] s) {
Demo m = new Demo();
m.demoLines();
}
}
``` | 2013/06/16 | [
"https://Stackoverflow.com/questions/17137171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1333380/"
] | There were a multitude of problems with that code. I fixed them but neglected to document every change. Look closely over this code and ask questions if you do not understand (from reading the relevant documentation/tutorial) why I made the change.

```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.EmptyBorder;
public class Demo extends JPanel
implements ListSelectionListener, MouseListener {
int clkCt = 0, // Count of the number of clicks we've done.
oldX, // Penultimate X value
oldY, // Penultimate X value
scrH = 100, // Height of the drawing canvas.
scrW = 400; // Width of the drawing canvas.
JLabel ctL; // Displays the number of clicks we've done.
int x, y;
public void demoLines() {
oldX = scrH / 2;
oldY = oldX;
// Create a panel
setBackground(Color.black);
setForeground(Color.red);
setPreferredSize(new Dimension(scrW, scrH));
// Create the label for the click count.
ctL = new JLabel("None Yet");
ctL.setBackground(Color.black);
ctL.setForeground(Color.red);
ctL.setBounds((scrH / 15), (scrH * 13 / 15), (scrW / 15), (scrH / 15));
add(ctL);
addMouseListener(this);
}
public void mouseClicked(MouseEvent m) {
// Where was the mouse clicked?
x = m.getX();
y = m.getY();
repaint();
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
public void paintComponent(Graphics g) {
// This always runs.
ctL.setText(clkCt + "");
if (clkCt == 0) {
// This never displays!
g.setColor(Color.green);
int r = scrH * 4 / 5;
g.drawOval((scrH / 10), (scrH / 10), r, r);
}
g.setColor(Color.red);
g.drawLine(oldX, oldY, x, y);
oldX = x;
oldY = y;
clkCt++;
}
public void valueChanged(ListSelectionEvent event) {
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
Demo m = new Demo();
m.demoLines();
JFrame f = new JFrame("Demo");
f.add(m);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
```
Notes
-----
1. Don't extend frame or other top level containers. Instead create & use an instance of one.
2. Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them, along with layout padding & borders for white space.
3. Instead of painting in a top level container such as `JFrame`, add a `JPanel` & do custom painting in the `paintComponent(Graphics)` method. Also return a sensible preferred size for the custom component, to assist the layout manager.
4. For custom painting in a `JComponent`, override `paintComponent(Graphics)` instead of `paint(Graphics)`. | You should always call `super.paintComponent()` as the first line when you override `paintComponent()`. |
129,565 | I recently came out of an introductory interview for a startup-like company and felt that the interview went well. Not perfect, as I was not invited for a second interview (I did not really fit the position anyway). I think what knocked me out of consideration was that I did not have a good answer to a question like "What do you want to do with your life?". The job was a manager role for a marketing firm, but my degree is in biochemistry and my work history is manufacturing (more recently materials management). So marketing is miles away from my experience.
I don't want to pursue a career in my degree for various reasons and I am applying for jobs that I think are interesting. I'm not picky since I haven't decided on a career path yet, just want to be able to pay my bills and have savings for the future. I'm an excellent worker with a good skill set (got promoted to a lead position within months at my current company with a 40% raise to another position after 1.5 years of employment). However, I'm having trouble getting my foot in the door.
How do I convey in interviews that despite any specific career goals I am a diligent worker? | 2019/02/19 | [
"https://workplace.stackexchange.com/questions/129565",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/100111/"
] | "I've switched career paths three times, but I'm a diligent worker, honest!" ...will never work, and it sounds like you're taking that approach.
>
> I think what knocked me out of consideration was that I did not have a good answer to a question like "What do you want to do with your life?" The job was a manager role for a marketing firm, but my degree is in biochemistry and my work history is manufacturing.
>
>
>
If I was looking at a candidate like this, rightly or wrongly, my initial reaction would be "This guy flits around a lot between industries - he has a degree in something, a background in something else and now he's applying for something else completely unrelated." I don't think I'd be alone in that assumption, and it doesn't work in your favour.
This means you're immediately on the back foot - so you need to do one of two things.
* Either you need to correct my thinking, showing that you're *not* flitting around at all;
* You need to show concrete reasons why this "flitting around" can be seen as a positive, showing what you're learnt on the way, and pressing home how transferable skills you've picked up elsewhere could be really useful in this sector.
It sounds like option 2 is much more likely in your case, and that means you have to have a *really good*, convincing answer to that question. To form a good case, you need to:
* Be honest. Feel free to lead with something akin to "I certainly don't have a typical career history for this sector do I! However, because of that I think I can bring something really unique to the table." (then present your argument.)
* Do tons of research in your target industry. Get to know the common terms, and use them. Don't pretend you know everything about the sector, but show that you're able to have a meaningful conversation without someone explaining every little item to you from the ground up.
* Have a really convincing argument prepared as to why you're going to stay in this industry and this role. You've changed tactic twice before, what's to say you won't again? Be prepared to present a good case there, again showing you've thought about the options. | >
> I think what knocked me out of consideration was that I did not have a good answer to a question like "What do you want to do with your life?" The job was a manager role for a marketing firm, but my degree is in biochemistry and my work history is manufacturing (more recently materials management). So marketing is miles away from my experience.
>
>
>
I was asked the "What do you want to do with your life?" question too for a small biotech startup and I was also doing a career switch into a Technical Program Manager. I answered honestly and said that I don't have the next several years of my life mapped out like some people might. I want to be in a role when I can feel like I'm making an impact and have enough ambiguity that I can really make the role my own.
The recruiter who asked me the question told me that flexibility and making an impact is why she joined the company too and find that people that have same mindset do the best in the company. Early startups in many ways lack of structure and that's what allows them to make decisions and pivot more quickly than established companies. But, for people that crave structure and organization, startups are a nightmare and they aren't a good fit for the company at this stage. Asking the "What do you want to do with your life?" is a good proxy to screen out the people that are too structured for poor culture fit.
Given what you wrote in the question, you seem quite flexible. **I suspect you did poorly on another question and not the "What do you want to do with your life?" one.** |
129,565 | I recently came out of an introductory interview for a startup-like company and felt that the interview went well. Not perfect, as I was not invited for a second interview (I did not really fit the position anyway). I think what knocked me out of consideration was that I did not have a good answer to a question like "What do you want to do with your life?". The job was a manager role for a marketing firm, but my degree is in biochemistry and my work history is manufacturing (more recently materials management). So marketing is miles away from my experience.
I don't want to pursue a career in my degree for various reasons and I am applying for jobs that I think are interesting. I'm not picky since I haven't decided on a career path yet, just want to be able to pay my bills and have savings for the future. I'm an excellent worker with a good skill set (got promoted to a lead position within months at my current company with a 40% raise to another position after 1.5 years of employment). However, I'm having trouble getting my foot in the door.
How do I convey in interviews that despite any specific career goals I am a diligent worker? | 2019/02/19 | [
"https://workplace.stackexchange.com/questions/129565",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/100111/"
] | "I've switched career paths three times, but I'm a diligent worker, honest!" ...will never work, and it sounds like you're taking that approach.
>
> I think what knocked me out of consideration was that I did not have a good answer to a question like "What do you want to do with your life?" The job was a manager role for a marketing firm, but my degree is in biochemistry and my work history is manufacturing.
>
>
>
If I was looking at a candidate like this, rightly or wrongly, my initial reaction would be "This guy flits around a lot between industries - he has a degree in something, a background in something else and now he's applying for something else completely unrelated." I don't think I'd be alone in that assumption, and it doesn't work in your favour.
This means you're immediately on the back foot - so you need to do one of two things.
* Either you need to correct my thinking, showing that you're *not* flitting around at all;
* You need to show concrete reasons why this "flitting around" can be seen as a positive, showing what you're learnt on the way, and pressing home how transferable skills you've picked up elsewhere could be really useful in this sector.
It sounds like option 2 is much more likely in your case, and that means you have to have a *really good*, convincing answer to that question. To form a good case, you need to:
* Be honest. Feel free to lead with something akin to "I certainly don't have a typical career history for this sector do I! However, because of that I think I can bring something really unique to the table." (then present your argument.)
* Do tons of research in your target industry. Get to know the common terms, and use them. Don't pretend you know everything about the sector, but show that you're able to have a meaningful conversation without someone explaining every little item to you from the ground up.
* Have a really convincing argument prepared as to why you're going to stay in this industry and this role. You've changed tactic twice before, what's to say you won't again? Be prepared to present a good case there, again showing you've thought about the options. | For someone changing fields, "what do you want to do with your life?" is a reasonable question. From the hiring manager's point of view, they want to see commitment to the path their job puts you on. If they were rude, they might ask "Why leave behind all your specific scientific training to do THIS job? Are you going to leave this job as soon as you find a job in your own field? Will I be stuck trying to hire another person in a year?"
You need an answer to this question for every interview. It's a big part of explaining who you are and what you bring to a job. My suggestion: work out a good answer to use in interviews. Maybe you should even get a friend to listen to your answer and help you refine it.
Of course your life plan isn't carved on a stone tablet. It changes as your life progresses. Still, it's good to be able to state your plan when you're looking for work.
Do some research on the company and the job before you turn up for the interview. Work out your "do with your life" answer *as if you already had the job.*
Prepare to say something about why you're switching fields. It can be as simple as "I'm allergic to acetone, so I must leave the lab." It can be "I want to work with people, not pipettes." You need to have a thoughtful and honest answer to this question for interviews.
As for your question about proving you're a diligent worker, simply say so. You can say "my degree field is notorious for being difficult, and I did well in it." And you can say "I like learning new things and I learn quickly." Prepare two or three examples where these personal strengths made a difference to your employer.
(This answer is from a former molecular biology student who went on to a good career in another field.) |
129,565 | I recently came out of an introductory interview for a startup-like company and felt that the interview went well. Not perfect, as I was not invited for a second interview (I did not really fit the position anyway). I think what knocked me out of consideration was that I did not have a good answer to a question like "What do you want to do with your life?". The job was a manager role for a marketing firm, but my degree is in biochemistry and my work history is manufacturing (more recently materials management). So marketing is miles away from my experience.
I don't want to pursue a career in my degree for various reasons and I am applying for jobs that I think are interesting. I'm not picky since I haven't decided on a career path yet, just want to be able to pay my bills and have savings for the future. I'm an excellent worker with a good skill set (got promoted to a lead position within months at my current company with a 40% raise to another position after 1.5 years of employment). However, I'm having trouble getting my foot in the door.
How do I convey in interviews that despite any specific career goals I am a diligent worker? | 2019/02/19 | [
"https://workplace.stackexchange.com/questions/129565",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/100111/"
] | "I've switched career paths three times, but I'm a diligent worker, honest!" ...will never work, and it sounds like you're taking that approach.
>
> I think what knocked me out of consideration was that I did not have a good answer to a question like "What do you want to do with your life?" The job was a manager role for a marketing firm, but my degree is in biochemistry and my work history is manufacturing.
>
>
>
If I was looking at a candidate like this, rightly or wrongly, my initial reaction would be "This guy flits around a lot between industries - he has a degree in something, a background in something else and now he's applying for something else completely unrelated." I don't think I'd be alone in that assumption, and it doesn't work in your favour.
This means you're immediately on the back foot - so you need to do one of two things.
* Either you need to correct my thinking, showing that you're *not* flitting around at all;
* You need to show concrete reasons why this "flitting around" can be seen as a positive, showing what you're learnt on the way, and pressing home how transferable skills you've picked up elsewhere could be really useful in this sector.
It sounds like option 2 is much more likely in your case, and that means you have to have a *really good*, convincing answer to that question. To form a good case, you need to:
* Be honest. Feel free to lead with something akin to "I certainly don't have a typical career history for this sector do I! However, because of that I think I can bring something really unique to the table." (then present your argument.)
* Do tons of research in your target industry. Get to know the common terms, and use them. Don't pretend you know everything about the sector, but show that you're able to have a meaningful conversation without someone explaining every little item to you from the ground up.
* Have a really convincing argument prepared as to why you're going to stay in this industry and this role. You've changed tactic twice before, what's to say you won't again? Be prepared to present a good case there, again showing you've thought about the options. | >
> "What do you want to do with your life?"
>
>
>
I don't want to claim to know the best, objective answer to the question, but I have an approach. So when we're saddled with a difficult question, one of the things we (people) do is wrongly try to tackle the whole problem at the same time. As complexity increases, it gets harder and harder to do this. The workaround is decompose the main issue into smaller, more workable problems. So, first you have to know what to break the big issue into, and in part this is why people go to therapy. As for the question **what do I want to do with my life**, I would decompose life first into *the foreseeable future*, and then decompose the foreseeable future into a *reasonable timeline*.
Okay so for me, good milestones are what do I want to accomplish in 1yr, 3yrs and 5yrs. You can also think about 1/5/10 years, whatever you can conceptualize. Then think about what you'd like to see done by those milestones. It doesn't have to be what actually happens, just what you'd *like* to see happen. And so then when the next person asks you what you want to do with your life, you can firmly tell them how you think your next several years should progress, since no one can see 30 years into the future. Even nailing down a year is more helpful than having nothing planned at all.
>
> How do I convey in interviews that despite any specific career goals I am a diligent worker?
>
>
>
The main hurdle, and as a science graduate you'd probably understand, but if I hire someone to do biological research and I look over their experience and realize they've never used a pipet or cultured cells, I'm most likely to hire someone who has the minimum bench experience over the one who has none. There is a chasm between diligence and experience that you can overcome with hard work, just not in a timeframe any reasonable employer might require. You have positions where the employer expects you will need to be developed, and others where you'll need to hit the ground running. Marketing manager feels like the latter case.
If you think your skillset is worth the lack of domain experience, you need to sell that in your interviews. No generalities, be specific and sell *why* your skillset will allow you to succeed. You might even find a gap in your understanding that will hold you back in interviews if you try to convince yourself first before you try to convince the interviewer. e.g. "I'm really good with Microsoft Access" versus "I lead the development of an Access database that got our receiving department on track with tracking such-and-such. And this is transferable in that it'll help me ... [something to do with role you're interviewing for]." |
12,292,932 | I have some kernel threads in Linux kernel, inside my KLM.
I have a server thread, that listens to the channel, Once it sees there is an incoming connection, it creates an accept socket, accepts the connection and spawns a child thread. It also passes the accepted socket to the child kernel thread as the (void \*) argument.
The code is working fine. I had a design question.
Suppose now the threads have to be terminated, main and the child threads, what would be the best way to close the accept socket. I can see two ways,
1] The main thread waits for all the child threads to exit, each of the child threads close the accept sockets while exiting, the last child thread passes a signal to the main thread for it to exit . Here even though the main thread was the one that created the accept socket, the child threads close that socket, and they do this before the main thread exits. So is this acceptable? Any problems you guys forsee here?
2] Second is the main thread closes all the accept sockets it created before it exits. But there may be a possibility(corner case) that the main thread gets an exception and will have to close, so if it closes the accept sockets before exiting, the child threads using that socket will be in danger.
Hence i am using the first case i mentioned.Let me know what you guys think? | 2012/09/06 | [
"https://Stackoverflow.com/questions/12292932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1251211/"
] | From the Javadoc for [`Class.getResourceAsStream()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29):
>
> This method delegates to this object's class loader.
> Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
>
>
> * If the `name` begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
> * Otherwise, the absolute name is of the following form:
> `modified_package_name/name`
>
> Where the modified\_package\_name is the package name of this object with '/' substituted for '.' ('\u002e').
>
>
>
In other words, they do the same thing if the "path" begins with a "/", but if not, then in the latter case, the path will be relative to the class's package, whereas the classloader one will be absolute.
In short, the first fetches `path/to/my/properties` and the second fetches `package/of/myclass/path/to/my/properties`. | From the `Class.getClassLoader()` [documentation](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getClassLoader%28%29):
>
> Returns the class loader for the class. Some implementations may use
> null to represent the bootstrap class loader. This method will return
> null in such implementations if this class was loaded by the bootstrap
> class loader.
>
>
>
So `getClassLoader()` *may* return `null` if the class was loaded by the bootstrap class loader, hence the null check in the `Class.getResourceAsStream` [implementation](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/Class.java#Class.getResourceAsStream%28java.lang.String%29):
```
public InputStream getResourceAsStream(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader0();
if (cl==null) {
// A system class.
return ClassLoader.getSystemResourceAsStream(name);
}
return cl.getResourceAsStream(name);
}
```
You'll also note the statement `name = resolveName(name);` which Mark Peters has explained in [his answer](https://stackoverflow.com/a/12292945/697449). |
12,292,932 | I have some kernel threads in Linux kernel, inside my KLM.
I have a server thread, that listens to the channel, Once it sees there is an incoming connection, it creates an accept socket, accepts the connection and spawns a child thread. It also passes the accepted socket to the child kernel thread as the (void \*) argument.
The code is working fine. I had a design question.
Suppose now the threads have to be terminated, main and the child threads, what would be the best way to close the accept socket. I can see two ways,
1] The main thread waits for all the child threads to exit, each of the child threads close the accept sockets while exiting, the last child thread passes a signal to the main thread for it to exit . Here even though the main thread was the one that created the accept socket, the child threads close that socket, and they do this before the main thread exits. So is this acceptable? Any problems you guys forsee here?
2] Second is the main thread closes all the accept sockets it created before it exits. But there may be a possibility(corner case) that the main thread gets an exception and will have to close, so if it closes the accept sockets before exiting, the child threads using that socket will be in danger.
Hence i am using the first case i mentioned.Let me know what you guys think? | 2012/09/06 | [
"https://Stackoverflow.com/questions/12292932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1251211/"
] | From the Javadoc for [`Class.getResourceAsStream()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29):
>
> This method delegates to this object's class loader.
> Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
>
>
> * If the `name` begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
> * Otherwise, the absolute name is of the following form:
> `modified_package_name/name`
>
> Where the modified\_package\_name is the package name of this object with '/' substituted for '.' ('\u002e').
>
>
>
In other words, they do the same thing if the "path" begins with a "/", but if not, then in the latter case, the path will be relative to the class's package, whereas the classloader one will be absolute.
In short, the first fetches `path/to/my/properties` and the second fetches `package/of/myclass/path/to/my/properties`. | The main practical difference is that you can use relative paths when you go through the class. So if your properties are in the same package as MyClass, you can do
```
MyClass.class.getResourceAsStream("properties");
``` |
61,912,017 | the problem i am facing is that my result set is only returning one row value while there are three.
and i could not found where the problem is:
```
public void eventInfo() throws SQLException
{
openConnection();
PreparedStatement ps1=null;
String query1="select * from events";
try {
ps1 = con.prepareStatement(query1);
} catch (SQLException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
}
EventData e= new EventData();
e.edata.clear();
Events obj = new Events();
ResultSet s=ps1.executeQuery();
int i=0;
System.out.println(s);
if(s.next())
{
// obj.setId(s.getInt("id"));
// obj.setTitle(s.getString("title"));
// obj.setDescription(s.getString("description"));
//
// obj.setType(s.getString("type"));
// obj.setOrganization(s.getString("organization"));
// obj.setPlace(s.getString("place"));
// obj.setTime(s.getString("time"));
// obj.setDate(s.getString("date"));
// obj.setRepetetion(s.getString("repetetion"));
// obj.setParticipants(s.getInt("participants"));
// obj.setLimit(s.getInt("elimit"));
System.out.println(i);
System.out.println(s.getString("title"));
i++;
// e.edata.add(obj);
}
if(con!=null)
{
con.close();
}
}
```
the database tables like
[enter image description here](https://i.stack.imgur.com/mA7l1.png)
the output looks like
[enter image description here](https://i.stack.imgur.com/lBuao.png)
can anyone help me with that? | 2020/05/20 | [
"https://Stackoverflow.com/questions/61912017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12210788/"
] | It should not surprise you that
```
if(s.next())
```
is not a loop but rather a condition. If you want to continuously access the result set you have to use a loop
```
while (s.next())
``` | ```
while (s.next()) {...}
```
...should do it for you. This will iterate through all rows. |
63,456,649 | The only documentation I can find is [here](https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer?tabs=csharp) but it doesn't really explain the properties on the TimerInfo class. Some questions I have
* Does the function extension use the azure storage to save the last time the function triggered and compare that to the current execution time to see if it missed an execution and set `IsPastDue` to true?
* Will `IsPastDue` be set to true if the function triggers a few seconds or milliseconds late or only if it missed an execution completely?
* Is `ScheduleStatus.Last` the last time it triggered or is that just computed based on the cron expression?
* What is `ScheduleStatus.LastUpdated` is that the last time I changed the cron expression?
* What is `Schedule.GetNextOccurrence` does that return same thing as `ScheduleStatus.Next` if I pass `DateTime.Now` | 2020/08/17 | [
"https://Stackoverflow.com/questions/63456649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5395257/"
] | After doing some testing and reading the source code this is my summary of what it does. I'll explain what it does when `UseMonitor` is set to true.
When the function host starts it checks the azure storage for the last time the trigger executed. If it has never executed it waits for the next scheduled occurrence based on your cron expression. If it has executed before it compares the last time it executed to the current time to see if it missed any executions. If it did miss any it immediately executes your function and passes `IsPastDue` as true. Then it continues to execute on the regular schedule.
`ScheduleStatus.Last`:
* The first time running it will be set to `default(DateTime)`.
* If its past due it will be the actual last time your function executed
* Otherwise it is the last time it executed rounded to the nearest scheduled execution
`ScheduleStatus.Next`:
* The next scheduled execution time which is usually approximately the current time unless the execution is past due in which case it would be in the past.
`ScheduleStatus.LastUpdated`:
* As for as I can tell this is the same as `ScheduleStatus.Last` except it will be `default(DateTime)` if its the first execution | >
> Does the function extension use the azure storage to save the last
> time the function triggered and compare that to the current execution
> time to see if it missed an execution and set IsPastDue to true?
>
>
>
The default value of the IsPastDue is false.
```
public TimerInfo(TimerSchedule schedule, ScheduleStatus status, bool isPastDue = false)
{
Schedule = schedule;
ScheduleStatus = status;
IsPastDue = isPastDue;
}
```
>
> Will IsPastDue be set to true if the function triggers a few seconds
> or milliseconds late or only if it missed an execution completely?
>
>
>
If the schedule is past due, this value will be true.
>
> Is ScheduleStatus.Last the last time it triggered or is that just
> computed based on the cron expression?
>
>
>
The value is obtained from `DateTime.Now`(The time you execute last time.), not computed based on the cron expression.
>
> What is ScheduleStatus.LastUpdated is that the last time I changed the
> cron expression?
>
>
>
This value is obtained from the as same value as ScheduleStatus.Last:
```
ScheduleStatus = new ScheduleStatus
{
Last = adjustedInvocationTime,
Next = _schedule.GetNextOccurrence(adjustedInvocationTime),
LastUpdated = adjustedInvocationTime
};
```
>
> What is Schedule.GetNextOccurrence does that return same thing as
> ScheduleStatus.Next if I pass DateTime.Now
>
>
>
Because ScheduleStatus is instantiated by the value provided by Schedule.GetNextOccurrence.
The source code:
<https://github.com/Azure/azure-webjobs-sdk-extensions/blob/a3a5a49a64f3592c1eb7c1296086dc83c2011e96/src/WebJobs.Extensions/Extensions/Timers/TimerInfo.cs>
<https://github.com/Azure/azure-webjobs-sdk-extensions/blob/a3a5a49a64f3592c1eb7c1296086dc83c2011e96/src/WebJobs.Extensions/Extensions/Timers/Listener/TimerListener.cs>
Please have a look. |
20,689,302 | I have a project that has a MainActivity which hosts a fragment that hosts two other fragments via a Viewpager. It looks fine on first start up, but when I rotate, the two fragments in the Viewpager are lost. I've tried changing getFragmentManager to getChildFragmentManager but I would then get a Illegal state exception: Can't retain fragements that are nested in other fragments.
**MainActivity.java:**
```
import android.app.ActionBar;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
public class MainActivity extends SlidingFragmentActivity {
@TargetApi(11)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.mainContentFrame, new WorkOutsContainerFrag())
.commit();
setBehindContentView(R.layout.menu);
ActionBar actionBar = getActionBar();
populate();
SlidingMenu menu = getSlidingMenu();
menu.setMode(SlidingMenu.LEFT);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindWidthRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setSlidingEnabled(false);
setSlidingActionBarEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void populate() {
ListView lv = (ListView) findViewById(R.id.listView1);
String[] values = new String[] { "Workouts", "Information", "Ladders"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
lv.setAdapter(adapter);
}
```
}
**WorkoutsContainerFrag.java:**
```
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.astuetz.PagerSlidingTabStrip;
public class WorkOutsContainerFrag extends Fragment {
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private WorkoutsPagerAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.workoutscontainer, container, false);
setRetainInstance(true);
tabs = (PagerSlidingTabStrip) view.findViewById(R.id.workoutstabs);
pager = (ViewPager) view.findViewById(R.id.workoutspager);
adapter = new WorkoutsPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
return view;
```
}
```
private GymWorkoutsFragment gymWorkoutsFragment;
private OCWorkoutsFragment ocWorkoutsFragment;
public class WorkoutsPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Gym Workouts", "OC Workouts"};
public WorkoutsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
@Override
public int getCount() {
return TITLES.length;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
gymWorkoutsFragment = new GymWorkoutsFragment();
return (Fragment)gymWorkoutsFragment;
case 1:
ocWorkoutsFragment = new OCWorkoutsFragment();
return (Fragment)ocWorkoutsFragment;
}
return null;
}
```
}
} | 2013/12/19 | [
"https://Stackoverflow.com/questions/20689302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3120224/"
] | Probably, if u wish to retain the fragment instance, you can try using this,
```
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setOffscreenPageLimit(2); // No of fragments to be preserved
```
Cheers!! | Search for the original fragment first before you create a new one. You can search by the id that you gave the fragment or by a tag. Here is an example.
```
WorkOutsContainerFrag fragment = (WorkOutsContainerFrag) getFragmentManager().findFragmentById(R.id.workout_frag_id);
if(fragment == null) {
fragment = new WorkOutsContainerFrag();
}
getSupportFragmentManager().beginTransactoin().replace(R.id.mainContentFrame,fragment).commit();
``` |
20,689,302 | I have a project that has a MainActivity which hosts a fragment that hosts two other fragments via a Viewpager. It looks fine on first start up, but when I rotate, the two fragments in the Viewpager are lost. I've tried changing getFragmentManager to getChildFragmentManager but I would then get a Illegal state exception: Can't retain fragements that are nested in other fragments.
**MainActivity.java:**
```
import android.app.ActionBar;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
public class MainActivity extends SlidingFragmentActivity {
@TargetApi(11)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.mainContentFrame, new WorkOutsContainerFrag())
.commit();
setBehindContentView(R.layout.menu);
ActionBar actionBar = getActionBar();
populate();
SlidingMenu menu = getSlidingMenu();
menu.setMode(SlidingMenu.LEFT);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindWidthRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setSlidingEnabled(false);
setSlidingActionBarEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void populate() {
ListView lv = (ListView) findViewById(R.id.listView1);
String[] values = new String[] { "Workouts", "Information", "Ladders"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
lv.setAdapter(adapter);
}
```
}
**WorkoutsContainerFrag.java:**
```
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.astuetz.PagerSlidingTabStrip;
public class WorkOutsContainerFrag extends Fragment {
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private WorkoutsPagerAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.workoutscontainer, container, false);
setRetainInstance(true);
tabs = (PagerSlidingTabStrip) view.findViewById(R.id.workoutstabs);
pager = (ViewPager) view.findViewById(R.id.workoutspager);
adapter = new WorkoutsPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
return view;
```
}
```
private GymWorkoutsFragment gymWorkoutsFragment;
private OCWorkoutsFragment ocWorkoutsFragment;
public class WorkoutsPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Gym Workouts", "OC Workouts"};
public WorkoutsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
@Override
public int getCount() {
return TITLES.length;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
gymWorkoutsFragment = new GymWorkoutsFragment();
return (Fragment)gymWorkoutsFragment;
case 1:
ocWorkoutsFragment = new OCWorkoutsFragment();
return (Fragment)ocWorkoutsFragment;
}
return null;
}
```
}
} | 2013/12/19 | [
"https://Stackoverflow.com/questions/20689302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3120224/"
] | The answer is actually super simple, it was to replace FragmentPagerAdapter with FragmentStatePagerAdapter | Search for the original fragment first before you create a new one. You can search by the id that you gave the fragment or by a tag. Here is an example.
```
WorkOutsContainerFrag fragment = (WorkOutsContainerFrag) getFragmentManager().findFragmentById(R.id.workout_frag_id);
if(fragment == null) {
fragment = new WorkOutsContainerFrag();
}
getSupportFragmentManager().beginTransactoin().replace(R.id.mainContentFrame,fragment).commit();
``` |
20,689,302 | I have a project that has a MainActivity which hosts a fragment that hosts two other fragments via a Viewpager. It looks fine on first start up, but when I rotate, the two fragments in the Viewpager are lost. I've tried changing getFragmentManager to getChildFragmentManager but I would then get a Illegal state exception: Can't retain fragements that are nested in other fragments.
**MainActivity.java:**
```
import android.app.ActionBar;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
public class MainActivity extends SlidingFragmentActivity {
@TargetApi(11)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.mainContentFrame, new WorkOutsContainerFrag())
.commit();
setBehindContentView(R.layout.menu);
ActionBar actionBar = getActionBar();
populate();
SlidingMenu menu = getSlidingMenu();
menu.setMode(SlidingMenu.LEFT);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindWidthRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setSlidingEnabled(false);
setSlidingActionBarEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void populate() {
ListView lv = (ListView) findViewById(R.id.listView1);
String[] values = new String[] { "Workouts", "Information", "Ladders"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
lv.setAdapter(adapter);
}
```
}
**WorkoutsContainerFrag.java:**
```
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.astuetz.PagerSlidingTabStrip;
public class WorkOutsContainerFrag extends Fragment {
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private WorkoutsPagerAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.workoutscontainer, container, false);
setRetainInstance(true);
tabs = (PagerSlidingTabStrip) view.findViewById(R.id.workoutstabs);
pager = (ViewPager) view.findViewById(R.id.workoutspager);
adapter = new WorkoutsPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
return view;
```
}
```
private GymWorkoutsFragment gymWorkoutsFragment;
private OCWorkoutsFragment ocWorkoutsFragment;
public class WorkoutsPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Gym Workouts", "OC Workouts"};
public WorkoutsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
@Override
public int getCount() {
return TITLES.length;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
gymWorkoutsFragment = new GymWorkoutsFragment();
return (Fragment)gymWorkoutsFragment;
case 1:
ocWorkoutsFragment = new OCWorkoutsFragment();
return (Fragment)ocWorkoutsFragment;
}
return null;
}
```
}
} | 2013/12/19 | [
"https://Stackoverflow.com/questions/20689302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3120224/"
] | The answer is actually super simple, it was to replace FragmentPagerAdapter with FragmentStatePagerAdapter | Probably, if u wish to retain the fragment instance, you can try using this,
```
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setOffscreenPageLimit(2); // No of fragments to be preserved
```
Cheers!! |
97,913 | I have views of ubercart products which are displayed in a table by standard drupal view standards.
How can i theme individual product fields ?
views-view-field.tpl is having the complete product listed inside $output variable..
I want to solve this in a template file where all fields are available individually .. | 2013/12/20 | [
"https://drupal.stackexchange.com/questions/97913",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/20004/"
] | As far as your question title says "Execution Order", rules have weight which you can set in the settings tab which you will find on rule manage page.
>
> Order rules that react on the same event. Rules with a higher weight
> are evaluated after rules with less weight.
>
>
>
As far as your query concern, it seems you need to pick up he right condition while setting up those three rules,you can also use php in the condition if your condition is quite specific.The rules automatically execute their actions based on if condition get satisfied. | As a variation to the prior answer, you could also try to combine the three rules in a single rule, by using the [Conditional Rules](https://www.drupal.org/project/rules_conditional) module, which allows to include the equivalent of a Rules Condition within a Rules Action. Have a look at part 2 of the answer to "[How to correct my rule to prevent duplicate taxonomy terms to be created?](https://drupal.stackexchange.com/questions/222120/how-to-correct-my-rule-to-prevent-duplicate-taxonomy-terms-to-be-created/222133#222133)" for a pretty advanced Rules example that uses this technique.
By using this technique, you can implement pretty complicated Rules Logic in a ***single*** rule, which possibly prevents the need for multiple rules. Moreover, it makes it possible to group related business logic in a single rule (instead of having to look at 3 different places in the admin UI to get the big picture of those rules).
Be aware however that by using this alternative solution, you better also pay attention to the correct usage of ***AND*** and ***OR*** constructs inside such custom rules (to prevent Rules from not behaving as you would expect). If you're struggling with these constructs, you may want to look at the answer to "[Which is the difference of combining rules with AND or just leave them follow one each other?](https://drupal.stackexchange.com/questions/228117/which-is-the-difference-of-combining-rules-with-and-or-just-leave-them-follow-on/228125#228125)"
PS: I'm assuming this question is about D7 ... |
58,711 | I'm trying to do a logo for myself, just to put it in my apps.
I just drawn (by hand) my Surname-Name, flipped the name vertically, added a background as you can see.
I know that usually there is a "theory" about colors and shapes. I have some doubts: for example, what changes into the watcher's eye if the text would be white? Is it too complex to be defined a "logo"? What can I do to make it more interesting for the eye?
[](https://i.stack.imgur.com/izUhF.png) | 2015/08/26 | [
"https://graphicdesign.stackexchange.com/questions/58711",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/-1/"
] | Two **very** basic benchmarks for a logo:
* If it has text, can you read it?
* If it made of shapes, can you draw
it from memory?
The problem with your logo really is that it has no unique shape that makes it distinguishable other than handwritten text, which we can't read. So you you are killing off your own benefit. And the color boxes (which are from the first kuler page, really) do not convey any message on their own. So your logo is left with saying *nothing*. Which is the opposite of what you want to achieve. | Few questions you can think over:
* The logo is using brush or handmade?
* Text used inside is signature of anyone?
* Is this readable?
The Logo:
* Logo is represents company brands or corporate identities in market.
* Logo should be simple and creative.
* Easy to read, relevant text can be added.
Solution you can go for:
* Change the text of Logo as it is gangling and ungraceful.
* Why you used the dark color background? Use bright colors, the dark color varnishes the glow of upper text.
Hope this helps to improve your Logo. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.