qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
15,350 | <p>After watching every possible YouTube video on the subject and reading any source available, and although I'm a PhD and quite computer savvy, I still can't make my Anet A6 (no probe) behave in terms of Z offset. I upgraded to silicone bed buffers instead of the stock springs; now my bed is ~5 mm raised, and I don't know how to proceed. Some observations:</p>
<ul>
<li><p><strong>G28</strong> makes the nozzle go to the center of the bed. Display says X 111 and Y 111. Is it preferable to set the home to the bottom-left corner, or is the center just fine?</p>
</li>
<li><p><strong>G28</strong> makes the nozzle squish the bed ~5 mm deep.</p>
</li>
<li><p>I've tried the <strong>G92</strong> approach and the <strong>M428</strong> approach. I can't quite understand what's the difference between them. Can anyone explain why sometimes the former is used and sometimes the latter?</p>
</li>
<li><p>I had high hopes for <strong>M428</strong>. What could be simpler? You physically guide the nozzle to where you want it to be, send the command, and that's your new 0,0,0. But I guess not. Since my "home" is at 111,111 and apparently M428 can only be used at a maximum of 20 mm from 0, I get a "too far from reference" error message.</p>
</li>
<li><p>At any rate, both approaches (also <strong>M206</strong>) haven't helped. When I <strong>G28</strong>, the nozzle still squishes the bed. The display either says Z 5 or Z -5 or whatever I've played with, but the nozzle still squishes the poor bed.</p>
</li>
<li><p>In my LCD menu (Marlin 1.1.9), I don't have Control -> Motion -> Z offset. Since many videos recommend using this, this is quite sad. Can anyone tell me why this option is absent?</p>
</li>
<li><p>On a very conceptual level, I can't quite understand why in all the video guides the bed screws are completely ignored when discussing Z offset. One guy showed how he's correcting his Z offset 0.3 mm using G-code. But he could've easily done it by adjusting his screws... They all say "Z offset means the distance between your nozzle and bed, and here is how to adjust it". Now comes G-code, or LCD menu, etc. But why is everyone forgetting that you can adjust the distance between your bed and nozzle using the screws?! I can't seem to wrap my head around this. In my case, of course, I can't use the screws -- they've reached their limit, so I need to add extra using G-code. But nobody seems to really explain this nicely...</p>
</li>
</ul>
<p><strong>Summary:</strong> I urgently need a walkthrough for 6-year-olds. Make that 4-year-olds.</p>
| [
{
"answer_id": 15353,
"author": "octopus8",
"author_id": 26170,
"author_profile": "https://3dprinting.stackexchange.com/users/26170",
"pm_score": 0,
"selected": false,
"text": "<p>Setting any offset will move the whole print ("effectively shifts the coordinate space") - so you can set up for printing above or below bed, or shifting several cm to the right, for example - and then your print may not actually fit the printing space. For example: my frame is blocking X moves at the top, I can set the 20 mm X offset to avoid accident when printing high (so shift the print). Or when setting the new print on top of another print, thus shifting the position, etc. If you call <code>M428</code> in any position, then current position will become the new offset. Current offset settings is reported by <code>M503</code> (or <code>M206</code> without parameters).</p>\n<p>Also <code>G92</code> is used as ad-hoc operation when relative positioning is used. It makes sense for extruder movements, but is not used for moving the printing head in practice. I would say that any such calls for X,Y,Z sound like some hacking, and you should know exactly what you are doing for tricking printer's logic this way. I would avoid this at all.</p>\n<p>Normally (0,0,0) for cartesian printers is nearest-bottom-left point of the bed. If properly zero the printer is what you are trying to achieve, then you should:</p>\n<ul>\n<li>zero any X,Y,Z offsets: <code>M206 X0 Y0 Z0</code> (unless some is justified like in the frame example)</li>\n<li>save this setting for future: <code>M500</code></li>\n<li>home the printer - it zero the position, and then automiaticall backoff to some "safe distance" (programmed in firmware)</li>\n<li>use LCD to move carriage back to zero: at least for the Z axis</li>\n<li>regulate bed screws to fit the zero position of printing head</li>\n</ul>\n<p>There are settings in <a href=\"https://marlinfw.org/docs/configuration/configuration.html#homing\" rel=\"nofollow noreferrer\">Marlin's file Configuration_adv.h</a>:</p>\n<ul>\n<li><p>Marlin 1.1:</p>\n<pre><code>#define X_HOME_BUMP_MM 5\n#define Y_HOME_BUMP_MM 5\n#define Z_HOME_BUMP_MM 2\n</code></pre>\n</li>\n<li><p>Marlin 2.x:</p>\n<pre><code>#define HOMING_BUMP_MM { 5, 5, 2 } // (mm) Backoff from endstops after first bump\n</code></pre>\n</li>\n</ul>\n<p>They do not change the zero (do not set offset), but force the carriage to move away from zero during homing operation and (Marlin 1.1) after homing, becuse usually it is convenient. Marlin 2.x offers separate parameter for final backoff:</p>\n<pre><code>//#define HOMING_BACKOFF_MM { 2, 2, 2 }\n</code></pre>\n<p>If you would like to center the head after homing, I would suggest to use these settings.</p>\n"
},
{
"answer_id": 15354,
"author": "0scar",
"author_id": 5740,
"author_profile": "https://3dprinting.stackexchange.com/users/5740",
"pm_score": 3,
"selected": true,
"text": "<p>So the new silicone buffers raised the bed by 5 mm? When this happens, you should raise the endstop also with 5 mm. Else the printer will go down to the Z endstop that is effectively 5 mm below the level of the bed. I guess the buffers cannot be compressed by 5 mm, so you need to move the endstop up to the level your buffer compression is in reach of.</p>\n<p>No software offset will work (for your current setup: homing on the bed surface does not work as the switch need to be triggered prior to having any offset in play) other than a hardware change or compression of the buffers of 5 mm. It would only be possible to use a software offset when the nozzle homes off the bed surface (next to the bed). The only thing you would have had to do is add in your start G-code:</p>\n<pre><code>G0 Z5 ; Move the head to 5 mm \nG92 Z0 ; Call this Z = 0 \n</code></pre>\n<p>If <code>#define Z_SAFE_HOMING</code> is enabled, you should comment the line in the configuration file to make it home Z at the homed X, Y position.</p>\n<p>I will not go into all G-codes, details are read on the <a href=\"https://reprap.org/wiki/G-code\" rel=\"nofollow noreferrer\">G-codes Wiki pages</a> and <a href=\"https://marlinfw.org/docs/gcode/\" rel=\"nofollow noreferrer\">Marlin firmware G-codes</a>, these won't be able to help you out unless you fix the homing on the bed surface. Currently, you need to do a hardware fix, your endstop is below the surface level of the bed. Alternative is to remove homing Z above the bed surface and redefine the Z offset. A hardware fix is a better solution, and if you manage to print a fancy Z endstop holder and counterpart with a screw you will be able to level the bed more easily.</p>\n<p>E.g. <a href=\"https://marlinfw.org/docs/gcode/M428.html\" rel=\"nofollow noreferrer\"><code>M428</code></a> can set an offset, yes, but, it needs a reference; that reference is the homing reference or the current position. The current position of a printer that is just turn on is meaningless, it can be everywhere in the print volume. So you need to trigger the endstops first, that is not possible when it is not reachable (without compressing the bed).</p>\n"
}
] | 2021/01/17 | [
"https://3dprinting.stackexchange.com/questions/15350",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/26360/"
] | After watching every possible YouTube video on the subject and reading any source available, and although I'm a PhD and quite computer savvy, I still can't make my Anet A6 (no probe) behave in terms of Z offset. I upgraded to silicone bed buffers instead of the stock springs; now my bed is ~5 mm raised, and I don't know how to proceed. Some observations:
* **G28** makes the nozzle go to the center of the bed. Display says X 111 and Y 111. Is it preferable to set the home to the bottom-left corner, or is the center just fine?
* **G28** makes the nozzle squish the bed ~5 mm deep.
* I've tried the **G92** approach and the **M428** approach. I can't quite understand what's the difference between them. Can anyone explain why sometimes the former is used and sometimes the latter?
* I had high hopes for **M428**. What could be simpler? You physically guide the nozzle to where you want it to be, send the command, and that's your new 0,0,0. But I guess not. Since my "home" is at 111,111 and apparently M428 can only be used at a maximum of 20 mm from 0, I get a "too far from reference" error message.
* At any rate, both approaches (also **M206**) haven't helped. When I **G28**, the nozzle still squishes the bed. The display either says Z 5 or Z -5 or whatever I've played with, but the nozzle still squishes the poor bed.
* In my LCD menu (Marlin 1.1.9), I don't have Control -> Motion -> Z offset. Since many videos recommend using this, this is quite sad. Can anyone tell me why this option is absent?
* On a very conceptual level, I can't quite understand why in all the video guides the bed screws are completely ignored when discussing Z offset. One guy showed how he's correcting his Z offset 0.3 mm using G-code. But he could've easily done it by adjusting his screws... They all say "Z offset means the distance between your nozzle and bed, and here is how to adjust it". Now comes G-code, or LCD menu, etc. But why is everyone forgetting that you can adjust the distance between your bed and nozzle using the screws?! I can't seem to wrap my head around this. In my case, of course, I can't use the screws -- they've reached their limit, so I need to add extra using G-code. But nobody seems to really explain this nicely...
**Summary:** I urgently need a walkthrough for 6-year-olds. Make that 4-year-olds. | So the new silicone buffers raised the bed by 5 mm? When this happens, you should raise the endstop also with 5 mm. Else the printer will go down to the Z endstop that is effectively 5 mm below the level of the bed. I guess the buffers cannot be compressed by 5 mm, so you need to move the endstop up to the level your buffer compression is in reach of.
No software offset will work (for your current setup: homing on the bed surface does not work as the switch need to be triggered prior to having any offset in play) other than a hardware change or compression of the buffers of 5 mm. It would only be possible to use a software offset when the nozzle homes off the bed surface (next to the bed). The only thing you would have had to do is add in your start G-code:
```
G0 Z5 ; Move the head to 5 mm
G92 Z0 ; Call this Z = 0
```
If `#define Z_SAFE_HOMING` is enabled, you should comment the line in the configuration file to make it home Z at the homed X, Y position.
I will not go into all G-codes, details are read on the [G-codes Wiki pages](https://reprap.org/wiki/G-code) and [Marlin firmware G-codes](https://marlinfw.org/docs/gcode/), these won't be able to help you out unless you fix the homing on the bed surface. Currently, you need to do a hardware fix, your endstop is below the surface level of the bed. Alternative is to remove homing Z above the bed surface and redefine the Z offset. A hardware fix is a better solution, and if you manage to print a fancy Z endstop holder and counterpart with a screw you will be able to level the bed more easily.
E.g. [`M428`](https://marlinfw.org/docs/gcode/M428.html) can set an offset, yes, but, it needs a reference; that reference is the homing reference or the current position. The current position of a printer that is just turn on is meaningless, it can be everywhere in the print volume. So you need to trigger the endstops first, that is not possible when it is not reachable (without compressing the bed). |
15,356 | <p>I just bought an Ender 3 Max and from the start I knew something was wrong. I figured out the problem: it is with the first few millimeters of the Z axis movement.</p>
<p>I turn on my 3D printer, go to prepare, move axis, move Z, move 1 mm.</p>
<p>Then I tell the printer to move up 1 mm. But in reality it only moves up 0.3 mm. I then tell it to move up another millimeter, except it only moves up 0.4 mm. When I tell it to move up another millimeter, and it moves up only 0.45 mm. I then tell it to move up another millimeter and it moves up 0.6 mm. And then anytime after that when I say to move up a millimeter it actually moves up a millimeter. Below is a little chart to help you understand what is happening.</p>
<pre><code>Set height | Actual height
--------------------------
0 | 0
1 | 0.3
2 | 0.7
3 | 1.15
4 | 1.75
5 | 2.75
6 | 3.75
7 | 4.75
8 | 5.75
9 | 6.75
10 | 7.75
</code></pre>
<p>As a result of this error on my printer, the test prints I have run so far are splayed out and uneven at the bottom, making my prints warped at the first 5 mm and several millimeters shorter than they should be.</p>
| [
{
"answer_id": 15360,
"author": "0scar",
"author_id": 5740,
"author_profile": "https://3dprinting.stackexchange.com/users/5740",
"pm_score": 2,
"selected": false,
"text": "<p>Your printer probably has an issue with binding in the lower region (binding means extra friction possibly causing the Z stepper to skip steps). Disconnect the lead screw an manually move the X gantry up and down. If there is binding, you need to find why this happens, with the unfortunate design of the Ender, many people experience issues when the rollers on both posts are not correctly installed.</p>\n"
},
{
"answer_id": 15366,
"author": "Jugglingboss",
"author_id": 26364,
"author_profile": "https://3dprinting.stackexchange.com/users/26364",
"pm_score": 0,
"selected": false,
"text": "<p>The problem turned out to be that the two extruded pieces of aluminium on the z axis were too close together - I tightened the screws too tight. This made the gap between the z axis bars smaller than desired and the z movement only lifted one side of the bar in the beginning.</p>\n<p>After I loosed those screws holding the gantry crane on, everything works now!</p>\n"
}
] | 2021/01/18 | [
"https://3dprinting.stackexchange.com/questions/15356",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/26364/"
] | I just bought an Ender 3 Max and from the start I knew something was wrong. I figured out the problem: it is with the first few millimeters of the Z axis movement.
I turn on my 3D printer, go to prepare, move axis, move Z, move 1 mm.
Then I tell the printer to move up 1 mm. But in reality it only moves up 0.3 mm. I then tell it to move up another millimeter, except it only moves up 0.4 mm. When I tell it to move up another millimeter, and it moves up only 0.45 mm. I then tell it to move up another millimeter and it moves up 0.6 mm. And then anytime after that when I say to move up a millimeter it actually moves up a millimeter. Below is a little chart to help you understand what is happening.
```
Set height | Actual height
--------------------------
0 | 0
1 | 0.3
2 | 0.7
3 | 1.15
4 | 1.75
5 | 2.75
6 | 3.75
7 | 4.75
8 | 5.75
9 | 6.75
10 | 7.75
```
As a result of this error on my printer, the test prints I have run so far are splayed out and uneven at the bottom, making my prints warped at the first 5 mm and several millimeters shorter than they should be. | Your printer probably has an issue with binding in the lower region (binding means extra friction possibly causing the Z stepper to skip steps). Disconnect the lead screw an manually move the X gantry up and down. If there is binding, you need to find why this happens, with the unfortunate design of the Ender, many people experience issues when the rollers on both posts are not correctly installed. |
15,421 | <p>I was printing an object and it started to drag so I stopped it.</p>
<p>Went to move the Z-axis up so I could clear the bed and Z-axis would not budge.
I switched the printer off and manually turned the motors to get the Z up.
Cleared the bed, switched on and homed the printer. When it came to home the Z, BLTouch deployed and then nothing. Motors will not turn.</p>
<p>Things I tried:</p>
<ul>
<li>Recompiled the firmware (Marlin 2.0.x)</li>
<li>Different motors - Motors were free from the printer, just resting on a desk so I know it's not binding or anything.</li>
<li>Swapped stepper driver with a known working one.</li>
</ul>
<p>Info about the printer:</p>
<ul>
<li>CR10s</li>
<li>SKR1.4 Turbo board</li>
<li>TMC2208 Steppers</li>
<li>BLTouch</li>
<li>Octopi to control the printer.</li>
</ul>
<p>Output of <code>M122</code> for the Z:</p>
<pre><code>Recv: Z
Recv: Address
Recv: Enabled false
Recv: Set current 1000
Recv: RMS current 994
Recv: MAX current 1402
Recv: Run current 17/31
Recv: Hold current 8/31
Recv: CS actual 8/31
Recv: PWM scale
Recv: vsense 0=.325
Recv: stealthChop true
Recv: msteps 16
Recv: tstep max
Recv: PWM thresh. 0
Recv: [mm/s] -
Recv: OT prewarn false
Recv: triggered
Recv: OTP false
Recv: pwm scale sum 10
Recv: pwm scale auto 0
Recv: pwm offset auto 36
Recv: pwm grad auto 14
Recv: off time 4
Recv: blank time 24
Recv: hysteresis
Recv: -end 2
Recv: -start 1
Recv: Stallguard thrs
Recv: uStep count 40
Recv: DRVSTATUS Z
Recv: sg_result
Recv: stst
Recv: olb
Recv: ola
Recv: s2gb
Recv: s2ga
Recv: otpw
Recv: to
Recv: 157C
Recv: 150C
Recv: 143C
Recv: 120C
Recv: s2vsa
Recv: s2vsb
Recv: Driver registers:
Recv: Z 0xC0:08:00:00
Recv:
Recv:
Recv: Testing Z connection... OK
</code></pre>
| [
{
"answer_id": 15422,
"author": "dandavis",
"author_id": 10437,
"author_profile": "https://3dprinting.stackexchange.com/users/10437",
"pm_score": 3,
"selected": true,
"text": "<p>extruder clicking means you're getting backed up, grinding.</p>\n<ul>\n<li>Make the hotend hotter so you can melt filament 3X faster than expected; most materials have quite a range; aim high.</li>\n<li>Slow down the cooling fan; a lot of them can cool the hotend.</li>\n<li>You have a silicone boot on the nozzle? that will help some.</li>\n<li>Use a larger diameter nozzle to reduce backpressure and allow thicker layers.</li>\n<li>Try cranking the feed rate</li>\n</ul>\n<p>Lastly, consider that you simply might not get acceptable results pushing speed THAT much.</p>\n"
},
{
"answer_id": 15423,
"author": "octopus8",
"author_id": 26170,
"author_profile": "https://3dprinting.stackexchange.com/users/26170",
"pm_score": 0,
"selected": false,
"text": "<p>Changing "Flow" will affect whole print. So even if it helped for the middle part (I doubt), the next it would ruin the print on sides by overextrusion. However: <strong>if sides are printed ok, then why the middle couldn't?</strong> Because walls are printed slower? Indeed, the under-extrusion may quickly rise along with speed because of plastic deformation between extruder gears under pressure and slight slipping, which actually increases with speed. The video "<a href=\"https://youtu.be/0xRtypDjNvI?t=301\" rel=\"nofollow noreferrer\">How fast can your hotend print?</a>" presents experiment on this phenomena and its outcomes.</p>\n<p>Then we go into master question: <strong>300% of what?</strong> Turning the speed knob during print will override all considerations that slicer took into account during calculations - and defintely override <a href=\"https://help.prusa3d.com/en/article/max-volumetric-speed_127176\" rel=\"nofollow noreferrer\">Max volumetric speed</a>, which is key factor to limit <strong>pressure in the nozzle</strong> (vide clicking noise).</p>\n<p>The real limit seems to be this middle part of print, and outer part is just cosmetics (probably calculated to print slower because of quality). So if you ensure, that printing these middle surfaces is <strong>planned (in G-Code) with similar speed</strong> as walls, then (at least in theory) you may be able to increase overall speed, playing e.g. only with temperature. (I actually mean the speed of extrusion, so this may not be simple as just setting equal speed for perimeters and infill, but this does not change the conclusion below.)</p>\n<p>So I say <strong>all it starts in the slicer</strong> software: increase speed there and re-caclulate. This will ensure to not exceed key limitations. Then you may manipulate maximal values in slicer for further experimentation.</p>\n"
},
{
"answer_id": 15448,
"author": "FarO",
"author_id": 2338,
"author_profile": "https://3dprinting.stackexchange.com/users/2338",
"pm_score": 0,
"selected": false,
"text": "<p>Provided you find a way to increase the extruder limits, as replied by @dandavis , you will still get underextrusion in the infill if the infill is printed faster than walls.</p>\n<p>You need to enable some option in the slicer to label each part of the print, so that you get a comment in the gcode to mark walls, infill, and so on.</p>\n<p>Then you need to process the generated gcode, so that when you find the label "infill" you replace it with a flow multiplier to increase flow. How much has to be tuned by try and fail.</p>\n<p>You also need to replace every remaining label (walls, ...) with a 100% flowrate setting to bring back the setting to the standard value, obviously.</p>\n"
}
] | 2021/01/24 | [
"https://3dprinting.stackexchange.com/questions/15421",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/23645/"
] | I was printing an object and it started to drag so I stopped it.
Went to move the Z-axis up so I could clear the bed and Z-axis would not budge.
I switched the printer off and manually turned the motors to get the Z up.
Cleared the bed, switched on and homed the printer. When it came to home the Z, BLTouch deployed and then nothing. Motors will not turn.
Things I tried:
* Recompiled the firmware (Marlin 2.0.x)
* Different motors - Motors were free from the printer, just resting on a desk so I know it's not binding or anything.
* Swapped stepper driver with a known working one.
Info about the printer:
* CR10s
* SKR1.4 Turbo board
* TMC2208 Steppers
* BLTouch
* Octopi to control the printer.
Output of `M122` for the Z:
```
Recv: Z
Recv: Address
Recv: Enabled false
Recv: Set current 1000
Recv: RMS current 994
Recv: MAX current 1402
Recv: Run current 17/31
Recv: Hold current 8/31
Recv: CS actual 8/31
Recv: PWM scale
Recv: vsense 0=.325
Recv: stealthChop true
Recv: msteps 16
Recv: tstep max
Recv: PWM thresh. 0
Recv: [mm/s] -
Recv: OT prewarn false
Recv: triggered
Recv: OTP false
Recv: pwm scale sum 10
Recv: pwm scale auto 0
Recv: pwm offset auto 36
Recv: pwm grad auto 14
Recv: off time 4
Recv: blank time 24
Recv: hysteresis
Recv: -end 2
Recv: -start 1
Recv: Stallguard thrs
Recv: uStep count 40
Recv: DRVSTATUS Z
Recv: sg_result
Recv: stst
Recv: olb
Recv: ola
Recv: s2gb
Recv: s2ga
Recv: otpw
Recv: to
Recv: 157C
Recv: 150C
Recv: 143C
Recv: 120C
Recv: s2vsa
Recv: s2vsb
Recv: Driver registers:
Recv: Z 0xC0:08:00:00
Recv:
Recv:
Recv: Testing Z connection... OK
``` | extruder clicking means you're getting backed up, grinding.
* Make the hotend hotter so you can melt filament 3X faster than expected; most materials have quite a range; aim high.
* Slow down the cooling fan; a lot of them can cool the hotend.
* You have a silicone boot on the nozzle? that will help some.
* Use a larger diameter nozzle to reduce backpressure and allow thicker layers.
* Try cranking the feed rate
Lastly, consider that you simply might not get acceptable results pushing speed THAT much. |
15,456 | <p>I have an Ender 5 with an auto bed leveling sensor (TRU-LEV 600).</p>
<p>It is working fine, however, as the sensor probes the bed, the nozzle and the bed cool down and are not staying heated as it is getting the points, even though they were heated up in the first place.</p>
<p>How do I stop the bed and hotend from cooling down while the bed is being probed?</p>
<p>Here is my start G-code:</p>
<pre><code>M75; Start Print Timer and Engage Fil Sensor if USB Printing
G92 E0; Reset Extruder distance to 0
G1 E-2; Retracts filament to prevent blobs during probing
M84 E; Disable E Motor for probe accuracy on direct drive systems
G28; home all axes
G28 Z; home Z to get more accurate Z position
G29; TRULEV mesh generation
G4 S10; wait for heaters to recover
M117 Purge extruder
G92 E0; reset extruder
G1 X0.1 Y20 Z0.3 F5000.0; move to start-line position
G1 Z1.0 F3000; move z up little
G1 X0.1 Y100.0 Z0.3 F750.0 E15; draw 1st line
G1 X0.4 Y100.0 Z0.3 F5000.0; move to side a little
G1 X0.4 Y20 Z0.3 F750.0 E30; draw 2nd line
G92 E0; reset extruder
G1 Z1.0 F3000; move z up little
M117 Printing.....
</code></pre>
| [
{
"answer_id": 15460,
"author": "octopus8",
"author_id": 26170,
"author_profile": "https://3dprinting.stackexchange.com/users/26170",
"pm_score": 1,
"selected": false,
"text": "<p>For Marlin firmware, you should <strong>check the setting <code>PROBING_HEATERS_OFF</code></strong> in <em>Configuration.h</em> file:</p>\n<pre><code>//#define PROBING_HEATERS_OFF // Turn heaters off when probing\n#if ENABLED(PROBING_HEATERS_OFF)\n //#define WAIT_FOR_BED_HEATER // Wait for bed to heat back up between probes (to improve accuracy)\n#endif\n//#define PROBING_FANS_OFF // Turn fans off when probing\n//#define PROBING_STEPPERS_OFF // Turn steppers off (unless needed to hold position) when probing\n//#define DELAY_BEFORE_PROBING 200 // (ms) To prevent vibrations from triggering piezo sensors\n</code></pre>\n<p>It is probably enabled in your case. You may want to switch this off and reinstall firmware to maintain constant heating during probing.</p>\n<p>However, you may want to take into account possibility of <strong>electrical or magnetic intereferences during probing</strong> from heaters and their circuits. Disabling them for a while may eliminate these influences and give more reliable measurements. Unless the bed ot hotend are unable to maintain stable temperature for a while and cool down too much (e.g. bed changing shape). So may want to experiment what works the best in your case, maybe including other settings listed in given section.</p>\n"
},
{
"answer_id": 18099,
"author": "Gerry",
"author_id": 31239,
"author_profile": "https://3dprinting.stackexchange.com/users/31239",
"pm_score": 0,
"selected": false,
"text": "<p>Eco mode under settings shuts off the bed after a 30 minutes ish maybe an hour. Either way it is probably the issue</p>\n"
}
] | 2021/01/26 | [
"https://3dprinting.stackexchange.com/questions/15456",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/25241/"
] | I have an Ender 5 with an auto bed leveling sensor (TRU-LEV 600).
It is working fine, however, as the sensor probes the bed, the nozzle and the bed cool down and are not staying heated as it is getting the points, even though they were heated up in the first place.
How do I stop the bed and hotend from cooling down while the bed is being probed?
Here is my start G-code:
```
M75; Start Print Timer and Engage Fil Sensor if USB Printing
G92 E0; Reset Extruder distance to 0
G1 E-2; Retracts filament to prevent blobs during probing
M84 E; Disable E Motor for probe accuracy on direct drive systems
G28; home all axes
G28 Z; home Z to get more accurate Z position
G29; TRULEV mesh generation
G4 S10; wait for heaters to recover
M117 Purge extruder
G92 E0; reset extruder
G1 X0.1 Y20 Z0.3 F5000.0; move to start-line position
G1 Z1.0 F3000; move z up little
G1 X0.1 Y100.0 Z0.3 F750.0 E15; draw 1st line
G1 X0.4 Y100.0 Z0.3 F5000.0; move to side a little
G1 X0.4 Y20 Z0.3 F750.0 E30; draw 2nd line
G92 E0; reset extruder
G1 Z1.0 F3000; move z up little
M117 Printing.....
``` | For Marlin firmware, you should **check the setting `PROBING_HEATERS_OFF`** in *Configuration.h* file:
```
//#define PROBING_HEATERS_OFF // Turn heaters off when probing
#if ENABLED(PROBING_HEATERS_OFF)
//#define WAIT_FOR_BED_HEATER // Wait for bed to heat back up between probes (to improve accuracy)
#endif
//#define PROBING_FANS_OFF // Turn fans off when probing
//#define PROBING_STEPPERS_OFF // Turn steppers off (unless needed to hold position) when probing
//#define DELAY_BEFORE_PROBING 200 // (ms) To prevent vibrations from triggering piezo sensors
```
It is probably enabled in your case. You may want to switch this off and reinstall firmware to maintain constant heating during probing.
However, you may want to take into account possibility of **electrical or magnetic intereferences during probing** from heaters and their circuits. Disabling them for a while may eliminate these influences and give more reliable measurements. Unless the bed ot hotend are unable to maintain stable temperature for a while and cool down too much (e.g. bed changing shape). So may want to experiment what works the best in your case, maybe including other settings listed in given section. |
15,816 | <p>I am building a 3D printer from scratch, the bed will only move on Z and the head will stay at the top of the printer and move X and Y.</p>
<p>How do I modify the Marlin firmware to have the bed lower as it prints instead of lift like most printers.</p>
| [
{
"answer_id": 15819,
"author": "Trish",
"author_id": 8884,
"author_profile": "https://3dprinting.stackexchange.com/users/8884",
"pm_score": 0,
"selected": false,
"text": "<p>To understand normal commands from a basic printer slicer, all movement commands in g-code are written to be away from the base layer as positive. Note that <em>technically</em> a "lower the bed" printer does violate Orthonormal coordinates unless you either swap X and Y while retaining 0 in the front-left corner or put 0 in the front-right corner, going left for +X (e.g. inverting that motor axis too) and back for -Y.</p>\n<h1>Hardware</h1>\n<p>To <em>invert</em> the movement direction of an axis without rewriting the firmware there are two main ways, from mos invasive to easiest:</p>\n<ul>\n<li>Mount the actuator "upside-down" as that flips the rotational normal vector.</li>\n<li>use a left-hand-threaded rod and nut. This does not flip rotation but how rotation affects the bed.</li>\n<li>alter the stepper cables by "crossing" one of the phases leads. The motor rotates reversed to its commands now.</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/miZU6.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/miZU6.jpg\" alt=\"enter image description here\" /></a></p>\n<h1>Firmware</h1>\n<p>In Marlin, you can also just flip the direction of the motor via <code>configuration.h</code> by altering the line from <code>false</code> to <code>true</code>:</p>\n<pre><code>#define INVERT_Z_DIR true\n</code></pre>\n"
},
{
"answer_id": 15820,
"author": "0scar",
"author_id": 5740,
"author_profile": "https://3dprinting.stackexchange.com/users/5740",
"pm_score": 2,
"selected": true,
"text": "<p>You can control in Marlin what the direction of the stepper motor is, e.g. my Hypercube CoreXY printer (which has a similar setup like you described) has the following set (in the Marlin <a href=\"https://github.com/MarlinFirmware/Marlin/blob/2.0.x/Marlin/Configuration.h\" rel=\"nofollow noreferrer\"><code>Configuration.h</code></a> file) to ensure the platform raises when it has to decrease height:</p>\n<pre><code>// Invert the stepper direction. Change (or reverse the motor connector) \n// if an axis goes the wrong way.\n#define INVERT_Z_DIR true\n</code></pre>\n<p>Furthermore, it matters where the Z endstop is located, e.g. using a bed probe sensor or a min Z endstop, you need to home towards a decreasing height (in the direction of your probe/endstop):</p>\n<pre><code>// Direction of endstops when homing; 1=MAX, -1=MIN\n#define Z_HOME_DIR -1\n</code></pre>\n<p>Don't forget to set a max Z height that falls within the printer volume, e.g.:</p>\n<pre><code>#define Z_MAX_POS 345\n</code></pre>\n<p>If the bed is heavy, you should also prevent the steppers to lose power when not being used, so at least set Z to <code>false</code>:</p>\n<pre><code>// Disables axis stepper immediately when it's not being used.\n// WARNING: When motors turn off there is a chance of losing position accuracy!\n#define DISABLE_Z false\n</code></pre>\n"
}
] | 2021/03/08 | [
"https://3dprinting.stackexchange.com/questions/15816",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/27229/"
] | I am building a 3D printer from scratch, the bed will only move on Z and the head will stay at the top of the printer and move X and Y.
How do I modify the Marlin firmware to have the bed lower as it prints instead of lift like most printers. | You can control in Marlin what the direction of the stepper motor is, e.g. my Hypercube CoreXY printer (which has a similar setup like you described) has the following set (in the Marlin [`Configuration.h`](https://github.com/MarlinFirmware/Marlin/blob/2.0.x/Marlin/Configuration.h) file) to ensure the platform raises when it has to decrease height:
```
// Invert the stepper direction. Change (or reverse the motor connector)
// if an axis goes the wrong way.
#define INVERT_Z_DIR true
```
Furthermore, it matters where the Z endstop is located, e.g. using a bed probe sensor or a min Z endstop, you need to home towards a decreasing height (in the direction of your probe/endstop):
```
// Direction of endstops when homing; 1=MAX, -1=MIN
#define Z_HOME_DIR -1
```
Don't forget to set a max Z height that falls within the printer volume, e.g.:
```
#define Z_MAX_POS 345
```
If the bed is heavy, you should also prevent the steppers to lose power when not being used, so at least set Z to `false`:
```
// Disables axis stepper immediately when it's not being used.
// WARNING: When motors turn off there is a chance of losing position accuracy!
#define DISABLE_Z false
``` |
15,954 | <p>I've updated my Ender 3 with V4.2.7 mainboard, BLTouch and 400XL kit (extends the capabilities of your Creality Ender 3 3D Printer to a 400 mm X, 400 mm Y and a 500 mm Z printing platform). Now I need to update the firmware. YouTube did not provide any help: i.e.: out of date, so cryptic as to be unusable. Marlin & Creality had overly complicated, for what I need, solutions. Trying these led only to frustrations! Any ideas?</p>
| [
{
"answer_id": 15956,
"author": "Joel Huebner",
"author_id": 15005,
"author_profile": "https://3dprinting.stackexchange.com/users/15005",
"pm_score": 1,
"selected": false,
"text": "<p>I've done the board upgrade on my Ender 3 Pro. As I've read the BLTouch is easy to install. I'd go over to the Creality <a href=\"https://forums.creality3dofficial.com/\" rel=\"nofollow noreferrer\">forum/help</a> site. You can open a support ticket. They actively have information on firmware in both "release" and "beta" threads. Look there & see if you can get your answers.</p>\n"
},
{
"answer_id": 15957,
"author": "Rykara",
"author_id": 16811,
"author_profile": "https://3dprinting.stackexchange.com/users/16811",
"pm_score": 2,
"selected": false,
"text": "<p>Without knowing exactly which Youtube videos you've looked at, I think where I would start is by downloading the latest Marlin Fimrware and configuration files for the Ender 3 with 4.2.7 board:</p>\n<p><a href=\"https://github.com/MarlinFirmware/Marlin/archive/2.0.x.zip\" rel=\"nofollow noreferrer\">Latest Release of Marlin Firmware on Github</a></p>\n<p><a href=\"https://github.com/MarlinFirmware/Configurations/tree/release-2.0.7.2/config/examples/Creality/Ender-3%20V2\" rel=\"nofollow noreferrer\">Configuration File Repository on Github</a></p>\n<p><a href=\"https://code.visualstudio.com/download\" rel=\"nofollow noreferrer\">Microsoft visual Studio</a></p>\n<p><a href=\"https://platformio.org/install/ide?install=vscode\" rel=\"nofollow noreferrer\">PlatormIO</a></p>\n<p>If I were doing your upgrade in your place, I would refer to <a href=\"https://www.youtube.com/watch?v=neS7lB7fCww&t=495s\" rel=\"nofollow noreferrer\">this video</a> for how to compile the firmware for the correct board. I've had to compile firmware for my Ender 3 a few times and I sometimes forget a step. This video is the best that I've found for showing/reminding me of each step.</p>\n<p>Essentially, what I think you need to do is compile your firmware as if it were a stock Ender 3 V2 using the settings files I linked above but then change your print area the configuration.h file to match the X400 x Y400 x Z500 print bed area.</p>\n<p>Look for the following:</p>\n<pre><code>// The size of the print bed\n#define X_BED_SIZE 200\n#define Y_BED_SIZE 200\n</code></pre>\n<p>Change to the following:</p>\n<pre><code>// The size of the print bed\n#define X_BED_SIZE 400\n#define Y_BED_SIZE 400\n</code></pre>\n<p>And then look for</p>\n<pre><code>#define Z_MAX_POS 200\n</code></pre>\n<p>and change to:</p>\n<pre><code>#define Z_MAX_POS 500\n</code></pre>\n<p>There are other changes you'd need to make to the settings file (refer to the video for those). I haven't done your particular upgrade on my machine, so I'm just guessing those extra couple of changes would work for you.</p>\n"
},
{
"answer_id": 15958,
"author": "LarryHills",
"author_id": 27509,
"author_profile": "https://3dprinting.stackexchange.com/users/27509",
"pm_score": 1,
"selected": false,
"text": "<p>Shortly after my post I found <a href=\"https://marlin.crc.id.au/\" rel=\"nofollow noreferrer\">this commercial Marlin site</a><sup> <em>1)</em></sup>. It offers firmware for Creality & other printers. You can order 'off the shelf' firmware or customize it yourself. Customizing is quite easy & self explanatory; 5 min. after submitting my requirements, I received a zip file, which I un-zipped & copied the needed file to my SD card. Then I inserted the SD card into my printer & started it. The printer recognized the new firmware & updated its self.</p>\n<hr />\n<p><sup><em>1)</em></sup> <em>This service is not free. Membership of \\$15.00/year, is required.</em></p>\n"
},
{
"answer_id": 16073,
"author": "0scar",
"author_id": 5740,
"author_profile": "https://3dprinting.stackexchange.com/users/5740",
"pm_score": 1,
"selected": false,
"text": "<p>A quick solution is obtaining a pre configured configuration file for this custom extended version of the Ender 3. While it should be very easy to find configurations for Ender 3 with or without BLTouch, the only difference this extension has is an updated printer volume specification. A ready made configuration is found <a href=\"https://github.com/teachingtechYT/Marlin/blob/Ender3-V2-BLtouch-extender/Marlin/Configuration.h\" rel=\"nofollow noreferrer\">here</a> (please note that it contains an errand for the maximum build height, change <code>#define Z_MAX_POS 250</code> to <code>#define Z_MAX_POS 500</code>.</p>\n<p>The basic changes are:</p>\n<pre><code>// The size of the print bed\n#define X_BED_SIZE 400\n#define Y_BED_SIZE 400\n\nZ_MAX_POS 500\n</code></pre>\n"
}
] | 2021/03/26 | [
"https://3dprinting.stackexchange.com/questions/15954",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/27509/"
] | I've updated my Ender 3 with V4.2.7 mainboard, BLTouch and 400XL kit (extends the capabilities of your Creality Ender 3 3D Printer to a 400 mm X, 400 mm Y and a 500 mm Z printing platform). Now I need to update the firmware. YouTube did not provide any help: i.e.: out of date, so cryptic as to be unusable. Marlin & Creality had overly complicated, for what I need, solutions. Trying these led only to frustrations! Any ideas? | Without knowing exactly which Youtube videos you've looked at, I think where I would start is by downloading the latest Marlin Fimrware and configuration files for the Ender 3 with 4.2.7 board:
[Latest Release of Marlin Firmware on Github](https://github.com/MarlinFirmware/Marlin/archive/2.0.x.zip)
[Configuration File Repository on Github](https://github.com/MarlinFirmware/Configurations/tree/release-2.0.7.2/config/examples/Creality/Ender-3%20V2)
[Microsoft visual Studio](https://code.visualstudio.com/download)
[PlatormIO](https://platformio.org/install/ide?install=vscode)
If I were doing your upgrade in your place, I would refer to [this video](https://www.youtube.com/watch?v=neS7lB7fCww&t=495s) for how to compile the firmware for the correct board. I've had to compile firmware for my Ender 3 a few times and I sometimes forget a step. This video is the best that I've found for showing/reminding me of each step.
Essentially, what I think you need to do is compile your firmware as if it were a stock Ender 3 V2 using the settings files I linked above but then change your print area the configuration.h file to match the X400 x Y400 x Z500 print bed area.
Look for the following:
```
// The size of the print bed
#define X_BED_SIZE 200
#define Y_BED_SIZE 200
```
Change to the following:
```
// The size of the print bed
#define X_BED_SIZE 400
#define Y_BED_SIZE 400
```
And then look for
```
#define Z_MAX_POS 200
```
and change to:
```
#define Z_MAX_POS 500
```
There are other changes you'd need to make to the settings file (refer to the video for those). I haven't done your particular upgrade on my machine, so I'm just guessing those extra couple of changes would work for you. |
16,113 | <p>My custom 3D printer prints everything inverted. I guess this is a homing problem as the motor moves in correct direction.</p>
<p>In Pronterface,</p>
<ul>
<li>if I press -Y — bed moves forward (towards the Y endstop)</li>
<li>if I press +Y — bed moves backward (away from Y endstop)</li>
<li>if I press -X — hotend moves left (towards the X endstop)</li>
<li>if I press +X — hotend moves right (away from the X endstop)</li>
</ul>
<p>on RAMPS 1.4:</p>
<ul>
<li>X endstop is connected on the 1st pin</li>
<li>Y endstop is connected on the 3rd pin</li>
<li>Z endstop is connected on the 5th pin</li>
</ul>
<p>(Pin 2, 4 & 6 are not used (are these for MAX_ENDSTOP ?))</p>
<p>Below is my Marlin config</p>
<pre><code>#define X_MIN_ENDSTOP_INVERTING true // Set to true to invert the logic of the endstop.
#define Y_MIN_ENDSTOP_INVERTING true // Set to true to invert the logic of the endstop.
#define Z_MIN_ENDSTOP_INVERTING true // Set to true to invert the logic of the endstop.
#define X_MAX_ENDSTOP_INVERTING false // Set to true to invert the logic of the endstop.
#define Y_MAX_ENDSTOP_INVERTING false // Set to true to invert the logic of the endstop.
#define Z_MAX_ENDSTOP_INVERTING false // Set to true to invert the logic of the endstop.
#define Z_MIN_PROBE_ENDSTOP_INVERTING false // Set to true to invert the logic of the probe.
#define X_HOME_DIR -1
#define Y_HOME_DIR -1
#define Z_HOME_DIR -1
#define INVERT_X_DIR false
#define INVERT_Y_DIR false
#define INVERT_Z_DIR false
</code></pre>
<p>I have attached 3 photographs.</p>
<ol>
<li>Shows the Home position of hotend. Y Motor on back and Y endstop at front.</li>
</ol>
<p><a href="https://i.stack.imgur.com/M4Gcr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M4Gcr.jpg" alt="Home position of hotend" /></a></p>
<ol start="2">
<li>Shows inverted print.</li>
</ol>
<p><a href="https://i.stack.imgur.com/9SRBZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9SRBZ.jpg" alt="inverted print" /></a></p>
<ol start="3">
<li>Pronterface screenshot (shows actual G-code file)</li>
</ol>
<p><a href="https://i.stack.imgur.com/4ru5r.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4ru5r.jpg" alt="Pronterface screenshot" /></a></p>
<p>I tried flipping the motor cables, but that inverts the motor direction
I also tried INVERT_Y_DIR true, but no luck.</p>
<p>Please help me. What am I doing wrong?</p>
| [
{
"answer_id": 16104,
"author": "Rykara",
"author_id": 16811,
"author_profile": "https://3dprinting.stackexchange.com/users/16811",
"pm_score": 3,
"selected": true,
"text": "<h1>Heater polarity doesn't matter</h1>\n<p>The heater cartridges are just large resistors and so polarity is irrelevant. Either can be positive or negative.</p>\n<p>You can extend the leads by cutting and splicing in ~20 gauge wires* to a two pin JST connector line you suggest.</p>\n<hr />\n<p>*<sup>At 24 volts and 30 watts, you need <a href=\"https://www.platt.com/CutSheets/Multiple/AWG%20Conductors.pdf\" rel=\"nofollow noreferrer\">wire that is rated to carry at least 1.25 amps</a>. The US National Electric Code dictates that this should be 20 gauge wire, but their standard is very conservative. Since you don't need to adhere to NEC codes, you could get away with something thinner (ie higher gauge number).</sup></p>\n"
},
{
"answer_id": 16107,
"author": "Perry Webb",
"author_id": 15075,
"author_profile": "https://3dprinting.stackexchange.com/users/15075",
"pm_score": 2,
"selected": false,
"text": "<p>1 meter puts you far enough away from the heater than you don't need high temperature wiring to extend it. The larger the guage(e.g. 20 guage) the less resistance you will add to the heater circuit. This doesn't matter as long as you can still achieve your maximum temperature (if you can still achieve the same current without maxing out your voltage on the heater).</p>\n<p>Your sensor is where added series resistance is critical. Series resistance to the thermistor will give a negative error in the temperature.</p>\n"
}
] | 2021/04/17 | [
"https://3dprinting.stackexchange.com/questions/16113",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/27919/"
] | My custom 3D printer prints everything inverted. I guess this is a homing problem as the motor moves in correct direction.
In Pronterface,
* if I press -Y — bed moves forward (towards the Y endstop)
* if I press +Y — bed moves backward (away from Y endstop)
* if I press -X — hotend moves left (towards the X endstop)
* if I press +X — hotend moves right (away from the X endstop)
on RAMPS 1.4:
* X endstop is connected on the 1st pin
* Y endstop is connected on the 3rd pin
* Z endstop is connected on the 5th pin
(Pin 2, 4 & 6 are not used (are these for MAX\_ENDSTOP ?))
Below is my Marlin config
```
#define X_MIN_ENDSTOP_INVERTING true // Set to true to invert the logic of the endstop.
#define Y_MIN_ENDSTOP_INVERTING true // Set to true to invert the logic of the endstop.
#define Z_MIN_ENDSTOP_INVERTING true // Set to true to invert the logic of the endstop.
#define X_MAX_ENDSTOP_INVERTING false // Set to true to invert the logic of the endstop.
#define Y_MAX_ENDSTOP_INVERTING false // Set to true to invert the logic of the endstop.
#define Z_MAX_ENDSTOP_INVERTING false // Set to true to invert the logic of the endstop.
#define Z_MIN_PROBE_ENDSTOP_INVERTING false // Set to true to invert the logic of the probe.
#define X_HOME_DIR -1
#define Y_HOME_DIR -1
#define Z_HOME_DIR -1
#define INVERT_X_DIR false
#define INVERT_Y_DIR false
#define INVERT_Z_DIR false
```
I have attached 3 photographs.
1. Shows the Home position of hotend. Y Motor on back and Y endstop at front.
[![Home position of hotend](https://i.stack.imgur.com/M4Gcr.jpg)](https://i.stack.imgur.com/M4Gcr.jpg)
2. Shows inverted print.
[![inverted print](https://i.stack.imgur.com/9SRBZ.jpg)](https://i.stack.imgur.com/9SRBZ.jpg)
3. Pronterface screenshot (shows actual G-code file)
[![Pronterface screenshot](https://i.stack.imgur.com/4ru5r.jpg)](https://i.stack.imgur.com/4ru5r.jpg)
I tried flipping the motor cables, but that inverts the motor direction
I also tried INVERT\_Y\_DIR true, but no luck.
Please help me. What am I doing wrong? | Heater polarity doesn't matter
==============================
The heater cartridges are just large resistors and so polarity is irrelevant. Either can be positive or negative.
You can extend the leads by cutting and splicing in ~20 gauge wires\* to a two pin JST connector line you suggest.
---
\*At 24 volts and 30 watts, you need [wire that is rated to carry at least 1.25 amps](https://www.platt.com/CutSheets/Multiple/AWG%20Conductors.pdf). The US National Electric Code dictates that this should be 20 gauge wire, but their standard is very conservative. Since you don't need to adhere to NEC codes, you could get away with something thinner (ie higher gauge number). |
16,210 | <p>My Ender 5 Plus (original) does not perform leveling.</p>
<p>After the self-leveling command, the Z axis only descends.
I have already exchanged the BLTouch three times, and the problem remains unchanged.</p>
<p>I bought my E5P in December, in America, to bring it to Brazil, I had to completely dismantle it.</p>
<p>Machine reassembled, I start work again, everything works very well.
But, one day, I made the mistake of stopping an impression (due to problems with the appearance of the piece) and, before removing the piece from the bed, I pressed the HOME command, which caused the hotend/BLTouch to rest on the printed part, forcing the whole mechanism.</p>
<p>Well, I changed the BLTouch and the problems really started.<br />
When I send the leveling command, the Z-axis behaves erratically, going down instead of returning to the beginning and, with each command, it goes down more and more.</p>
<p>I changed the leveler again, the problem persisted, I disassembled piece by piece, wiped a general cleaning, applied a clean solution to contacts all over the electronics, reassembled, reinstalled the firmware (Version 1.71.0 KF), and everything went back to work.</p>
<p>Yesterday, I sent a piece for printing (PLA nozzle 1.00 mm, layer 0.36 mm, speed 100 mm/s, infill 40 %), and left for my morning walk. When I returned, there was a huge ball of melted material, adhered to the hotend, again more problems. I disassembled the entire hotend, carried out the total cleaning, reassembled it, and let's go back to work.</p>
<p>Leveling OK, there was a problem with the thermistor and the heating of the nozzle, I changed the thermistor and the heater cartridge (taking the opportunity, since several times the system had heating problems, when the temperature should be above 230 °C / 446 °F). Everything ready, come on...</p>
<ul>
<li>Leveling problem has returned.</li>
<li>BLTouch exchange done, nothing done</li>
<li>Loading the firmware again, nothing done</li>
<li>Review of connections, nothing done</li>
</ul>
<p>The Z-axis continues to descend, not responding to commands, and in the Pronterface the message appears:</p>
<pre><code>Error: STOP called because of BLTouch error - restart with M999
Error: STOP called because of BLTouch error - restart with M999
</code></pre>
<p>I've already exchanged BLTouch 2 times and it didn't work out.
I have 2 inductive levelers here, maybe the solution is to install them and forget the BLTouch, or do the leveling manually.</p>
<p>Questions:</p>
<ol>
<li>Has anyone had this kind of problem with the printer? If so, what is the solution?</li>
<li>removing the leveler and performing manual leveling, has anyone tried this? What changes in Marlin need to be made?</li>
<li>Does the replacement of the BLTouch by an inductive sensor imply in what firmware changes? Is there a tutorial about it?</li>
</ol>
<p>I appreciate any help you can get from friends</p>
| [
{
"answer_id": 16365,
"author": "Mr Dean E Sarelius",
"author_id": 28536,
"author_profile": "https://3dprinting.stackexchange.com/users/28536",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem with my Ender 5 Plus.</p>\n<p>There is a small set screw at the top of the BLTouch you will need to tighten this in to adjust the location of the sensor pin. Keep screwing it more and more until you see it initialize reliably that is it should move out and back twice to initialize.</p>\n<p>When the BLTouch initializes correctly then the leveling can be completed.</p>\n"
},
{
"answer_id": 18982,
"author": "G-Prizzy",
"author_id": 33258,
"author_profile": "https://3dprinting.stackexchange.com/users/33258",
"pm_score": -1,
"selected": false,
"text": "<p>I had the same issue. The probe for the BL touch was just stuck.</p>\n<p>I manually pulled it out and tightened the screw and then the problem was fixed.</p>\n"
}
] | 2021/04/28 | [
"https://3dprinting.stackexchange.com/questions/16210",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/28103/"
] | My Ender 5 Plus (original) does not perform leveling.
After the self-leveling command, the Z axis only descends.
I have already exchanged the BLTouch three times, and the problem remains unchanged.
I bought my E5P in December, in America, to bring it to Brazil, I had to completely dismantle it.
Machine reassembled, I start work again, everything works very well.
But, one day, I made the mistake of stopping an impression (due to problems with the appearance of the piece) and, before removing the piece from the bed, I pressed the HOME command, which caused the hotend/BLTouch to rest on the printed part, forcing the whole mechanism.
Well, I changed the BLTouch and the problems really started.
When I send the leveling command, the Z-axis behaves erratically, going down instead of returning to the beginning and, with each command, it goes down more and more.
I changed the leveler again, the problem persisted, I disassembled piece by piece, wiped a general cleaning, applied a clean solution to contacts all over the electronics, reassembled, reinstalled the firmware (Version 1.71.0 KF), and everything went back to work.
Yesterday, I sent a piece for printing (PLA nozzle 1.00 mm, layer 0.36 mm, speed 100 mm/s, infill 40 %), and left for my morning walk. When I returned, there was a huge ball of melted material, adhered to the hotend, again more problems. I disassembled the entire hotend, carried out the total cleaning, reassembled it, and let's go back to work.
Leveling OK, there was a problem with the thermistor and the heating of the nozzle, I changed the thermistor and the heater cartridge (taking the opportunity, since several times the system had heating problems, when the temperature should be above 230 °C / 446 °F). Everything ready, come on...
* Leveling problem has returned.
* BLTouch exchange done, nothing done
* Loading the firmware again, nothing done
* Review of connections, nothing done
The Z-axis continues to descend, not responding to commands, and in the Pronterface the message appears:
```
Error: STOP called because of BLTouch error - restart with M999
Error: STOP called because of BLTouch error - restart with M999
```
I've already exchanged BLTouch 2 times and it didn't work out.
I have 2 inductive levelers here, maybe the solution is to install them and forget the BLTouch, or do the leveling manually.
Questions:
1. Has anyone had this kind of problem with the printer? If so, what is the solution?
2. removing the leveler and performing manual leveling, has anyone tried this? What changes in Marlin need to be made?
3. Does the replacement of the BLTouch by an inductive sensor imply in what firmware changes? Is there a tutorial about it?
I appreciate any help you can get from friends | I had the same problem with my Ender 5 Plus.
There is a small set screw at the top of the BLTouch you will need to tighten this in to adjust the location of the sensor pin. Keep screwing it more and more until you see it initialize reliably that is it should move out and back twice to initialize.
When the BLTouch initializes correctly then the leveling can be completed. |
16,279 | <p><strong>My setup</strong></p>
<ul>
<li>Ender 3</li>
<li>Creality glass bed</li>
<li>Creality 3D BL Touch auto bed levelling kit v1</li>
<li>Creality 3D silent mainboard v4.2.7</li>
<li>OctoPrint running on a Raspberry Pi 4 connected over USB (with the 5 V pin covered with a piece of tape to prevent powering the mainboard)</li>
</ul>
<p><strong>Problem</strong></p>
<p>Despite starting with <code>G28</code> & <code>G29</code> in my G-code file, and the printer & BLTouch doing a proper bed levelling (the BLTouch seems to work as intended), the first layer comes out uneven. Please find some pictures below of a test print (<a href="https://thingiverse.com/thing:4077747" rel="nofollow noreferrer">this one</a>). I hope the pictures show clearly that the nozzle is too close in the bottom left, and too far in the top right (top left is also a bit far, and bottom right a bit close).</p>
<p>I've done days of research, all over the web, Reddit, forums & YouTube and tried numerous fixes, to no avail</p>
<p><a href="https://i.stack.imgur.com/KBGqd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KBGqd.jpg" alt="total" /></a>
<a href="https://i.stack.imgur.com/0AUFG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0AUFG.jpg" alt="top left" /></a>
<a href="https://i.stack.imgur.com/TXjUk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TXjUk.jpg" alt="top right" /></a>
<a href="https://i.stack.imgur.com/Qhg7n.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qhg7n.jpg" alt="bottom left" /></a>
<a href="https://i.stack.imgur.com/leTlq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/leTlq.jpg" alt="bottom right" /></a></p>
<p><strong>What I've done to try to fix / debug 1: Observe z compensation</strong></p>
<p>When I do a test print with a bed levelling at the start, I observe the z-axis go up and down during the print, suggesting the printer is trying to compensate based on the readings from the start of the print. It just seems it's not compensating enough (or too much).</p>
<p>When I run a <code>M420 V</code> I get (which implies it has the mesh loaded):</p>
<pre><code>Send: M420 V
Communication timeout while idle, trying to trigger response from printer. Configure long running commands or increase communication timeout if that happens regularly on specific commands or long moves.
Recv: Bilinear Leveling Grid:
Recv: 0 1 2 3 4
Recv: 0 +1.245 +1.257 +1.282 +1.332 +1.342
Recv: 1 +1.187 +1.167 +1.130 +1.127 +1.147
Recv: 2 +1.082 +1.080 +1.057 +1.077 +1.085
Recv: 3 +1.202 +1.147 +1.057 +1.000 +0.957
Recv: 4 +1.192 +1.180 +1.117 +1.085 +1.027
Recv:
Recv: echo:Bed Leveling ON
Recv: echo:Fade Height 10.00
Recv: ok P15 B3
</code></pre>
<p><strong>What I've done to try to fix / debug 2: Level the bed as much as possible</strong></p>
<p>I've tried to level the bed as best as possible. As you can observe from the <code>M420 V</code> command the bed is pretty level. This was done using the Bed Level Visualizer plugin from OctoPrint.</p>
<p><strong>What I've done to try to fix / debug 3: I've changed from a 3x3 grid to a 5x5 grid</strong></p>
<p>As advised in several places the bed levelling is now done with a 5x5 grid. This didn't make a (noticeable) difference.</p>
<p><strong>What I've done to try to fix / debug 4: I've updated the firmware</strong></p>
<p>I used to run on the Creality firmware. I've downloaded new firmware from <code>marlin.crc.id.au</code> (did that today, so using <code>Ender3-v4.2.7-BLTouch-20210511.bin</code>). Didn't help.</p>
<p><strong>What I've done to try to fix / debug 5: I've calibrated the Z-offset</strong></p>
<p>I've done a lot of tests, tweaking the z value to the current value, where part of the bed comes too close to the nozzle, and part of the bed stays too far away. So the Z-offset is not going to be able to improve anything I believe.</p>
<p><strong>What I've done to try to fix / debug 6: I've done all the regular hardware tweaks</strong></p>
<p>I've checked all the common things: Belts are tight, wheels are properly tightened, nothing is wobbly, Z-axis is clean.</p>
<p><strong>What I've done to try to fix / debug 7: I've tried to add M420 S</strong></p>
<p>I've tried to add the <code>M420</code> command after the <code>G29</code> command (I know it shouldn't be needed, as <code>G29</code> enables bed levelling, but just wanted to make sure)</p>
<p><strong>Reference: My printer M503 settings</strong></p>
<pre><code>echo: G21 ; Units in mm (mm)
echo: M149 C ; Units in Celsius
echo:; Filament settings: Disabled
echo: M200 S0 D1.75
echo:; Steps per unit:
echo: M92 X80.00 Y80.00 Z400.00 E93.00
echo:; Maximum feedrates (units/s):
echo: M203 X500.00 Y500.00 Z20.00 E50.00
echo:; Maximum Acceleration (units/s2):
echo: M201 X500.00 Y500.00 Z100.00 E5000.00
echo:; Acceleration (units/s2): P<print_accel> R<retract_accel> T<travel_accel>
echo: M204 P500.00 R500.00 T500.00
echo:; Advanced: B<min_segment_time_us> S<min_feedrate> T<min_travel_feedrate> X<max_x_jerk> Y<max_y_jerk> Z<max_z_jerk> E<max_e_jerk>
echo: M205 B20000.00 S0.00 T0.00 X10.00 Y10.00 Z0.30 E15.00
echo:; Home offset:
echo: M206 X0.00 Y0.00 Z0.00
echo:; Auto Bed Leveling:
echo: M420 S1 Z10.00
echo: G29 W I0 J0 Z1.24499
echo: G29 W I1 J0 Z1.25749
echo: G29 W I2 J0 Z1.28249
echo: G29 W I3 J0 Z1.33249
echo: G29 W I4 J0 Z1.34249
echo: G29 W I0 J1 Z1.18749
echo: G29 W I1 J1 Z1.16749
echo: G29 W I2 J1 Z1.12999
echo: G29 W I3 J1 Z1.12749
echo: G29 W I4 J1 Z1.14749
echo: G29 W I0 J2 Z1.08249
echo: G29 W I1 J2 Z1.07999
echo: G29 W I2 J2 Z1.05749
echo: G29 W I3 J2 Z1.07749
echo: G29 W I4 J2 Z1.08499
echo: G29 W I0 J3 Z1.20249
echo: G29 W I1 J3 Z1.14749
echo: G29 W I2 J3 Z1.05749
echo: G29 W I3 J3 Z0.99999
echo: G29 W I4 J3 Z0.95749
echo: G29 W I0 J4 Z1.19249
echo: G29 W I1 J4 Z1.17999
echo: G29 W I2 J4 Z1.11749
echo: G29 W I3 J4 Z1.08499
echo: G29 W I4 J4 Z1.02749
echo:; Material heatup parameters:
echo: M145 S0 H200.00 B60.00 F255
echo: M145 S1 H240.00 B70.00 F255
echo:; PID settings:
echo: M301 P21.73 I1.54 D76.55
echo:; Retract: S<length> F<units/m> Z<lift>
echo: M207 S3.00 W13.00 F4800.00 Z0.30
echo:; Recover: S<length> F<units/m>
echo: M208 S0.00 W0.00 F4800.00
echo:; Z-Probe Offset (mm):
echo: M851 X-45.00 Y-7.00 Z-3.30
echo:; Filament load/unload lengths:
echo: M603 L415.00 U450.00
echo:; Filament runout sensor:
echo: M412 S0 D8.00
ok P15 B3
</code></pre>
<p><strong>Reference: The start of my G-code file</strong></p>
<pre><code>;FLAVOR:Marlin
;TIME:775
;Filament used: 0.480677m
;Layer height: 0.2
;MINX:16.516
;MINY:16.515
;MINZ:0.2
;MAXX:218.485
;MAXY:218.485
;MAXZ:0.2
;Generated with Cura_SteamEngine 4.9.0
M140 S60
M105
M190 S60
M104 S215
M105
M109 S215
M82 ;absolute extrusion mode
; Ender 3 Custom Start G-code
G92 E0 ; Reset Extruder
G28 ; Home all axes
G29 ; Auto bed levelling
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position
G1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line
G1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little
G1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line
G92 E0 ; Reset Extruder
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X5 Y20 Z0.3 F5000.0 ; Move over to prevent blob squish
G92 E0
G92 E0
G1 F2700 E-5
;LAYER_COUNT:1
;LAYER:0
M107
G0 F6000 X26.14 Y20.098 Z0.2
;TYPE:SKIRT
G1 F2700 E0
</code></pre>
<p><strong>Reference: Congifuration.h</strong></p>
<p>As I've used two precompiled firmwares (see point 4 above), I don't have a <code>Congifuration.h</code> to share.</p>
<p><strong>Concluding</strong></p>
<p>I hope I've given a detailed enough account for you guys to help me. If you have any additional questions I'll try to answer them as quickly as possible. Thanks a million!</p>
| [
{
"answer_id": 18472,
"author": "Trimsley",
"author_id": 32131,
"author_profile": "https://3dprinting.stackexchange.com/users/32131",
"pm_score": 0,
"selected": false,
"text": "<p>I had the exact same issue as you and had done all the fixes you mentioned. The only thing that solved it for me was to make sure the model in the slicing software was flat to the "bed".</p>\n<p>I use Cura and it has a "flat the bed" option which I only discovered due to a model that was slightly off which caused the top and bottom layer to half.</p>\n"
},
{
"answer_id": 18865,
"author": "cybernard",
"author_id": 16395,
"author_profile": "https://3dprinting.stackexchange.com/users/16395",
"pm_score": 1,
"selected": false,
"text": "<p>Had similar problems. I even did a 10x10 grid just to find out that my printing bed wasn't actually flat.</p>\n<p>It actually had dips in it.</p>\n<p>I would have to look up the command, but I actually just lowered the nozzle by 0.050 mm at a time. Eventually it got too low, and then I backed it off in even smaller increments.</p>\n<p>I also had to print with a raft so any extreme dips are held together on top of the raft.</p>\n"
}
] | 2021/05/12 | [
"https://3dprinting.stackexchange.com/questions/16279",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/28336/"
] | **My setup**
* Ender 3
* Creality glass bed
* Creality 3D BL Touch auto bed levelling kit v1
* Creality 3D silent mainboard v4.2.7
* OctoPrint running on a Raspberry Pi 4 connected over USB (with the 5 V pin covered with a piece of tape to prevent powering the mainboard)
**Problem**
Despite starting with `G28` & `G29` in my G-code file, and the printer & BLTouch doing a proper bed levelling (the BLTouch seems to work as intended), the first layer comes out uneven. Please find some pictures below of a test print ([this one](https://thingiverse.com/thing:4077747)). I hope the pictures show clearly that the nozzle is too close in the bottom left, and too far in the top right (top left is also a bit far, and bottom right a bit close).
I've done days of research, all over the web, Reddit, forums & YouTube and tried numerous fixes, to no avail
[![total](https://i.stack.imgur.com/KBGqd.jpg)](https://i.stack.imgur.com/KBGqd.jpg)
[![top left](https://i.stack.imgur.com/0AUFG.jpg)](https://i.stack.imgur.com/0AUFG.jpg)
[![top right](https://i.stack.imgur.com/TXjUk.jpg)](https://i.stack.imgur.com/TXjUk.jpg)
[![bottom left](https://i.stack.imgur.com/Qhg7n.jpg)](https://i.stack.imgur.com/Qhg7n.jpg)
[![bottom right](https://i.stack.imgur.com/leTlq.jpg)](https://i.stack.imgur.com/leTlq.jpg)
**What I've done to try to fix / debug 1: Observe z compensation**
When I do a test print with a bed levelling at the start, I observe the z-axis go up and down during the print, suggesting the printer is trying to compensate based on the readings from the start of the print. It just seems it's not compensating enough (or too much).
When I run a `M420 V` I get (which implies it has the mesh loaded):
```
Send: M420 V
Communication timeout while idle, trying to trigger response from printer. Configure long running commands or increase communication timeout if that happens regularly on specific commands or long moves.
Recv: Bilinear Leveling Grid:
Recv: 0 1 2 3 4
Recv: 0 +1.245 +1.257 +1.282 +1.332 +1.342
Recv: 1 +1.187 +1.167 +1.130 +1.127 +1.147
Recv: 2 +1.082 +1.080 +1.057 +1.077 +1.085
Recv: 3 +1.202 +1.147 +1.057 +1.000 +0.957
Recv: 4 +1.192 +1.180 +1.117 +1.085 +1.027
Recv:
Recv: echo:Bed Leveling ON
Recv: echo:Fade Height 10.00
Recv: ok P15 B3
```
**What I've done to try to fix / debug 2: Level the bed as much as possible**
I've tried to level the bed as best as possible. As you can observe from the `M420 V` command the bed is pretty level. This was done using the Bed Level Visualizer plugin from OctoPrint.
**What I've done to try to fix / debug 3: I've changed from a 3x3 grid to a 5x5 grid**
As advised in several places the bed levelling is now done with a 5x5 grid. This didn't make a (noticeable) difference.
**What I've done to try to fix / debug 4: I've updated the firmware**
I used to run on the Creality firmware. I've downloaded new firmware from `marlin.crc.id.au` (did that today, so using `Ender3-v4.2.7-BLTouch-20210511.bin`). Didn't help.
**What I've done to try to fix / debug 5: I've calibrated the Z-offset**
I've done a lot of tests, tweaking the z value to the current value, where part of the bed comes too close to the nozzle, and part of the bed stays too far away. So the Z-offset is not going to be able to improve anything I believe.
**What I've done to try to fix / debug 6: I've done all the regular hardware tweaks**
I've checked all the common things: Belts are tight, wheels are properly tightened, nothing is wobbly, Z-axis is clean.
**What I've done to try to fix / debug 7: I've tried to add M420 S**
I've tried to add the `M420` command after the `G29` command (I know it shouldn't be needed, as `G29` enables bed levelling, but just wanted to make sure)
**Reference: My printer M503 settings**
```
echo: G21 ; Units in mm (mm)
echo: M149 C ; Units in Celsius
echo:; Filament settings: Disabled
echo: M200 S0 D1.75
echo:; Steps per unit:
echo: M92 X80.00 Y80.00 Z400.00 E93.00
echo:; Maximum feedrates (units/s):
echo: M203 X500.00 Y500.00 Z20.00 E50.00
echo:; Maximum Acceleration (units/s2):
echo: M201 X500.00 Y500.00 Z100.00 E5000.00
echo:; Acceleration (units/s2): P<print_accel> R<retract_accel> T<travel_accel>
echo: M204 P500.00 R500.00 T500.00
echo:; Advanced: B<min_segment_time_us> S<min_feedrate> T<min_travel_feedrate> X<max_x_jerk> Y<max_y_jerk> Z<max_z_jerk> E<max_e_jerk>
echo: M205 B20000.00 S0.00 T0.00 X10.00 Y10.00 Z0.30 E15.00
echo:; Home offset:
echo: M206 X0.00 Y0.00 Z0.00
echo:; Auto Bed Leveling:
echo: M420 S1 Z10.00
echo: G29 W I0 J0 Z1.24499
echo: G29 W I1 J0 Z1.25749
echo: G29 W I2 J0 Z1.28249
echo: G29 W I3 J0 Z1.33249
echo: G29 W I4 J0 Z1.34249
echo: G29 W I0 J1 Z1.18749
echo: G29 W I1 J1 Z1.16749
echo: G29 W I2 J1 Z1.12999
echo: G29 W I3 J1 Z1.12749
echo: G29 W I4 J1 Z1.14749
echo: G29 W I0 J2 Z1.08249
echo: G29 W I1 J2 Z1.07999
echo: G29 W I2 J2 Z1.05749
echo: G29 W I3 J2 Z1.07749
echo: G29 W I4 J2 Z1.08499
echo: G29 W I0 J3 Z1.20249
echo: G29 W I1 J3 Z1.14749
echo: G29 W I2 J3 Z1.05749
echo: G29 W I3 J3 Z0.99999
echo: G29 W I4 J3 Z0.95749
echo: G29 W I0 J4 Z1.19249
echo: G29 W I1 J4 Z1.17999
echo: G29 W I2 J4 Z1.11749
echo: G29 W I3 J4 Z1.08499
echo: G29 W I4 J4 Z1.02749
echo:; Material heatup parameters:
echo: M145 S0 H200.00 B60.00 F255
echo: M145 S1 H240.00 B70.00 F255
echo:; PID settings:
echo: M301 P21.73 I1.54 D76.55
echo:; Retract: S<length> F<units/m> Z<lift>
echo: M207 S3.00 W13.00 F4800.00 Z0.30
echo:; Recover: S<length> F<units/m>
echo: M208 S0.00 W0.00 F4800.00
echo:; Z-Probe Offset (mm):
echo: M851 X-45.00 Y-7.00 Z-3.30
echo:; Filament load/unload lengths:
echo: M603 L415.00 U450.00
echo:; Filament runout sensor:
echo: M412 S0 D8.00
ok P15 B3
```
**Reference: The start of my G-code file**
```
;FLAVOR:Marlin
;TIME:775
;Filament used: 0.480677m
;Layer height: 0.2
;MINX:16.516
;MINY:16.515
;MINZ:0.2
;MAXX:218.485
;MAXY:218.485
;MAXZ:0.2
;Generated with Cura_SteamEngine 4.9.0
M140 S60
M105
M190 S60
M104 S215
M105
M109 S215
M82 ;absolute extrusion mode
; Ender 3 Custom Start G-code
G92 E0 ; Reset Extruder
G28 ; Home all axes
G29 ; Auto bed levelling
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position
G1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line
G1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little
G1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line
G92 E0 ; Reset Extruder
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X5 Y20 Z0.3 F5000.0 ; Move over to prevent blob squish
G92 E0
G92 E0
G1 F2700 E-5
;LAYER_COUNT:1
;LAYER:0
M107
G0 F6000 X26.14 Y20.098 Z0.2
;TYPE:SKIRT
G1 F2700 E0
```
**Reference: Congifuration.h**
As I've used two precompiled firmwares (see point 4 above), I don't have a `Congifuration.h` to share.
**Concluding**
I hope I've given a detailed enough account for you guys to help me. If you have any additional questions I'll try to answer them as quickly as possible. Thanks a million! | Had similar problems. I even did a 10x10 grid just to find out that my printing bed wasn't actually flat.
It actually had dips in it.
I would have to look up the command, but I actually just lowered the nozzle by 0.050 mm at a time. Eventually it got too low, and then I backed it off in even smaller increments.
I also had to print with a raft so any extreme dips are held together on top of the raft. |
16,546 | <p>I have a Tevo Flash. Normally, I don't care about perpendicularity with respect to the table. But now I have a 5" disc on a ball bearing, held by a 3D printed tube with a flat bottom. If the tube's axis is not 100 % perpendicular to the bottom, the disc, when spun, wobbles at the edge: ~1/8".</p>
<p><a href="https://i.stack.imgur.com/LgMr5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LgMr5.png" alt="Disc wobble" /></a></p>
<p>As a test, I printed a vertical sample tube. I took close-up pics, on the printer's table, next to a carpenter's square. Down the table's Y axis, there's a vert. deviation of ~1 mm over 45 mm of height, between the sample tube and the square. Down the X-axis, the deviation is small.</p>
<p><a href="https://i.stack.imgur.com/rhb9c.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rhb9c.jpg" alt="Deviation photos" /></a></p>
<p>How do I deal with it? Can a slicer (I have Simplify3D) compensate for it? I could gently "skew" the geo in 3D modeling software, but it seems inelegant.</p>
<p>Note: this has nothing to do with bed leveling. The bed is level, the printer has a BLTouch. The first layers look great. The problem is above the bed. The right angles of the aluminum-extrusion frame aren't 100 % exact. Measured with the carpenter's square, the vertical columns of the frame (Z) deviate 1-2 mm over 100 mm from perpendicular, with respect to the bottom frame (X-Y). Trying to fix the whole frame would be hard.</p>
<p>EDIT: I used a 0.127 mm shim (from a sacrificial steel gauge blade), it fixed most of it. With the printer laid horizontally (so I could work with the screws underneath) and the shim in, the vertical posts were 100% true (see pic). When I put the printer back into its vertical, working position, the posts tilted back a bit. I'll try a 0.15 mm shim.</p>
<p><a href="https://i.stack.imgur.com/2Rt9t.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Rt9t.jpg" alt="Shim added" /></a></p>
| [
{
"answer_id": 16550,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 11157,
"author_profile": "https://3dprinting.stackexchange.com/users/11157",
"pm_score": 0,
"selected": false,
"text": "<p>If you've measured the frame and it's not square, that's almost surely your problem and you need to fix it. But having a BLtouch does not mean your bed is level. The effect you're seeing is exactly what you get from using a BLtouch and mesh leveling to compensate for a non-level bed, and it's a very bad thing and why these fake leveling systems are band-aids to make it easier to get started printing something minimally viable, not something that gives you a working, precise printer. The bed needs to be physically square with the Z axis.</p>\n"
},
{
"answer_id": 16551,
"author": "0scar",
"author_id": 5740,
"author_profile": "https://3dprinting.stackexchange.com/users/5740",
"pm_score": 4,
"selected": true,
"text": "<p>In answer to <em>(doesn't have to the issue of the OP, but as a reaction for other readers)</em>:</p>\n<blockquote>\n<p>Note: this has nothing to do with bed leveling. The bed is level, the printer has a BLTouch.</p>\n</blockquote>\n<p><a href=\"/a/16605\">Having a BLTouch doesn't imply the bed is level!</a> The bed is level when the nozzle moves in the same plane parallel to the bed, the bed shape is compensated for by the BLTouch, it can be very skew and still it will print.</p>\n<blockquote>\n<p>The right angles of the aluminum-extrusion frame aren't 100 % exact.</p>\n</blockquote>\n<p>That is a problem, the frame needs to be square. I don't think that it is a major operation to modify that, you can use some support struts, I've done that for a 2040 aluminum extrusion i3 clone.</p>\n<p>Note, this is a portal style printer driven by a single Z lead screw (and a roller mount on the other Z post) as far as can be seen from the manufacturer photographs. <em>(Update, the OP has a dual screw Z portal, so this possibly is not applicable to that specific version)</em> Single Z screw portal printer types are also prone to unlevel over height, be sure the rollers of the nozzle carrier and the opposite Z post rollers are correctly functioning.</p>\n<p>Although fixing the hardware is the preferred option, there is an alternative, you can solve this in firmware like e.g. Marlin.</p>\n<p>You need to make some test prints and fill out the correct values to correct for the skewness, but this may be limited to overall Z skewness, not individual skew Z posts.</p>\n<p>E.g. in Marlin, the configuration file can be used to compensate the skewness problem:</p>\n<pre><code>/**\n * Bed Skew Compensation\n *\n * This feature corrects for misalignment in the XYZ axes.\n *\n * Take the following steps to get the bed skew in the XY plane:\n * 1. Print a test square (e.g., https://www.thingiverse.com/thing:2563185)\n * 2. For XY_DIAG_AC measure the diagonal A to C\n * 3. For XY_DIAG_BD measure the diagonal B to D\n * 4. For XY_SIDE_AD measure the edge A to D\n *\n * Marlin automatically computes skew factors from these measurements.\n * Skew factors may also be computed and set manually:\n *\n * - Compute AB : SQRT(2*AC*AC+2*BD*BD-4*AD*AD)/2\n * - XY_SKEW_FACTOR : TAN(PI/2-ACOS((AC*AC-AB*AB-AD*AD)/(2*AB*AD)))\n *\n * If desired, follow the same procedure for XZ and YZ.\n * Use these diagrams for reference:\n *\n * Y Z Z\n * ^ B-------C ^ B-------C ^ B-------C\n * | / / | / / | / /\n * | / / | / / | / /\n * | A-------D | A-------D | A-------D\n * +-------------->X +-------------->X +-------------->Y\n * XY_SKEW_FACTOR XZ_SKEW_FACTOR YZ_SKEW_FACTOR\n */\n//#define SKEW_CORRECTION\n</code></pre>\n<p>But, this requires a new firmware installation, the reader should investigate whether this is within the capabilities of the reader.</p>\n"
},
{
"answer_id": 16553,
"author": "Zeiss Ikon",
"author_id": 28508,
"author_profile": "https://3dprinting.stackexchange.com/users/28508",
"pm_score": 0,
"selected": false,
"text": "<p>The vertical axis of your print is determined by the machine's Z axis, not by the "bed level" compensation of a BL Touch or similar bed error compensation system.</p>\n<p>When you print after BL Touch measures the bed height, the firmware moves the Z axis up and down to compensate for errors in the bed (including non-planar bed surface, which is its main utility) -- but as you print and the hotend moves up layer by layer, the movement is determined by the Z axis -- with a common gantry type printer, this is set by the vertical frame. If that frame isn't perpendicular to the X and Y axes, the verticals of the print won't be, either.</p>\n<p>To correct your Y axis tilt, you need to correct your vertical frame tilt. The simplest way to do this is likely to be installing an adjustable frame brace system (you can print all the parts except for a couple threaded rods). That will let you make a precise adjustment, print another test like the one in the question, and verify that it's accurate, before printing your "disk on a donut" actual part.</p>\n"
}
] | 2021/06/17 | [
"https://3dprinting.stackexchange.com/questions/16546",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/14316/"
] | I have a Tevo Flash. Normally, I don't care about perpendicularity with respect to the table. But now I have a 5" disc on a ball bearing, held by a 3D printed tube with a flat bottom. If the tube's axis is not 100 % perpendicular to the bottom, the disc, when spun, wobbles at the edge: ~1/8".
[![Disc wobble](https://i.stack.imgur.com/LgMr5.png)](https://i.stack.imgur.com/LgMr5.png)
As a test, I printed a vertical sample tube. I took close-up pics, on the printer's table, next to a carpenter's square. Down the table's Y axis, there's a vert. deviation of ~1 mm over 45 mm of height, between the sample tube and the square. Down the X-axis, the deviation is small.
[![Deviation photos](https://i.stack.imgur.com/rhb9c.jpg)](https://i.stack.imgur.com/rhb9c.jpg)
How do I deal with it? Can a slicer (I have Simplify3D) compensate for it? I could gently "skew" the geo in 3D modeling software, but it seems inelegant.
Note: this has nothing to do with bed leveling. The bed is level, the printer has a BLTouch. The first layers look great. The problem is above the bed. The right angles of the aluminum-extrusion frame aren't 100 % exact. Measured with the carpenter's square, the vertical columns of the frame (Z) deviate 1-2 mm over 100 mm from perpendicular, with respect to the bottom frame (X-Y). Trying to fix the whole frame would be hard.
EDIT: I used a 0.127 mm shim (from a sacrificial steel gauge blade), it fixed most of it. With the printer laid horizontally (so I could work with the screws underneath) and the shim in, the vertical posts were 100% true (see pic). When I put the printer back into its vertical, working position, the posts tilted back a bit. I'll try a 0.15 mm shim.
[![Shim added](https://i.stack.imgur.com/2Rt9t.jpg)](https://i.stack.imgur.com/2Rt9t.jpg) | In answer to *(doesn't have to the issue of the OP, but as a reaction for other readers)*:
>
> Note: this has nothing to do with bed leveling. The bed is level, the printer has a BLTouch.
>
>
>
[Having a BLTouch doesn't imply the bed is level!](/a/16605) The bed is level when the nozzle moves in the same plane parallel to the bed, the bed shape is compensated for by the BLTouch, it can be very skew and still it will print.
>
> The right angles of the aluminum-extrusion frame aren't 100 % exact.
>
>
>
That is a problem, the frame needs to be square. I don't think that it is a major operation to modify that, you can use some support struts, I've done that for a 2040 aluminum extrusion i3 clone.
Note, this is a portal style printer driven by a single Z lead screw (and a roller mount on the other Z post) as far as can be seen from the manufacturer photographs. *(Update, the OP has a dual screw Z portal, so this possibly is not applicable to that specific version)* Single Z screw portal printer types are also prone to unlevel over height, be sure the rollers of the nozzle carrier and the opposite Z post rollers are correctly functioning.
Although fixing the hardware is the preferred option, there is an alternative, you can solve this in firmware like e.g. Marlin.
You need to make some test prints and fill out the correct values to correct for the skewness, but this may be limited to overall Z skewness, not individual skew Z posts.
E.g. in Marlin, the configuration file can be used to compensate the skewness problem:
```
/**
* Bed Skew Compensation
*
* This feature corrects for misalignment in the XYZ axes.
*
* Take the following steps to get the bed skew in the XY plane:
* 1. Print a test square (e.g., https://www.thingiverse.com/thing:2563185)
* 2. For XY_DIAG_AC measure the diagonal A to C
* 3. For XY_DIAG_BD measure the diagonal B to D
* 4. For XY_SIDE_AD measure the edge A to D
*
* Marlin automatically computes skew factors from these measurements.
* Skew factors may also be computed and set manually:
*
* - Compute AB : SQRT(2*AC*AC+2*BD*BD-4*AD*AD)/2
* - XY_SKEW_FACTOR : TAN(PI/2-ACOS((AC*AC-AB*AB-AD*AD)/(2*AB*AD)))
*
* If desired, follow the same procedure for XZ and YZ.
* Use these diagrams for reference:
*
* Y Z Z
* ^ B-------C ^ B-------C ^ B-------C
* | / / | / / | / /
* | / / | / / | / /
* | A-------D | A-------D | A-------D
* +-------------->X +-------------->X +-------------->Y
* XY_SKEW_FACTOR XZ_SKEW_FACTOR YZ_SKEW_FACTOR
*/
//#define SKEW_CORRECTION
```
But, this requires a new firmware installation, the reader should investigate whether this is within the capabilities of the reader. |
17,853 | <p>I'm just learning how to use a 3D printer, I have an Anycubic Mega Zero 2.0.</p>
<p>When I start printing the PLA filament doesn't want to adhere very well. I have leveled it out and all of my corners on my test print adhere well. However, when I go to print anything besides the test print I get basically a small bead - it doesn't smooth flat. If I try and adjust from there it starts pushing all the material around.</p>
<p>This lack of adhesion and bead continue throughout the print making it flimsy. It's weird because it looks nice but it's not strong.</p>
<p><a href="https://i.stack.imgur.com/8CAGr.jpg" rel="nofollow noreferrer" title="Print on bed"><img src="https://i.stack.imgur.com/8CAGr.jpg" alt="Print on bed" title="Print on bed" /></a></p>
<p><a href="https://i.stack.imgur.com/XIqlp.jpg" rel="nofollow noreferrer" title="Flimsy printed filament"><img src="https://i.stack.imgur.com/XIqlp.jpg" alt="Flimsy printed filament" title="Flimsy printed filament" /></a></p>
<p><a href="https://i.stack.imgur.com/HfpdH.jpg" rel="nofollow noreferrer" title="Finished print"><img src="https://i.stack.imgur.com/HfpdH.jpg" alt="Finished print" title="Finished print" /></a></p>
<p><a href="https://i.stack.imgur.com/R6PeV.jpg" rel="nofollow noreferrer" title="Base of finished print"><img src="https://i.stack.imgur.com/R6PeV.jpg" alt="Base of finished print" title="Base of finished print" /></a></p>
| [
{
"answer_id": 17854,
"author": "0scar",
"author_id": 5740,
"author_profile": "https://3dprinting.stackexchange.com/users/5740",
"pm_score": 2,
"selected": false,
"text": "<p>If you look at the multiple lines of the skirt, you see that none of the printed lines are touching the other laid down lines. This is an indication for under extrusion or a too large of a gap between the nozzle and the bed (or both). Considering you are talking about a bead/drop/blob of hot filament not adhering to the bed, this might be a good indication for a too large of a distance, if the gap is too large, the filament will not adhere to the bed and forms a blob. You could consider decreasing the gap by leveling with a thinner piece of paper or feeler gauge first. An alternative that might be quick to test is to re-define the bed height prior to printing using a plug-in in Ultimaker Cura or manually inserted in your G-code file. E.g. in you start code, add a move to a certain height and define that to a different height:</p>\n<pre><code>G1 Z0.2 ; move printer head to 0.2 mm height\nG92 Z0.24 ; re-define 0.2 to 0.24 mm, if the first layer prints at e.g. 0.2 mm,\n ; the printer will move down 0.04 mm\n</code></pre>\n<p>The images aren't very sharp, but, from one of the top layers it looks like you are indeed suffering from under extrusion. First, check if the filament can unwind freely without too much force from the spool. Second, under extrusion should be fixed by <a href=\"https://3dprinting.stackexchange.com/a/6484/5740\">adjusting the steps per millimeter value</a>. Beware, a new printer should have the correct value already inserted in the firmware, you should definitely check the filament path for obstructions first.</p>\n<p>A glass bed should be pretty flat, but it has been reported that there are glass manufacturers that produce low quality glass beds with dents. If so, you could shim the middle of the heated bed. An alternative is to flash new firmware and mesh the glass bed and the printer will automatically adjust for the height; this is not recommended for beginners.</p>\n<p>You could also increase the temperature of the bed, PLA can be printed on a cold prepared bed, but works very well on beds at 50-60 °C. You could consider using an adhesive on the glass as well, certain hairsprays, certain glue sticks, and special adhesive print sprays like 3DLAC work very well.</p>\n<p>Last but not least, incorrect filament diameter can cause under extrusion, older versions of Cura are notorious for resetting the filament diameter to 2.85 mm when you need e.g. 1.75 mm.</p>\n"
},
{
"answer_id": 17868,
"author": "Kezat",
"author_id": 30645,
"author_profile": "https://3dprinting.stackexchange.com/users/30645",
"pm_score": 1,
"selected": false,
"text": "<p>This looks exactly like you are extruding less plastic then you should be. Gaps can be seen on the top "solid" infill layer and even more telling is the gaps from one perimeter loop to the other. Suffering from weak prints is another indication of this. (or low extruder temps)</p>\n<p>You may find solving the under extrusion issue goes a long way to assist with the bed adhesion issues you are having. I would recommend you first solve that and then see if the bed adhesion issue is still present. At the very least it should make is easier to dial in the bed adhesion.</p>\n<p>If any slicer changes or tuning was done a quick and easy sanity check would be to download and run a print with known good profiles for your model of printer. It's easy to chase and tune for one issue and unknowingly create another that shows up at a later time in a different print, especially if you are new to 3d printing. (ask me how I know)</p>\n"
},
{
"answer_id": 18106,
"author": "Uwe",
"author_id": 29373,
"author_profile": "https://3dprinting.stackexchange.com/users/29373",
"pm_score": 0,
"selected": false,
"text": "<p>If the print bed is contaminated with oil or fat, print bed adhesion may be too low. Cleaning with alcohol might help.</p>\n"
}
] | 2021/08/05 | [
"https://3dprinting.stackexchange.com/questions/17853",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/30634/"
] | I'm just learning how to use a 3D printer, I have an Anycubic Mega Zero 2.0.
When I start printing the PLA filament doesn't want to adhere very well. I have leveled it out and all of my corners on my test print adhere well. However, when I go to print anything besides the test print I get basically a small bead - it doesn't smooth flat. If I try and adjust from there it starts pushing all the material around.
This lack of adhesion and bead continue throughout the print making it flimsy. It's weird because it looks nice but it's not strong.
[![Print on bed](https://i.stack.imgur.com/8CAGr.jpg "Print on bed")](https://i.stack.imgur.com/8CAGr.jpg "Print on bed")
[![Flimsy printed filament](https://i.stack.imgur.com/XIqlp.jpg "Flimsy printed filament")](https://i.stack.imgur.com/XIqlp.jpg "Flimsy printed filament")
[![Finished print](https://i.stack.imgur.com/HfpdH.jpg "Finished print")](https://i.stack.imgur.com/HfpdH.jpg "Finished print")
[![Base of finished print](https://i.stack.imgur.com/R6PeV.jpg "Base of finished print")](https://i.stack.imgur.com/R6PeV.jpg "Base of finished print") | If you look at the multiple lines of the skirt, you see that none of the printed lines are touching the other laid down lines. This is an indication for under extrusion or a too large of a gap between the nozzle and the bed (or both). Considering you are talking about a bead/drop/blob of hot filament not adhering to the bed, this might be a good indication for a too large of a distance, if the gap is too large, the filament will not adhere to the bed and forms a blob. You could consider decreasing the gap by leveling with a thinner piece of paper or feeler gauge first. An alternative that might be quick to test is to re-define the bed height prior to printing using a plug-in in Ultimaker Cura or manually inserted in your G-code file. E.g. in you start code, add a move to a certain height and define that to a different height:
```
G1 Z0.2 ; move printer head to 0.2 mm height
G92 Z0.24 ; re-define 0.2 to 0.24 mm, if the first layer prints at e.g. 0.2 mm,
; the printer will move down 0.04 mm
```
The images aren't very sharp, but, from one of the top layers it looks like you are indeed suffering from under extrusion. First, check if the filament can unwind freely without too much force from the spool. Second, under extrusion should be fixed by [adjusting the steps per millimeter value](https://3dprinting.stackexchange.com/a/6484/5740). Beware, a new printer should have the correct value already inserted in the firmware, you should definitely check the filament path for obstructions first.
A glass bed should be pretty flat, but it has been reported that there are glass manufacturers that produce low quality glass beds with dents. If so, you could shim the middle of the heated bed. An alternative is to flash new firmware and mesh the glass bed and the printer will automatically adjust for the height; this is not recommended for beginners.
You could also increase the temperature of the bed, PLA can be printed on a cold prepared bed, but works very well on beds at 50-60 °C. You could consider using an adhesive on the glass as well, certain hairsprays, certain glue sticks, and special adhesive print sprays like 3DLAC work very well.
Last but not least, incorrect filament diameter can cause under extrusion, older versions of Cura are notorious for resetting the filament diameter to 2.85 mm when you need e.g. 1.75 mm. |
18,135 | <p>I'm trying to 3D print a lattice work or truss, basically some beams forming a rectangle and additional beams forming the diagonals and where those beams cross, they should be fused. So, something like this:</p>
<p><a href="https://i.stack.imgur.com/gdKj1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gdKj1.jpg" alt="simple lattice" /></a></p>
<p>The problem is that any slicer I give a form like this to starts drawing triangles around the inner openings and in best case those triangles then touch if you use enough walls, but the pull strength you would get from beams in such a truss is lost because the opposite corners of the rectangle are not connected by a single length of filament laid down. Here as example what PrusaSlicer does for every layer:</p>
<p><a href="https://i.stack.imgur.com/dpkQW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dpkQW.jpg" alt="enter image description here" /></a></p>
<p>Basically this gives separate triangles at the top, bottom, left and right with some rectangular walls at the outside. Not bad, but I think that for extra strength it would be better if on even layers there would be long extrusions going all the way from the top-left corner to the bottom-right corner (and hence interrupting extrusion on the other diagonal) and on odd layers having just the opposite (so long extrusions from bottom-left to top-right).</p>
<p>So, my question: is there any way to tell the slicer to do something like that? So, having extra long (alternating) corner to corner extrusions next to the triangular "outer" walls that it normally puts down? Or, is there some other trick I could use to get a similar effect (while also having long extrusions between adjacent corners)?</p>
| [
{
"answer_id": 18136,
"author": "fred_dot_u",
"author_id": 854,
"author_profile": "https://3dprinting.stackexchange.com/users/854",
"pm_score": 1,
"selected": false,
"text": "<p>If on even layers, the routing is in one direction and on odd layers, the routing is the opposite diagonal, you'll have a much weaker structure, as there will be no material after the crossing point.</p>\n<p>Addressing that aspect, one could consider that the design is implemented in such a way that the nozzle creates the odd layer continuously from one corner to the other and then creates the "missing" segments from corner to center on the opposite diagonal.</p>\n<p>I know of no slicer which will create such tool paths from a model imported to the workspace.</p>\n<p>This leaves a relatively impractical option of creating the g-code manually. One of my clients is a machinist from the 50s who can look at an engineering drawing and hand-write the g-code for the machine center on which the part is to be created. Of course, that's not additive manufacture, it's the reverse and the cutting tool can remove far more material than a 3D printer can add.</p>\n<p>It's not an impossible task, but would be quite tedious. One might create a python code to generate appropriate g-code, given layer heights and machine-appropriate data such as speeds and temperatures, etc.</p>\n<p>Consider an <a href=\"https://www.youtube.com/watch?v=nRLJ4ylGTFc\" rel=\"nofollow noreferrer\">alternative post processing</a> specific to PETG, if PETG is an acceptable material for your project. One uses 100 percent infill in the model and then embeds the part in flour salt (finely ground salt), packing it in tightly. The salt-encased part is then re-melted. The part becomes "non-layered" removing the objections in the original reference. If you consider this method, some experimentation is indicated.</p>\n<p>The above link is a six minute YouTube video showing the process for multiple models, one after the other. PLA is shown with possibly poor results compared to PETG, hence the reference to experimentation.</p>\n"
},
{
"answer_id": 18147,
"author": "Perry Webb",
"author_id": 15075,
"author_profile": "https://3dprinting.stackexchange.com/users/15075",
"pm_score": 1,
"selected": false,
"text": "<p>The way I get rid of voids, like your triangular shaped voids the slicing program interprets as fill area, is to increase the number of vertical/perimeter shells (the shells on the side).</p>\n<p><a href=\"https://i.stack.imgur.com/bbUdP.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bbUdP.jpg\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 18149,
"author": "0scar",
"author_id": 5740,
"author_profile": "https://3dprinting.stackexchange.com/users/5740",
"pm_score": 3,
"selected": true,
"text": "<h2>Yes you can!</h2>\n<p>To have stronger prints you would have to choose the correct direction of filament deposition paths/traces. This answer demonstrates changing the direction of the filament path in Ultimaker Cura slicer.</p>\n<p>To do this, it requires some tinkering of your model and choosing the correct slicer parameters (decimals aren't allowed in changing the direction in Cura, only integer or round-off degrees).</p>\n<p>To recreate the experiment I have created a similar model in <a href=\"https://openscad.org/\" rel=\"nofollow noreferrer\">OpenSCAD</a>:</p>\n<pre><code>union(){\n difference(){\n cube([100, 50, 1],center = true); // outer contour\n cube([90, 40, 1.1],center = true); // inner contour\n }\n // add 2 cross beams\n for (i=[-1:2:1]) {\n // Note:\n // 26.565051177078 would have been exactly corner to corner, but \n // decimals aren't allowed in Cura, hence the choice for 26 degrees\n rotate([0,0,i*26]){ \n cube([100, 5, 1],center = true);\n }\n }\n}\n</code></pre>\n<p>Which gives you:\n<a href=\"https://i.stack.imgur.com/F527k.png\" rel=\"nofollow noreferrer\" title=\"Rectangle with cross beams\"><img src=\"https://i.stack.imgur.com/F527k.png\" alt=\"Rectangle with cross beams\" title=\"Rectangle with cross beams\" /></a></p>\n<p>Create an STL from the code and load this into Ultimaker Cura slicer.</p>\n<p>The trick is to direct the deposition of the top/bottom pattern [<code>lines</code>] and the infill [<code>lines</code>] in the direction you need (and for infill a high infill percentage). Remember the 26° angle of the cross beams, the definition of Cura line direction is different, so the angle of deposition needs to be ±(90 - 26) = ±64° which is denoted as [64, -64] in the slicer. Note the top and bottom contain 2 layers, the rest is infill. You can also have no infill by selecting very large top/bottom thickness, or, no top/bottom layers and only infill (this answer demonstrates <strong>both options</strong>, but you could choose just one).</p>\n<p>Look at the bottom layer (see slicer settings on the right):\n<a href=\"https://i.stack.imgur.com/72Gbu.png\" rel=\"nofollow noreferrer\" title=\"Bottom layer\"><img src=\"https://i.stack.imgur.com/72Gbu.png\" alt=\"Bottom layer\" title=\"Bottom layer\" /></a></p>\n<p>The second layer looks like:\n<a href=\"https://i.stack.imgur.com/XfdHA.png\" rel=\"nofollow noreferrer\" title=\"Second layer\"><img src=\"https://i.stack.imgur.com/XfdHA.png\" alt=\"Second layer\" title=\"Second layer\" /></a></p>\n<p>First infill layer:\n<a href=\"https://i.stack.imgur.com/yY10h.png\" rel=\"nofollow noreferrer\" title=\"First infill layer\"><img src=\"https://i.stack.imgur.com/yY10h.png\" alt=\"First infill layer\" title=\"First infill layer\" /></a></p>\n<p>Second infill layer (needed to lower the top layer to a single layer to be able to display this):\n<a href=\"https://i.stack.imgur.com/RbtzN.png\" rel=\"nofollow noreferrer\" title=\"Second infill layer (needed to lower the top layer to a single layer to be able to display this)\"><img src=\"https://i.stack.imgur.com/RbtzN.png\" alt=\"Second infill layer\" title=\"Second infill layer (needed to lower the top layer to a single layer to be able to display this)\" /></a></p>\n<p>As seen by the sliced layers, you can have an alternating pattern where the filament path is continuous for each cross-beam every other layer. This should increase the load (tension) the beam is able to support opposed to the given pattern in the question body.</p>\n"
},
{
"answer_id": 18157,
"author": "janherich",
"author_id": 31405,
"author_profile": "https://3dprinting.stackexchange.com/users/31405",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look at <a href=\"https://www.reddit.com/r/3Dprinting/comments/pt80ap/new_3d_printing_slicer_geared_towards_highspeed/\" rel=\"nofollow noreferrer\">Chisel</a> infills there are very strength optimised, limitation is currently that they must be single line width, but multiple-lines thick infill will be supported soon.\nAfter that, it's very simple, basically setting double corrugated infill with corrugation size 1 for your rectangle model.</p>\n"
}
] | 2021/09/25 | [
"https://3dprinting.stackexchange.com/questions/18135",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/31349/"
] | I'm trying to 3D print a lattice work or truss, basically some beams forming a rectangle and additional beams forming the diagonals and where those beams cross, they should be fused. So, something like this:
[![simple lattice](https://i.stack.imgur.com/gdKj1.jpg)](https://i.stack.imgur.com/gdKj1.jpg)
The problem is that any slicer I give a form like this to starts drawing triangles around the inner openings and in best case those triangles then touch if you use enough walls, but the pull strength you would get from beams in such a truss is lost because the opposite corners of the rectangle are not connected by a single length of filament laid down. Here as example what PrusaSlicer does for every layer:
[![enter image description here](https://i.stack.imgur.com/dpkQW.jpg)](https://i.stack.imgur.com/dpkQW.jpg)
Basically this gives separate triangles at the top, bottom, left and right with some rectangular walls at the outside. Not bad, but I think that for extra strength it would be better if on even layers there would be long extrusions going all the way from the top-left corner to the bottom-right corner (and hence interrupting extrusion on the other diagonal) and on odd layers having just the opposite (so long extrusions from bottom-left to top-right).
So, my question: is there any way to tell the slicer to do something like that? So, having extra long (alternating) corner to corner extrusions next to the triangular "outer" walls that it normally puts down? Or, is there some other trick I could use to get a similar effect (while also having long extrusions between adjacent corners)? | Yes you can!
------------
To have stronger prints you would have to choose the correct direction of filament deposition paths/traces. This answer demonstrates changing the direction of the filament path in Ultimaker Cura slicer.
To do this, it requires some tinkering of your model and choosing the correct slicer parameters (decimals aren't allowed in changing the direction in Cura, only integer or round-off degrees).
To recreate the experiment I have created a similar model in [OpenSCAD](https://openscad.org/):
```
union(){
difference(){
cube([100, 50, 1],center = true); // outer contour
cube([90, 40, 1.1],center = true); // inner contour
}
// add 2 cross beams
for (i=[-1:2:1]) {
// Note:
// 26.565051177078 would have been exactly corner to corner, but
// decimals aren't allowed in Cura, hence the choice for 26 degrees
rotate([0,0,i*26]){
cube([100, 5, 1],center = true);
}
}
}
```
Which gives you:
[![Rectangle with cross beams](https://i.stack.imgur.com/F527k.png "Rectangle with cross beams")](https://i.stack.imgur.com/F527k.png "Rectangle with cross beams")
Create an STL from the code and load this into Ultimaker Cura slicer.
The trick is to direct the deposition of the top/bottom pattern [`lines`] and the infill [`lines`] in the direction you need (and for infill a high infill percentage). Remember the 26° angle of the cross beams, the definition of Cura line direction is different, so the angle of deposition needs to be ±(90 - 26) = ±64° which is denoted as [64, -64] in the slicer. Note the top and bottom contain 2 layers, the rest is infill. You can also have no infill by selecting very large top/bottom thickness, or, no top/bottom layers and only infill (this answer demonstrates **both options**, but you could choose just one).
Look at the bottom layer (see slicer settings on the right):
[![Bottom layer](https://i.stack.imgur.com/72Gbu.png "Bottom layer")](https://i.stack.imgur.com/72Gbu.png "Bottom layer")
The second layer looks like:
[![Second layer](https://i.stack.imgur.com/XfdHA.png "Second layer")](https://i.stack.imgur.com/XfdHA.png "Second layer")
First infill layer:
[![First infill layer](https://i.stack.imgur.com/yY10h.png "First infill layer")](https://i.stack.imgur.com/yY10h.png "First infill layer")
Second infill layer (needed to lower the top layer to a single layer to be able to display this):
[![Second infill layer](https://i.stack.imgur.com/RbtzN.png "Second infill layer (needed to lower the top layer to a single layer to be able to display this)")](https://i.stack.imgur.com/RbtzN.png "Second infill layer (needed to lower the top layer to a single layer to be able to display this)")
As seen by the sliced layers, you can have an alternating pattern where the filament path is continuous for each cross-beam every other layer. This should increase the load (tension) the beam is able to support opposed to the given pattern in the question body. |
18,207 | <p>I bought an Ender 3 V2 printer and printed successfully with PLA and PLA+. Ender 3 V2 is rated at <= 250 °C but when I set temperature above 200 °C to print to PLA+, I get an error message "Nozzle is too lowperature" and the printer freezes (the term lowperature is actual and not a typo error).</p>
<p>I tried to raise the temperature gradually. I started at 200 °C and have gone to 205 °C and a little bit more. I started printing and I might get this message again or might not. Also, the temperature seems to change or lower while printing. It is not stable.</p>
<p>Any suggestions as to what causes this unstable behavior?</p>
<hr />
<p>Following the above behavior, I was able to raise the temperature to 213 °C and I was printing for 10 minutes or so, then I got the message "thermal runaway".</p>
<hr />
<p>I managed to capture the event <a href="https://youtu.be/oo0f237iTVo" rel="nofollow noreferrer">here</a></p>
| [
{
"answer_id": 18213,
"author": "Proxy303",
"author_id": 28485,
"author_profile": "https://3dprinting.stackexchange.com/users/28485",
"pm_score": 2,
"selected": false,
"text": "<p>This sounds like a bad thermistor. Try replacing the head thermistor, see if this fixes it.</p>\n<p>As for the strange error message, it looks like the word Temperature is being drawn on the wrong line, and then "is too low" writes over it.</p>\n<p>See the way the word lines up below:</p>\n<pre><code>nozzle temperature\nis too lowperature\n</code></pre>\n"
},
{
"answer_id": 18624,
"author": "thermike",
"author_id": 31470,
"author_profile": "https://3dprinting.stackexchange.com/users/31470",
"pm_score": 0,
"selected": false,
"text": "<p>The problem was solved after the supplier replaced the motherboard.\nHowever after that I had to try various versions of firmware as different ones had different behavior to the printer.\nIf you face a similar situation be aware of the cabling and connections when changing the motherboard. You may have to do the plugins twice to be sure that they are correctly attached.</p>\n"
}
] | 2021/10/06 | [
"https://3dprinting.stackexchange.com/questions/18207",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/31470/"
] | I bought an Ender 3 V2 printer and printed successfully with PLA and PLA+. Ender 3 V2 is rated at <= 250 °C but when I set temperature above 200 °C to print to PLA+, I get an error message "Nozzle is too lowperature" and the printer freezes (the term lowperature is actual and not a typo error).
I tried to raise the temperature gradually. I started at 200 °C and have gone to 205 °C and a little bit more. I started printing and I might get this message again or might not. Also, the temperature seems to change or lower while printing. It is not stable.
Any suggestions as to what causes this unstable behavior?
---
Following the above behavior, I was able to raise the temperature to 213 °C and I was printing for 10 minutes or so, then I got the message "thermal runaway".
---
I managed to capture the event [here](https://youtu.be/oo0f237iTVo) | This sounds like a bad thermistor. Try replacing the head thermistor, see if this fixes it.
As for the strange error message, it looks like the word Temperature is being drawn on the wrong line, and then "is too low" writes over it.
See the way the word lines up below:
```
nozzle temperature
is too lowperature
``` |
18,376 | <p>I am at a school with several Makerbot Replicator+ – a total of 9 of them.</p>
<p>So, they seem to print fine and I can hook up to two of them to one laptop (they are some Lenovo models from a few years back) using Makerbot Print. Well and good.</p>
<p>But I wanted to hook them up to my MacBook Pro (2020, OS X Catalina) with the USB cables, and the MacBook doesn't seem to "read" the printers, it's like they aren't even there. Makerbot Print (latest version) doesn't seem to "see" that they are hooked up. I checked the system prefs to see if the Makerbots showed up as connected USB devices and they don't seem to be there either.</p>
<p>Now, I am connecting via the USB cables and then through an adapter that connects the USB-A to USB-C. If I should just use a USB-B to USB-C cable (I ordered one to test it) then fine, I'll do that. I just wanted to check that there wasn't some other problem or if anyone else had this issue.</p>
<p>Next up: USB hubs. Makerbot says they don't recommend it, but sometimes I have to print out lots of stuff at once for student projects and I can't tie up multiple laptops for hours-long prints. I have done the technique of leaving stuff all night but that's hit or miss – if something goes wrong I am not there to stop the print (at least once something got unstuck from the build plate and I ended up with an extruder with the end encased in hard plastic like a stalactite. Unless I basically blowtorch it off... )</p>
<p>So, the question(s) is/are:</p>
<p>Any recommendations for USB hubs? (I would do wireless but that I am less sure of, and it seems easier, faster, and more reliable to link up through USB. The wireless connection always drops).</p>
<p>Any recommendations for the MacBook issue? Is it just a matter of finding the right cable? (it's certainly possible my $10 USB-A to USB-C adapter plugs aren't well designed, and I should just go for direct cabling)</p>
<p>Any recommendations for a good USB hub to link a Mac (or anything else) to Makerbots?</p>
<p>Thanks for your time and help. I do hope I am not duplicating a post but I don't see anything in my searches that addresses the specific issues I have; though it's possible I didn't use the right search terms.</p>
| [
{
"answer_id": 18377,
"author": "Greenonline",
"author_id": 4762,
"author_profile": "https://3dprinting.stackexchange.com/users/4762",
"pm_score": 3,
"selected": true,
"text": "<p><em><strong>It would seem that the printer control board doesn't use a CH340 (see bottom of this answer) and therefore this answer should be ignored.</strong></em></p>\n<hr />\n<h3>CH340 and OS X incompatibility</h3>\n<p>The reason your Mac might not see the printers <em>could</em> be down to the USB interface <em><strong>on the printer controller board</strong></em>.</p>\n<p>If it is implemented by a CH340 (which is probably is, in order to reduce manufacturing costs) then, historically, MacBooks have a problem with the drivers for this device and its derivatives. That is to say, the OS has a problem - more specifically the device drivers used by the OS X kernel - as opposed to the hardware. There are a number of posts dealing with this problem, it is common on Arduino clones too, see <a href=\"https://arduino.stackexchange.com/search?q=mac+ch340\">here</a>.</p>\n<p>The third party drivers for the CH340(G) written for OS X are often poorly written and/or have shoddy documentation - although this opinion may be hotly debated, and I have no wish to expand upon.</p>\n<p>If the USB interface, on the printer controller board, is implemented with an FTDI or a ATmega 16U2 then it will work fine. Unfortunately the solution is probably not to use the Mac and stick with the Lenovos (i.e. PC clone).</p>\n<p>See the extensive answers to <a href=\"https://3dprinting.stackexchange.com/q/6221/4762\">Can't connect Cura to my Anet A8 on OSX 10.11.6</a></p>\n<hr />\n<p>As an aside, I gave up trying to buy/use cheap Arduino clones with a CH340(G), on a Mac long along, as it just wasn't worth the effort in trying to get the Mac to see it. I now ensure that either:</p>\n<ul>\n<li>I purchase a slightly more expensive Arduino which uses a 16U2 (the more pricey FTDI chip is more rarely used on boards these days, but can still be found). Obviously, you don't have that sort of luxury when selecting a 3D printer.</li>\n<li>I will use a PC instead, if the board has a CH340(G), or similar.</li>\n</ul>\n<h3>One possible solution</h3>\n<p>However, having said all of that, this issue <strong>may</strong> have been resolved in newer versions of OS X (post Mountain Lion, or thereabouts). This <em>might</em> provide a solution, <a href=\"https://arduino.stackexchange.com/q/57126/6936\">Connect to ch340 on MacOS Mojave</a></p>\n<blockquote>\n<p>remove all old drivers:</p>\n<pre><code>sudo rm -rf /Library/Extensions/usbserial.kext\nsudo rm -rf /System/Library/Extensions/usb.kext\n</code></pre>\n<p>Now reboot the computer.</p>\n<p>And then (very important, because it took me 10 cables to find the\nright one) use a <strong>fully connected</strong> cable ;-)</p>\n<p>Now I have these ports:</p>\n<pre><code>/dev/cu.wchusbserial1410\n/dev/cu.usbserial-1410\n</code></pre>\n</blockquote>\n<p><strong>Important note</strong>: Clearly, deleting kernel drivers (also known as <em>kernel extensions</em>, <code>.kext</code>) shouldn't be taken lightly. If you feel uncomfortable doing it, or don't know how to revert the process, by using a saved backup of the drivers, then <em><strong>please don't attempt this</strong></em>.</p>\n<p>For completeness:</p>\n<ul>\n<li><p>To back up the <code>kext</code> (<em><strong>before</strong></em> deleting it as shown above):</p>\n<pre><code>sudo cp /Library/Extensions/usbserial.kext /Library/Extensions/usbserial.kext.bak\nsudo cp /System/Library/Extensions/usb.kext /System/Library/Extensions/usb.kext.bak\n</code></pre>\n</li>\n<li><p>To restore the <code>kext</code> (<em><strong>after</strong></em> having deleted the kernel extension and then finding that it made no difference whatsoever):</p>\n<pre><code>sudo mv /Library/Extensions/usbserial.kext.bak /Library/Extensions/usbserial.kext\nsudo mv /System/Library/Extensions/usb.kext.bak /System/Library/Extensions/usb.kext\n</code></pre>\n</li>\n</ul>\n<hr />\n<p>Alternatively, instead of <em>deleting</em> the kernel drivers, you could just <em>rename</em> them to hide them, by adding <code>.bak</code> to the filename, like so</p>\n<pre><code>sudo mv /Library/Extensions/usbserial.kext /Library/Extensions/usbserial.kext.bak\nsudo mv /System/Library/Extensions/usb.kext /System/Library/Extensions/usb.kext.bak\n</code></pre>\n<p>Then reboot. Check the printer connects or not. If not, then just <em>restore</em> them using the same commands shown above - so you just end up removing the additional <code>.bak</code> from the filename.</p>\n<hr />\n<p>With respect to the quoted answer, I'm not entirely sure what is meant by a <strong>fully connected</strong> cable... There <em>is</em> a well-known issue that some USB <em><strong>charging</strong></em> cables - that look like normal USB cables - have only the power lines connected, and omit the data lines (again for cheapness), and it can be difficult to tell the two apart (usually by thickness, the thicker cables have more lines connected). Obviously, if the data lines are missing then the cable will not transfer data.</p>\n<p><em>However</em>, this usually applies only to cables with mini, or micro USB connectors, and usually doesn't apply to standard peripheral cables such as a USB-A to USB-B cable:</p>\n<p><a href=\"https://i.stack.imgur.com/11mVl.png\" rel=\"nofollow noreferrer\" title=\"USB connectors\"><img src=\"https://i.stack.imgur.com/11mVl.png\" alt=\"USB connectors\" title=\"USB connectors\" /></a></p>\n<p>So, this issue should only arise for micro/mini USB connectors... it will depend upon your connector type.</p>\n<hr />\n<p>We can't recommend particular makes or models of USB hubs as that is a shopping question, which is <a href=\"https://3dprinting.stackexchange.com/help/on-topic\">off-topic</a>.</p>\n<hr />\n<h3>Analysis on the printer board</h3>\n<p>Makerbot appear to use the Mightyboard for the Replicator. INterestingly from the following two photos it would appear that a CH340(G) is <em><strong>not</strong></em> used, and the IC is in fact a 16U2.</p>\n<p>Here is a photo of the board (image from <a href=\"https://www.fargo3dprinting.com/products/makerbot-replicator-2-2x-rev-h-mightyboard-oem/\" rel=\"nofollow noreferrer\">MakerBot Replicator 2/2X Rev H Mightyboard – Official, OEM Board w/ 4 BotSteps</a>):</p>\n<p><a href=\"https://i.stack.imgur.com/AcMoE.jpg\" rel=\"nofollow noreferrer\" title=\"Photo of Mightboard\"><img src=\"https://i.stack.imgur.com/AcMoE.jpg\" alt=\"Photo of Mightboard\" title=\"Photo of Mightboard\" /></a></p>\n<p>The IC closest to the USB-B port would appear to be a 16U2:</p>\n<ul>\n<li>Its form is square like a 16U2 and not elongated like a CH340G</li>\n<li>It would appear to have an Atmel logo printed upon it.</li>\n</ul>\n<p>This image (from <a href=\"https://www.teknistore.com/en/3d-printer-module-board/19403-mightyboard-motherboard-3d-printer-dashboard.html?mobile_theme_ok\" rel=\"nofollow noreferrer\">MightyBoard Motherboard 3D Printer Dashboard</a>), also suggests the a 16U2 is used:</p>\n<p><a href=\"https://i.stack.imgur.com/DoO9c.jpg\" rel=\"nofollow noreferrer\" title=\"Annotated photo of MightBoard\"><img src=\"https://i.stack.imgur.com/DoO9c.jpg\" alt=\"Annotated photo of MightBoard\" title=\"Annotated photo of MightBoard\" /></a></p>\n<p>All of which means that, if your printer(s) have this board, then your Mac <em>should</em> indeed connect to the printer.</p>\n"
},
{
"answer_id": 18426,
"author": "Joel Coehoorn",
"author_id": 12562,
"author_profile": "https://3dprinting.stackexchange.com/users/12562",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p>what do you mean by SD card approach? The Makerbots take flash drives, but my attempts to print off of one were unsuccessful (it seems to be rather hard to make the right kind of file, it won't work with STLs and I gave up figuring out how to make them .makerbot files)</p>\n</blockquote>\n<p>This sounds like you need a better basic understanding of the printing process.</p>\n<p>An STL file describes a shape you want to print, but it does not have all the information needed to actually print the object. In order to actually print the file, you need to know things like what material you will use (which will determine temperatures), what the capabilities of the machine are (how fast you can go), how much vertical detail is important to retain (layer thickness vs print time trade-off), and how strong the piece needs to be (trade-off between infill + wall thickness vs print time + material costs). You also need to specify things like how to orient the shape for best print results and what to do when there are steep overhangs or bridges.</p>\n<p>To get this information, you must <strong>slice</strong> the STL (or OBJ or 3DS) file.</p>\n<p>There are a number of different software packages available to do slicing, many of them freely available: Cura and slic3r come to mind. Makerbot also has their own slicer. I know you can download and install Cura on a Mac.</p>\n<p>The output of the slicer is usually a <strong>.gcode</strong> file, and I would expect your Makerbots to be able to handle gcode files that were produced with the appropriate options. In fact, I strongly suspect the ".makerbot" file mentioned in your comment is actually a gcode file in disguise.</p>\n<p>Why does this matter?</p>\n<p>Print jobs can take hours and even days, and they tend to completely take over the computer while printing. No one wants to leave their laptop sitting next to a printer overnight, not able to do anything else. Newer printers will also have features like automatic resume from power loss, filament out detection, are more, that a are less likely to function properly when printing from a computer.</p>\n<p>There's just too much that can go wrong while printing via computer, such that <em>you're pretty much always better off going with the SD card or USB option.</em><sup>*</sup></p>\n<p>In other words, printing directly from your main computer is <strong>waaaaay</strong> down the list. It's not the first, second, or even third of fourth option as the best way to do this.</p>\n<hr />\n<p><sub>* A <em>dedicated</em> print station can work well, when setup properly, and people often use OctoPrint installed on a Raspberri Pi in this way. However, this also implies a high-end laptop is complete overkill for the task.</sub></p>\n"
}
] | 2021/11/15 | [
"https://3dprinting.stackexchange.com/questions/18376",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/31967/"
] | I am at a school with several Makerbot Replicator+ – a total of 9 of them.
So, they seem to print fine and I can hook up to two of them to one laptop (they are some Lenovo models from a few years back) using Makerbot Print. Well and good.
But I wanted to hook them up to my MacBook Pro (2020, OS X Catalina) with the USB cables, and the MacBook doesn't seem to "read" the printers, it's like they aren't even there. Makerbot Print (latest version) doesn't seem to "see" that they are hooked up. I checked the system prefs to see if the Makerbots showed up as connected USB devices and they don't seem to be there either.
Now, I am connecting via the USB cables and then through an adapter that connects the USB-A to USB-C. If I should just use a USB-B to USB-C cable (I ordered one to test it) then fine, I'll do that. I just wanted to check that there wasn't some other problem or if anyone else had this issue.
Next up: USB hubs. Makerbot says they don't recommend it, but sometimes I have to print out lots of stuff at once for student projects and I can't tie up multiple laptops for hours-long prints. I have done the technique of leaving stuff all night but that's hit or miss – if something goes wrong I am not there to stop the print (at least once something got unstuck from the build plate and I ended up with an extruder with the end encased in hard plastic like a stalactite. Unless I basically blowtorch it off... )
So, the question(s) is/are:
Any recommendations for USB hubs? (I would do wireless but that I am less sure of, and it seems easier, faster, and more reliable to link up through USB. The wireless connection always drops).
Any recommendations for the MacBook issue? Is it just a matter of finding the right cable? (it's certainly possible my $10 USB-A to USB-C adapter plugs aren't well designed, and I should just go for direct cabling)
Any recommendations for a good USB hub to link a Mac (or anything else) to Makerbots?
Thanks for your time and help. I do hope I am not duplicating a post but I don't see anything in my searches that addresses the specific issues I have; though it's possible I didn't use the right search terms. | ***It would seem that the printer control board doesn't use a CH340 (see bottom of this answer) and therefore this answer should be ignored.***
---
### CH340 and OS X incompatibility
The reason your Mac might not see the printers *could* be down to the USB interface ***on the printer controller board***.
If it is implemented by a CH340 (which is probably is, in order to reduce manufacturing costs) then, historically, MacBooks have a problem with the drivers for this device and its derivatives. That is to say, the OS has a problem - more specifically the device drivers used by the OS X kernel - as opposed to the hardware. There are a number of posts dealing with this problem, it is common on Arduino clones too, see [here](https://arduino.stackexchange.com/search?q=mac+ch340).
The third party drivers for the CH340(G) written for OS X are often poorly written and/or have shoddy documentation - although this opinion may be hotly debated, and I have no wish to expand upon.
If the USB interface, on the printer controller board, is implemented with an FTDI or a ATmega 16U2 then it will work fine. Unfortunately the solution is probably not to use the Mac and stick with the Lenovos (i.e. PC clone).
See the extensive answers to [Can't connect Cura to my Anet A8 on OSX 10.11.6](https://3dprinting.stackexchange.com/q/6221/4762)
---
As an aside, I gave up trying to buy/use cheap Arduino clones with a CH340(G), on a Mac long along, as it just wasn't worth the effort in trying to get the Mac to see it. I now ensure that either:
* I purchase a slightly more expensive Arduino which uses a 16U2 (the more pricey FTDI chip is more rarely used on boards these days, but can still be found). Obviously, you don't have that sort of luxury when selecting a 3D printer.
* I will use a PC instead, if the board has a CH340(G), or similar.
### One possible solution
However, having said all of that, this issue **may** have been resolved in newer versions of OS X (post Mountain Lion, or thereabouts). This *might* provide a solution, [Connect to ch340 on MacOS Mojave](https://arduino.stackexchange.com/q/57126/6936)
>
> remove all old drivers:
>
>
>
> ```
> sudo rm -rf /Library/Extensions/usbserial.kext
> sudo rm -rf /System/Library/Extensions/usb.kext
>
> ```
>
> Now reboot the computer.
>
>
> And then (very important, because it took me 10 cables to find the
> right one) use a **fully connected** cable ;-)
>
>
> Now I have these ports:
>
>
>
> ```
> /dev/cu.wchusbserial1410
> /dev/cu.usbserial-1410
>
> ```
>
>
**Important note**: Clearly, deleting kernel drivers (also known as *kernel extensions*, `.kext`) shouldn't be taken lightly. If you feel uncomfortable doing it, or don't know how to revert the process, by using a saved backup of the drivers, then ***please don't attempt this***.
For completeness:
* To back up the `kext` (***before*** deleting it as shown above):
```
sudo cp /Library/Extensions/usbserial.kext /Library/Extensions/usbserial.kext.bak
sudo cp /System/Library/Extensions/usb.kext /System/Library/Extensions/usb.kext.bak
```
* To restore the `kext` (***after*** having deleted the kernel extension and then finding that it made no difference whatsoever):
```
sudo mv /Library/Extensions/usbserial.kext.bak /Library/Extensions/usbserial.kext
sudo mv /System/Library/Extensions/usb.kext.bak /System/Library/Extensions/usb.kext
```
---
Alternatively, instead of *deleting* the kernel drivers, you could just *rename* them to hide them, by adding `.bak` to the filename, like so
```
sudo mv /Library/Extensions/usbserial.kext /Library/Extensions/usbserial.kext.bak
sudo mv /System/Library/Extensions/usb.kext /System/Library/Extensions/usb.kext.bak
```
Then reboot. Check the printer connects or not. If not, then just *restore* them using the same commands shown above - so you just end up removing the additional `.bak` from the filename.
---
With respect to the quoted answer, I'm not entirely sure what is meant by a **fully connected** cable... There *is* a well-known issue that some USB ***charging*** cables - that look like normal USB cables - have only the power lines connected, and omit the data lines (again for cheapness), and it can be difficult to tell the two apart (usually by thickness, the thicker cables have more lines connected). Obviously, if the data lines are missing then the cable will not transfer data.
*However*, this usually applies only to cables with mini, or micro USB connectors, and usually doesn't apply to standard peripheral cables such as a USB-A to USB-B cable:
[![USB connectors](https://i.stack.imgur.com/11mVl.png "USB connectors")](https://i.stack.imgur.com/11mVl.png "USB connectors")
So, this issue should only arise for micro/mini USB connectors... it will depend upon your connector type.
---
We can't recommend particular makes or models of USB hubs as that is a shopping question, which is [off-topic](https://3dprinting.stackexchange.com/help/on-topic).
---
### Analysis on the printer board
Makerbot appear to use the Mightyboard for the Replicator. INterestingly from the following two photos it would appear that a CH340(G) is ***not*** used, and the IC is in fact a 16U2.
Here is a photo of the board (image from [MakerBot Replicator 2/2X Rev H Mightyboard – Official, OEM Board w/ 4 BotSteps](https://www.fargo3dprinting.com/products/makerbot-replicator-2-2x-rev-h-mightyboard-oem/)):
[![Photo of Mightboard](https://i.stack.imgur.com/AcMoE.jpg "Photo of Mightboard")](https://i.stack.imgur.com/AcMoE.jpg "Photo of Mightboard")
The IC closest to the USB-B port would appear to be a 16U2:
* Its form is square like a 16U2 and not elongated like a CH340G
* It would appear to have an Atmel logo printed upon it.
This image (from [MightyBoard Motherboard 3D Printer Dashboard](https://www.teknistore.com/en/3d-printer-module-board/19403-mightyboard-motherboard-3d-printer-dashboard.html?mobile_theme_ok)), also suggests the a 16U2 is used:
[![Annotated photo of MightBoard](https://i.stack.imgur.com/DoO9c.jpg "Annotated photo of MightBoard")](https://i.stack.imgur.com/DoO9c.jpg "Annotated photo of MightBoard")
All of which means that, if your printer(s) have this board, then your Mac *should* indeed connect to the printer. |
18,567 | <p>I have a new Creality Ender 2 Pro with a Creality 4.2.3 mainboard. I'm attempting to compile Marlin to fix a bug. How can I tell what driver chips I have on this board?</p>
<p>I've narrowed it down to likely <code>A4988</code> or <code>TMC2208_STANDALONE</code> or possibly the <code>TMC2225</code>. Strangely Creality only has documentation for the 4.2.2 and the 4.2.7 boards (not 4.2.3)</p>
<p>4.2.2 => TMC2208<br />
4.2.3 => ?<br />
4.2.7 => TMC2225</p>
<p>Some say you can tell the driver just by listening to the noise it makes. <a href="https://youtu.be/4hL-r02w6rM" rel="nofollow noreferrer">Here is a video of the printer running</a>. The motors are nearly silent to my ear.</p>
<p><a href="https://i.stack.imgur.com/ALHyb.jpg" rel="nofollow noreferrer" title="Photo of Ender 2 Pro motherboard version 4.2.3"><img src="https://i.stack.imgur.com/ALHyb.jpg" alt="Photo of Ender 2 Pro motherboard version 4.2.3" title="Photo of Ender 2 Pro motherboard version 4.2.3" /></a></p>
<p><a href="https://i.stack.imgur.com/xUdVU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xUdVU.jpg" alt="Top corner photo" /></a></p>
<p>Resources</p>
<ul>
<li><a href="https://github.com/Creality3DPrinting/Ender-3/issues/58#issuecomment-842935869" rel="nofollow noreferrer">https://github.com/Creality3DPrinting/Ender-3/issues/58#issuecomment-842935869</a></li>
<li>4.2.2 <a href="https://github-repository-files.githubusercontent.com/139231738/7626788?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20211215%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20211215T153407Z&X-Amz-Expires=300&X-Amz-Signature=43dfe1ff5518c5003cf55ade1554caeb5953c733a599db07fb153cc976cebb45&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=139231738&response-content-disposition=attachment%3Bfilename%3D1623133432-Creality422-Schematic-2.pdf&response-content-type=application%2Fpdf" rel="nofollow noreferrer">schematic</a></li>
<li><a href="https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382" rel="nofollow noreferrer">Marlin Config pull request</a></li>
</ul>
| [
{
"answer_id": 18570,
"author": "spuder",
"author_id": 28932,
"author_profile": "https://3dprinting.stackexchange.com/users/28932",
"pm_score": 3,
"selected": true,
"text": "<p>According to <a href=\"https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382\" rel=\"nofollow noreferrer\">'The-EG' comment</a> in this GitHub issue, <a href=\"https://github.com/MarlinFirmware/Configurations/pull/633\" rel=\"nofollow noreferrer\">Add Creality Ender 2 Pro config #633</a>, you can often determine the stepper drivers by one of a few ways:</p>\n<ol>\n<li><p>Listen to the sound. The 'TMC22**' will sound much quieter</p>\n</li>\n<li><p>Look for a marking in Sharpie on the SD Card reader</p>\n<pre><code>C = HR4998\nE = A4988\nA = TMC2208\nB = TMC2209\nH = TMC2225\n</code></pre>\n</li>\n<li><p>Remove the heat sync</p>\n<p><a href=\"https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295\" rel=\"nofollow noreferrer\">https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295</a></p>\n<p>After removing the heat sync, it appears that the Chip is actually a <code>MS35775</code></p>\n<p><a href=\"https://i.stack.imgur.com/0o5mK.jpg\" rel=\"nofollow noreferrer\" title=\"Closeup of MS35775 on board\"><img src=\"https://i.stack.imgur.com/0o5mK.jpg\" alt=\"Closeup of MS35775 on board\" title=\"Closeup of MS35775 on board\" /></a></p>\n</li>\n</ol>\n"
},
{
"answer_id": 18728,
"author": "vimaana",
"author_id": 32660,
"author_profile": "https://3dprinting.stackexchange.com/users/32660",
"pm_score": 1,
"selected": false,
"text": "<p>MS35775 appears to be TMC208 compatible. You can find the data sheet on relmon.com here is the overview:</p>\n<ul>\n<li>2-Phase stepping motor peak current of 2A</li>\n<li>Step / dir interface 2, 4, 8, 16, or 32 microstep</li>\n<li>Internal 256 micro steps</li>\n<li>Quiet mode</li>\n<li>Fast mode</li>\n<li>HS Rdson 0.29 Ω ,LS Rdson 0.28 Ω</li>\n<li>Voltage range 4.75 ~ 36V</li>\n<li>When the motor is still, it will enter into the power saving mode automatically</li>\n<li>Internal resistor mode is optional (no need for external sense resistor)</li>\n<li>Single wire UART bus and OTP control</li>\n<li>QFN28 package</li>\n</ul>\n"
}
] | 2021/12/15 | [
"https://3dprinting.stackexchange.com/questions/18567",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/28932/"
] | I have a new Creality Ender 2 Pro with a Creality 4.2.3 mainboard. I'm attempting to compile Marlin to fix a bug. How can I tell what driver chips I have on this board?
I've narrowed it down to likely `A4988` or `TMC2208_STANDALONE` or possibly the `TMC2225`. Strangely Creality only has documentation for the 4.2.2 and the 4.2.7 boards (not 4.2.3)
4.2.2 => TMC2208
4.2.3 => ?
4.2.7 => TMC2225
Some say you can tell the driver just by listening to the noise it makes. [Here is a video of the printer running](https://youtu.be/4hL-r02w6rM). The motors are nearly silent to my ear.
[![Photo of Ender 2 Pro motherboard version 4.2.3](https://i.stack.imgur.com/ALHyb.jpg "Photo of Ender 2 Pro motherboard version 4.2.3")](https://i.stack.imgur.com/ALHyb.jpg "Photo of Ender 2 Pro motherboard version 4.2.3")
[![Top corner photo](https://i.stack.imgur.com/xUdVU.jpg)](https://i.stack.imgur.com/xUdVU.jpg)
Resources
* <https://github.com/Creality3DPrinting/Ender-3/issues/58#issuecomment-842935869>
* 4.2.2 [schematic](https://github-repository-files.githubusercontent.com/139231738/7626788?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20211215%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20211215T153407Z&X-Amz-Expires=300&X-Amz-Signature=43dfe1ff5518c5003cf55ade1554caeb5953c733a599db07fb153cc976cebb45&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=139231738&response-content-disposition=attachment%3Bfilename%3D1623133432-Creality422-Schematic-2.pdf&response-content-type=application%2Fpdf)
* [Marlin Config pull request](https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382) | According to ['The-EG' comment](https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382) in this GitHub issue, [Add Creality Ender 2 Pro config #633](https://github.com/MarlinFirmware/Configurations/pull/633), you can often determine the stepper drivers by one of a few ways:
1. Listen to the sound. The 'TMC22\*\*' will sound much quieter
2. Look for a marking in Sharpie on the SD Card reader
```
C = HR4998
E = A4988
A = TMC2208
B = TMC2209
H = TMC2225
```
3. Remove the heat sync
<https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295>
After removing the heat sync, it appears that the Chip is actually a `MS35775`
[![Closeup of MS35775 on board](https://i.stack.imgur.com/0o5mK.jpg "Closeup of MS35775 on board")](https://i.stack.imgur.com/0o5mK.jpg "Closeup of MS35775 on board") |
18,568 | <p>Why do concrete 3D printers lay the concrete in a zigzag shape? I know pouring it in a straight line makes it unstable, but the zigzag shape reduces the contact of the top layer to the layer below. What is the advantage?</p>
| [
{
"answer_id": 18570,
"author": "spuder",
"author_id": 28932,
"author_profile": "https://3dprinting.stackexchange.com/users/28932",
"pm_score": 3,
"selected": true,
"text": "<p>According to <a href=\"https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382\" rel=\"nofollow noreferrer\">'The-EG' comment</a> in this GitHub issue, <a href=\"https://github.com/MarlinFirmware/Configurations/pull/633\" rel=\"nofollow noreferrer\">Add Creality Ender 2 Pro config #633</a>, you can often determine the stepper drivers by one of a few ways:</p>\n<ol>\n<li><p>Listen to the sound. The 'TMC22**' will sound much quieter</p>\n</li>\n<li><p>Look for a marking in Sharpie on the SD Card reader</p>\n<pre><code>C = HR4998\nE = A4988\nA = TMC2208\nB = TMC2209\nH = TMC2225\n</code></pre>\n</li>\n<li><p>Remove the heat sync</p>\n<p><a href=\"https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295\" rel=\"nofollow noreferrer\">https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295</a></p>\n<p>After removing the heat sync, it appears that the Chip is actually a <code>MS35775</code></p>\n<p><a href=\"https://i.stack.imgur.com/0o5mK.jpg\" rel=\"nofollow noreferrer\" title=\"Closeup of MS35775 on board\"><img src=\"https://i.stack.imgur.com/0o5mK.jpg\" alt=\"Closeup of MS35775 on board\" title=\"Closeup of MS35775 on board\" /></a></p>\n</li>\n</ol>\n"
},
{
"answer_id": 18728,
"author": "vimaana",
"author_id": 32660,
"author_profile": "https://3dprinting.stackexchange.com/users/32660",
"pm_score": 1,
"selected": false,
"text": "<p>MS35775 appears to be TMC208 compatible. You can find the data sheet on relmon.com here is the overview:</p>\n<ul>\n<li>2-Phase stepping motor peak current of 2A</li>\n<li>Step / dir interface 2, 4, 8, 16, or 32 microstep</li>\n<li>Internal 256 micro steps</li>\n<li>Quiet mode</li>\n<li>Fast mode</li>\n<li>HS Rdson 0.29 Ω ,LS Rdson 0.28 Ω</li>\n<li>Voltage range 4.75 ~ 36V</li>\n<li>When the motor is still, it will enter into the power saving mode automatically</li>\n<li>Internal resistor mode is optional (no need for external sense resistor)</li>\n<li>Single wire UART bus and OTP control</li>\n<li>QFN28 package</li>\n</ul>\n"
}
] | 2021/12/15 | [
"https://3dprinting.stackexchange.com/questions/18568",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/32308/"
] | Why do concrete 3D printers lay the concrete in a zigzag shape? I know pouring it in a straight line makes it unstable, but the zigzag shape reduces the contact of the top layer to the layer below. What is the advantage? | According to ['The-EG' comment](https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382) in this GitHub issue, [Add Creality Ender 2 Pro config #633](https://github.com/MarlinFirmware/Configurations/pull/633), you can often determine the stepper drivers by one of a few ways:
1. Listen to the sound. The 'TMC22\*\*' will sound much quieter
2. Look for a marking in Sharpie on the SD Card reader
```
C = HR4998
E = A4988
A = TMC2208
B = TMC2209
H = TMC2225
```
3. Remove the heat sync
<https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295>
After removing the heat sync, it appears that the Chip is actually a `MS35775`
[![Closeup of MS35775 on board](https://i.stack.imgur.com/0o5mK.jpg "Closeup of MS35775 on board")](https://i.stack.imgur.com/0o5mK.jpg "Closeup of MS35775 on board") |
18,575 | <p>It seems there are some missing lines on the outer wall on the Z-axis with my prints. I'm not able to pinpoint the problem. Does anyone have ideas about what might be wrong with my setup/settings?</p>
<p>Example:</p>
<p><a href="https://i.stack.imgur.com/3q1k3.jpg" rel="nofollow noreferrer" title="Printed model with printing errors highlighted"><img src="https://i.stack.imgur.com/3q1k3.jpg" alt="Printed model with printing errors highlighted" title="Printed model with printing errors highlighted" /></a></p>
<p>Here are some settings that I think are relevant:<br />
Printer: Ender 3 v1<br />
Filament: Das Filament<br />
Slicer: Cura</p>
<ul>
<li>Hotend temp: 215 °C</li>
<li>Layer height: 0.2 mm</li>
<li>Wall speed: 30 mm/s</li>
<li>Travel speed: 200 mm/s</li>
<li>Retraction distance: 6.5 mm</li>
<li>Combing mode: not in skin (Max comb: 30)</li>
</ul>
<p>Cheers</p>
| [
{
"answer_id": 18570,
"author": "spuder",
"author_id": 28932,
"author_profile": "https://3dprinting.stackexchange.com/users/28932",
"pm_score": 3,
"selected": true,
"text": "<p>According to <a href=\"https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382\" rel=\"nofollow noreferrer\">'The-EG' comment</a> in this GitHub issue, <a href=\"https://github.com/MarlinFirmware/Configurations/pull/633\" rel=\"nofollow noreferrer\">Add Creality Ender 2 Pro config #633</a>, you can often determine the stepper drivers by one of a few ways:</p>\n<ol>\n<li><p>Listen to the sound. The 'TMC22**' will sound much quieter</p>\n</li>\n<li><p>Look for a marking in Sharpie on the SD Card reader</p>\n<pre><code>C = HR4998\nE = A4988\nA = TMC2208\nB = TMC2209\nH = TMC2225\n</code></pre>\n</li>\n<li><p>Remove the heat sync</p>\n<p><a href=\"https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295\" rel=\"nofollow noreferrer\">https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295</a></p>\n<p>After removing the heat sync, it appears that the Chip is actually a <code>MS35775</code></p>\n<p><a href=\"https://i.stack.imgur.com/0o5mK.jpg\" rel=\"nofollow noreferrer\" title=\"Closeup of MS35775 on board\"><img src=\"https://i.stack.imgur.com/0o5mK.jpg\" alt=\"Closeup of MS35775 on board\" title=\"Closeup of MS35775 on board\" /></a></p>\n</li>\n</ol>\n"
},
{
"answer_id": 18728,
"author": "vimaana",
"author_id": 32660,
"author_profile": "https://3dprinting.stackexchange.com/users/32660",
"pm_score": 1,
"selected": false,
"text": "<p>MS35775 appears to be TMC208 compatible. You can find the data sheet on relmon.com here is the overview:</p>\n<ul>\n<li>2-Phase stepping motor peak current of 2A</li>\n<li>Step / dir interface 2, 4, 8, 16, or 32 microstep</li>\n<li>Internal 256 micro steps</li>\n<li>Quiet mode</li>\n<li>Fast mode</li>\n<li>HS Rdson 0.29 Ω ,LS Rdson 0.28 Ω</li>\n<li>Voltage range 4.75 ~ 36V</li>\n<li>When the motor is still, it will enter into the power saving mode automatically</li>\n<li>Internal resistor mode is optional (no need for external sense resistor)</li>\n<li>Single wire UART bus and OTP control</li>\n<li>QFN28 package</li>\n</ul>\n"
}
] | 2021/12/16 | [
"https://3dprinting.stackexchange.com/questions/18575",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/32326/"
] | It seems there are some missing lines on the outer wall on the Z-axis with my prints. I'm not able to pinpoint the problem. Does anyone have ideas about what might be wrong with my setup/settings?
Example:
[![Printed model with printing errors highlighted](https://i.stack.imgur.com/3q1k3.jpg "Printed model with printing errors highlighted")](https://i.stack.imgur.com/3q1k3.jpg "Printed model with printing errors highlighted")
Here are some settings that I think are relevant:
Printer: Ender 3 v1
Filament: Das Filament
Slicer: Cura
* Hotend temp: 215 °C
* Layer height: 0.2 mm
* Wall speed: 30 mm/s
* Travel speed: 200 mm/s
* Retraction distance: 6.5 mm
* Combing mode: not in skin (Max comb: 30)
Cheers | According to ['The-EG' comment](https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382) in this GitHub issue, [Add Creality Ender 2 Pro config #633](https://github.com/MarlinFirmware/Configurations/pull/633), you can often determine the stepper drivers by one of a few ways:
1. Listen to the sound. The 'TMC22\*\*' will sound much quieter
2. Look for a marking in Sharpie on the SD Card reader
```
C = HR4998
E = A4988
A = TMC2208
B = TMC2209
H = TMC2225
```
3. Remove the heat sync
<https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295>
After removing the heat sync, it appears that the Chip is actually a `MS35775`
[![Closeup of MS35775 on board](https://i.stack.imgur.com/0o5mK.jpg "Closeup of MS35775 on board")](https://i.stack.imgur.com/0o5mK.jpg "Closeup of MS35775 on board") |
18,587 | <p>I have an Ender 3 V1 with a glass Creality plate. I was having difficulty using manual levelling and my prints were struggling, so I ordered a 3DTouch. I have installed the 3DTouch and used Creality's BLTouch firmware. But my bed is still not level.</p>
<p>So my build is an Ender 3 V1 with:</p>
<ul>
<li>Extruder upgraded to all-metal extruder</li>
<li>Glass bed upgrade</li>
<li>3DTouch Upgrade</li>
<li>Capricorn Tubing</li>
<li>Yellow bed springs</li>
</ul>
<p>I manually levelled my bed using my 3DTouch. I used the <code>G30</code> command in <code>Pronterface</code> to probe each corner of the plate. At each corner, I would adjust the knob until the 3DTouch read 0.0. I did this iteratively multiple times until I thought it was reasonably level. The four corner values were something like 0.1, 0.0, -0.2, and 0.3 mm.</p>
<p>I have also put a straight edge with an Angle Finder Phone App. The bed is quite level. It reads 0, 1, or 2°
depending on how I place the level. X-axis gantry has a 1° tilt.</p>
<p>Here is my current bed levelling mesh:</p>
<p><a href="https://i.stack.imgur.com/kepvq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kepvq.png" alt="My mesh bed levelling result" /></a></p>
<p>After doing this, I added <code>G29</code> after <code>G28</code> in my starting G-Code in Cura. I sliced a model from Thingiverse that had 5 squares and some lines. Here are the results:</p>
<p><a href="https://i.stack.imgur.com/we8Sk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/we8Sk.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/XWZZB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XWZZB.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/ONbBq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ONbBq.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/h3aib.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h3aib.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/YBnku.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YBnku.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/O7gkY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O7gkY.jpg" alt="enter image description here" /></a></p>
<p>I am using:</p>
<ul>
<li>Filament : PLA</li>
<li>Bed Temp : 60 °C</li>
<li>Nozzle Temp : 200 °C</li>
</ul>
<p>Some miscellaneous notes:</p>
<ul>
<li>The bed was cleaned thoroughly prior to use</li>
<li>I rotated the bed 90° and the print looked the exact same way</li>
<li>I ensured that the bed soaked in some heat for some time prior to printing</li>
<li>I have set my Z offset to -1.800 mm</li>
<li>The frame and components seem to be square and tightened down. Nothing is shaking around and seems to be in order.</li>
</ul>
<p>I would really appreciate help on this. I'm really not sure what to do next. I've been really excited about 3D printing and I hope I can find a solution to this.</p>
<p><strong>Leveling using CHEP's video</strong></p>
<p>So I have rebuilt my 3D printer using CHEP's video. I noticed that one or two things were off compared to how it was supposed to be. I will be doing some test prints to see if that actually fixed things. I am hopeful.</p>
<p>I did a mesh before any other changes, and the slant is very clear now. See below. I believe one of the plates on the gantry wasn't completely straight.</p>
<p><a href="https://i.stack.imgur.com/XjTYg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XjTYg.png" alt="enter image description here" /></a></p>
<p><strong>Leveling after rebuilding printer</strong></p>
<p>Here is my latest mesh, after rebuilding the printer and then re-levelling its bed manually.</p>
<p><a href="https://i.stack.imgur.com/fn3G9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fn3G9.png" alt="enter image description here" /></a></p>
<p>These are the results of the print. I had to change my Z offset to -1.60 mm. The broken line is my fault. It was caused by my finger. The focus is the corners. As I mentioned, this is after rebuilding my printer.</p>
<p><a href="https://i.stack.imgur.com/JFJ6U.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JFJ6U.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/xyD3N.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xyD3N.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/P3fjP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P3fjP.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/b6IWZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b6IWZ.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/2oNF7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2oNF7.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/MR0WM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MR0WM.jpg" alt="enter image description here" /></a></p>
<p><strong>Edit</strong></p>
<p>I would like to have more probing points than Creality's 3x3 grid. To my understanding, Creality's source code is not available, and so I will be rolling my own with Marlin 2.0. I downloaded the latest Marlin from <a href="https://github.com/MarlinFirmware/Marlin/releases" rel="nofollow noreferrer">https://github.com/MarlinFirmware/Marlin/releases</a>, and copied the 4.2.2 Creality configuration from the default Configurations. I then changed the following:</p>
<ol>
<li>I ensured <code>#define PDITEMP</code> is not commented so that I can do PID tuning of the nozzle.</li>
<li>Similar to 1., I ensured that <code>#define PIDTEMPBED</code> is not commented so that I can do PID tuning of the bed.</li>
<li>I commented <code>#define Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN</code> since I will be using the 5-pin BLTouch port that is on my 4.2.2. board.</li>
<li>I uncommented <code>#define USE_PROBE_FOR_Z_HOMING</code> since I removed my z-axis endstop and want to use my 3DTouch as the z endstop.</li>
<li>Uncommented <code>#define BLTOUCH</code> since the 3DTouch is a BLTouch clone.</li>
<li>Changed my x and y offsets in the setting <code>#define NOZZLE_TO_PROBE_OFFSET { -42, -8, 0 }</code>. I left the z-offset 0, since I will be using the tuning tool to adjust that and observe the squish. For the x and y, I measured the distance between my probe and the nozzle using a digital caliper.</li>
<li>I adjusted the probe margin from 10 to 15, since I have clips that previously would interfere with the 3DTouch. 15 should give more distance. <code>#define PROBING_MARGIN 15</code></li>
<li>I enabled and set MULTIPLE_PROBING to 3. I'm paranoid about the current accuracy, and am willing to see if that improves anything at the expense of a few additional minutes. <code>#define MULTIPLE_PROBING 3</code>. I think 2 should be fine for general use.</li>
<li>Uncommented <code>#define Z_MIN_PROBE_REPEATABILITY_TEST</code>. I want to test my 3DTouch and uncommenting allows the use of M48 to test it.</li>
<li>Uncommented <code>#define PROBING_FANS_OFF</code>, <code>#define PROBING_ESTEPPERS_OFF</code>, <code>#define PROBING_STEPPERS_OFF</code>, <code>#define DELAY_BEFORE_PROBING 200</code>. The documentation this may improve probing results. I'm all in.</li>
<li>Uncommented <code>#define NO_MOTION_BEFORE_HOMING</code> and <code>#define HOME_AFTER_DEACTIVATE</code>.</li>
<li>Uncommented <code>#define AUTO_BED_LEVELING_BILINEAR</code></li>
<li>Uncommented <code>#define RESTORE_LEVELING_AFTER_G28</code>. This is to ensure the mesh is applied even after G28, which disables the mesh otherwise.</li>
<li>Ensures that this setting was 10. <code>#define DEFAULT_LEVELING_FADE_HEIGHT 10.0</code></li>
<li>I set the following : <code>#define GRID_MAX_POINTS_X 7</code>. Ensures a 7x7 mesh grid is created. This could be more or less. 49 points is an improvement over Creality's 9, although a bit much. Worthwhile in my case.</li>
<li>Uncommented <code>#define EXTRAPOLATE_BEYOND_GRID</code>. I was actually wondering if this was causing some of the inconsistent prints near the edge.</li>
<li>Uncommented <code>#define LCD_BED_LEVELING</code>. This is to unlock more options for ABL in the menu.</li>
<li>Uncommented <code>#define LEVEL_BED_CORNERS</code>. This should make moving between corners for manual levelling easier.</li>
<li>Uncommented <code>#define LEVEL_CORNERS_USE_PROBE</code>. This is to achieve exactly what I was doing with G30 in Pronterface. I changed to tolerance with <code>#define LEVEL_CORNERS_PROBE_TOLERANCE 0.03</code></li>
<li>Uncommented <code>#define Z_SAFE_HOMING</code>, which is important for the BLTouch.</li>
<li>Changed my PLA profile according to what I have determined to be best with <code>#define PREHEAT_1_TEMP_HOTEND 200</code> and <code>#define PREHEAT_1_TEMP_BED 60</code></li>
</ol>
<p>I had to comment <code>#define BLTOUCH_SET_5V_MODE</code> for things to compile. I also had to modify <code>#define LEVEL_CORNERS_INSET_LFRB { 30, 30, 45, 45 }</code>, due to the margin I set as well as the offset of my touch. Otherwise, the above configuration was fine, in terms of compilation.</p>
<p>I'll post back with the results.</p>
<p>Here are the results for the M48 3DTouch test. Are these values good?</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Measurement</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Mean</td>
<td>0.063667</td>
</tr>
<tr>
<td>Min</td>
<td>0.061</td>
</tr>
<tr>
<td>Max</td>
<td>0.068</td>
</tr>
<tr>
<td>Range</td>
<td>0.007</td>
</tr>
<tr>
<td>STD</td>
<td>0.002478</td>
</tr>
</tbody>
</table>
</div>
<p>I reduced the speed of the probing in half in order to make the probing more accurate. This was done by changing from <code>#define Z_PROBE_FEEDRATE_FAST (4*60)</code> to <code>#define Z_PROBE_FEEDRATE_FAST (2*60)</code>. I also made the mesh grid 8x8 because might as well.</p>
<p>These are my M48 repeatability results. Interesting to compare to the above table which probed at double the speed.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Measurement</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Mean</td>
<td>0.005500</td>
</tr>
<tr>
<td>Min</td>
<td>0.002</td>
</tr>
<tr>
<td>Max</td>
<td>0.010</td>
</tr>
<tr>
<td>Range</td>
<td>0.008</td>
</tr>
<tr>
<td>STD</td>
<td>0.001908</td>
</tr>
</tbody>
</table>
</div>
<p>I also changed the filament (brand new). Just as another variable to modify.</p>
<p>The following prints are the result.</p>
<p>The mesh before this print is as follows:</p>
<p><a href="https://i.stack.imgur.com/tk0TQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tk0TQ.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/MJAWB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MJAWB.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/v9LPr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v9LPr.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/JVV4Y.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JVV4Y.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/MndtV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MndtV.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/IE4eq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IE4eq.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/LY47R.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LY47R.jpg" alt="enter image description here" /></a></p>
<p><strong>Levelling the X-Axis Gantry</strong></p>
<p>As Oscar in the comments has mentioned, I have read some other forum posts that described the cause of uneven lines and similar inconsistencies as what I am noticing, as being due to the X-axis Gantry that moves up and down as not being level.</p>
<p>I used a digital caliper and measured the x axis gantry relative to the frame of the 3D printer. So for example, I put my caliper against the base metal extrusion and then against the x-axis gantry. I did this on both sides.</p>
<p>The side without the Z-Axis lead screw (right side) was above the side with the Z-Axis lead screw (left side) by about 1.7mm. I'm surprised that CHEP and some other build videos never mentioned to check this, but it does seem logical to consider. Making the brackets flush is NOT adequate. When I do make it flush, then one side is higher than the other. The build videos say to make it flush. This will make things OFF.</p>
<p>To adjust this, I took off the gantry, slightly loosened the bolts on both side plates, so that it was stiff enough that it wouldn't move easily, but could make subtle adjustments by twisting it hard enough. I then put the gantry back on the printer, did some measurements and corresponding adjustments. I then carefully threaded the gantry off and tightened the plates.</p>
<p>Currently, my left and right side have a difference of .17mm. I figured I won't get anything better by hand. I'll do another test print tonight. 1.7mm vs .17mm is a reasonable difference.</p>
| [
{
"answer_id": 18570,
"author": "spuder",
"author_id": 28932,
"author_profile": "https://3dprinting.stackexchange.com/users/28932",
"pm_score": 3,
"selected": true,
"text": "<p>According to <a href=\"https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382\" rel=\"nofollow noreferrer\">'The-EG' comment</a> in this GitHub issue, <a href=\"https://github.com/MarlinFirmware/Configurations/pull/633\" rel=\"nofollow noreferrer\">Add Creality Ender 2 Pro config #633</a>, you can often determine the stepper drivers by one of a few ways:</p>\n<ol>\n<li><p>Listen to the sound. The 'TMC22**' will sound much quieter</p>\n</li>\n<li><p>Look for a marking in Sharpie on the SD Card reader</p>\n<pre><code>C = HR4998\nE = A4988\nA = TMC2208\nB = TMC2209\nH = TMC2225\n</code></pre>\n</li>\n<li><p>Remove the heat sync</p>\n<p><a href=\"https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295\" rel=\"nofollow noreferrer\">https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295</a></p>\n<p>After removing the heat sync, it appears that the Chip is actually a <code>MS35775</code></p>\n<p><a href=\"https://i.stack.imgur.com/0o5mK.jpg\" rel=\"nofollow noreferrer\" title=\"Closeup of MS35775 on board\"><img src=\"https://i.stack.imgur.com/0o5mK.jpg\" alt=\"Closeup of MS35775 on board\" title=\"Closeup of MS35775 on board\" /></a></p>\n</li>\n</ol>\n"
},
{
"answer_id": 18728,
"author": "vimaana",
"author_id": 32660,
"author_profile": "https://3dprinting.stackexchange.com/users/32660",
"pm_score": 1,
"selected": false,
"text": "<p>MS35775 appears to be TMC208 compatible. You can find the data sheet on relmon.com here is the overview:</p>\n<ul>\n<li>2-Phase stepping motor peak current of 2A</li>\n<li>Step / dir interface 2, 4, 8, 16, or 32 microstep</li>\n<li>Internal 256 micro steps</li>\n<li>Quiet mode</li>\n<li>Fast mode</li>\n<li>HS Rdson 0.29 Ω ,LS Rdson 0.28 Ω</li>\n<li>Voltage range 4.75 ~ 36V</li>\n<li>When the motor is still, it will enter into the power saving mode automatically</li>\n<li>Internal resistor mode is optional (no need for external sense resistor)</li>\n<li>Single wire UART bus and OTP control</li>\n<li>QFN28 package</li>\n</ul>\n"
}
] | 2021/12/18 | [
"https://3dprinting.stackexchange.com/questions/18587",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/32347/"
] | I have an Ender 3 V1 with a glass Creality plate. I was having difficulty using manual levelling and my prints were struggling, so I ordered a 3DTouch. I have installed the 3DTouch and used Creality's BLTouch firmware. But my bed is still not level.
So my build is an Ender 3 V1 with:
* Extruder upgraded to all-metal extruder
* Glass bed upgrade
* 3DTouch Upgrade
* Capricorn Tubing
* Yellow bed springs
I manually levelled my bed using my 3DTouch. I used the `G30` command in `Pronterface` to probe each corner of the plate. At each corner, I would adjust the knob until the 3DTouch read 0.0. I did this iteratively multiple times until I thought it was reasonably level. The four corner values were something like 0.1, 0.0, -0.2, and 0.3 mm.
I have also put a straight edge with an Angle Finder Phone App. The bed is quite level. It reads 0, 1, or 2°
depending on how I place the level. X-axis gantry has a 1° tilt.
Here is my current bed levelling mesh:
[![My mesh bed levelling result](https://i.stack.imgur.com/kepvq.png)](https://i.stack.imgur.com/kepvq.png)
After doing this, I added `G29` after `G28` in my starting G-Code in Cura. I sliced a model from Thingiverse that had 5 squares and some lines. Here are the results:
[![enter image description here](https://i.stack.imgur.com/we8Sk.jpg)](https://i.stack.imgur.com/we8Sk.jpg)
[![enter image description here](https://i.stack.imgur.com/XWZZB.jpg)](https://i.stack.imgur.com/XWZZB.jpg)
[![enter image description here](https://i.stack.imgur.com/ONbBq.jpg)](https://i.stack.imgur.com/ONbBq.jpg)
[![enter image description here](https://i.stack.imgur.com/h3aib.jpg)](https://i.stack.imgur.com/h3aib.jpg)
[![enter image description here](https://i.stack.imgur.com/YBnku.jpg)](https://i.stack.imgur.com/YBnku.jpg)
[![enter image description here](https://i.stack.imgur.com/O7gkY.jpg)](https://i.stack.imgur.com/O7gkY.jpg)
I am using:
* Filament : PLA
* Bed Temp : 60 °C
* Nozzle Temp : 200 °C
Some miscellaneous notes:
* The bed was cleaned thoroughly prior to use
* I rotated the bed 90° and the print looked the exact same way
* I ensured that the bed soaked in some heat for some time prior to printing
* I have set my Z offset to -1.800 mm
* The frame and components seem to be square and tightened down. Nothing is shaking around and seems to be in order.
I would really appreciate help on this. I'm really not sure what to do next. I've been really excited about 3D printing and I hope I can find a solution to this.
**Leveling using CHEP's video**
So I have rebuilt my 3D printer using CHEP's video. I noticed that one or two things were off compared to how it was supposed to be. I will be doing some test prints to see if that actually fixed things. I am hopeful.
I did a mesh before any other changes, and the slant is very clear now. See below. I believe one of the plates on the gantry wasn't completely straight.
[![enter image description here](https://i.stack.imgur.com/XjTYg.png)](https://i.stack.imgur.com/XjTYg.png)
**Leveling after rebuilding printer**
Here is my latest mesh, after rebuilding the printer and then re-levelling its bed manually.
[![enter image description here](https://i.stack.imgur.com/fn3G9.png)](https://i.stack.imgur.com/fn3G9.png)
These are the results of the print. I had to change my Z offset to -1.60 mm. The broken line is my fault. It was caused by my finger. The focus is the corners. As I mentioned, this is after rebuilding my printer.
[![enter image description here](https://i.stack.imgur.com/JFJ6U.jpg)](https://i.stack.imgur.com/JFJ6U.jpg)
[![enter image description here](https://i.stack.imgur.com/xyD3N.jpg)](https://i.stack.imgur.com/xyD3N.jpg)
[![enter image description here](https://i.stack.imgur.com/P3fjP.jpg)](https://i.stack.imgur.com/P3fjP.jpg)
[![enter image description here](https://i.stack.imgur.com/b6IWZ.jpg)](https://i.stack.imgur.com/b6IWZ.jpg)
[![enter image description here](https://i.stack.imgur.com/2oNF7.jpg)](https://i.stack.imgur.com/2oNF7.jpg)
[![enter image description here](https://i.stack.imgur.com/MR0WM.jpg)](https://i.stack.imgur.com/MR0WM.jpg)
**Edit**
I would like to have more probing points than Creality's 3x3 grid. To my understanding, Creality's source code is not available, and so I will be rolling my own with Marlin 2.0. I downloaded the latest Marlin from <https://github.com/MarlinFirmware/Marlin/releases>, and copied the 4.2.2 Creality configuration from the default Configurations. I then changed the following:
1. I ensured `#define PDITEMP` is not commented so that I can do PID tuning of the nozzle.
2. Similar to 1., I ensured that `#define PIDTEMPBED` is not commented so that I can do PID tuning of the bed.
3. I commented `#define Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN` since I will be using the 5-pin BLTouch port that is on my 4.2.2. board.
4. I uncommented `#define USE_PROBE_FOR_Z_HOMING` since I removed my z-axis endstop and want to use my 3DTouch as the z endstop.
5. Uncommented `#define BLTOUCH` since the 3DTouch is a BLTouch clone.
6. Changed my x and y offsets in the setting `#define NOZZLE_TO_PROBE_OFFSET { -42, -8, 0 }`. I left the z-offset 0, since I will be using the tuning tool to adjust that and observe the squish. For the x and y, I measured the distance between my probe and the nozzle using a digital caliper.
7. I adjusted the probe margin from 10 to 15, since I have clips that previously would interfere with the 3DTouch. 15 should give more distance. `#define PROBING_MARGIN 15`
8. I enabled and set MULTIPLE\_PROBING to 3. I'm paranoid about the current accuracy, and am willing to see if that improves anything at the expense of a few additional minutes. `#define MULTIPLE_PROBING 3`. I think 2 should be fine for general use.
9. Uncommented `#define Z_MIN_PROBE_REPEATABILITY_TEST`. I want to test my 3DTouch and uncommenting allows the use of M48 to test it.
10. Uncommented `#define PROBING_FANS_OFF`, `#define PROBING_ESTEPPERS_OFF`, `#define PROBING_STEPPERS_OFF`, `#define DELAY_BEFORE_PROBING 200`. The documentation this may improve probing results. I'm all in.
11. Uncommented `#define NO_MOTION_BEFORE_HOMING` and `#define HOME_AFTER_DEACTIVATE`.
12. Uncommented `#define AUTO_BED_LEVELING_BILINEAR`
13. Uncommented `#define RESTORE_LEVELING_AFTER_G28`. This is to ensure the mesh is applied even after G28, which disables the mesh otherwise.
14. Ensures that this setting was 10. `#define DEFAULT_LEVELING_FADE_HEIGHT 10.0`
15. I set the following : `#define GRID_MAX_POINTS_X 7`. Ensures a 7x7 mesh grid is created. This could be more or less. 49 points is an improvement over Creality's 9, although a bit much. Worthwhile in my case.
16. Uncommented `#define EXTRAPOLATE_BEYOND_GRID`. I was actually wondering if this was causing some of the inconsistent prints near the edge.
17. Uncommented `#define LCD_BED_LEVELING`. This is to unlock more options for ABL in the menu.
18. Uncommented `#define LEVEL_BED_CORNERS`. This should make moving between corners for manual levelling easier.
19. Uncommented `#define LEVEL_CORNERS_USE_PROBE`. This is to achieve exactly what I was doing with G30 in Pronterface. I changed to tolerance with `#define LEVEL_CORNERS_PROBE_TOLERANCE 0.03`
20. Uncommented `#define Z_SAFE_HOMING`, which is important for the BLTouch.
21. Changed my PLA profile according to what I have determined to be best with `#define PREHEAT_1_TEMP_HOTEND 200` and `#define PREHEAT_1_TEMP_BED 60`
I had to comment `#define BLTOUCH_SET_5V_MODE` for things to compile. I also had to modify `#define LEVEL_CORNERS_INSET_LFRB { 30, 30, 45, 45 }`, due to the margin I set as well as the offset of my touch. Otherwise, the above configuration was fine, in terms of compilation.
I'll post back with the results.
Here are the results for the M48 3DTouch test. Are these values good?
| Measurement | Value |
| --- | --- |
| Mean | 0.063667 |
| Min | 0.061 |
| Max | 0.068 |
| Range | 0.007 |
| STD | 0.002478 |
I reduced the speed of the probing in half in order to make the probing more accurate. This was done by changing from `#define Z_PROBE_FEEDRATE_FAST (4*60)` to `#define Z_PROBE_FEEDRATE_FAST (2*60)`. I also made the mesh grid 8x8 because might as well.
These are my M48 repeatability results. Interesting to compare to the above table which probed at double the speed.
| Measurement | Value |
| --- | --- |
| Mean | 0.005500 |
| Min | 0.002 |
| Max | 0.010 |
| Range | 0.008 |
| STD | 0.001908 |
I also changed the filament (brand new). Just as another variable to modify.
The following prints are the result.
The mesh before this print is as follows:
[![enter image description here](https://i.stack.imgur.com/tk0TQ.png)](https://i.stack.imgur.com/tk0TQ.png)
[![enter image description here](https://i.stack.imgur.com/MJAWB.jpg)](https://i.stack.imgur.com/MJAWB.jpg)
[![enter image description here](https://i.stack.imgur.com/v9LPr.jpg)](https://i.stack.imgur.com/v9LPr.jpg)
[![enter image description here](https://i.stack.imgur.com/JVV4Y.jpg)](https://i.stack.imgur.com/JVV4Y.jpg)
[![enter image description here](https://i.stack.imgur.com/MndtV.jpg)](https://i.stack.imgur.com/MndtV.jpg)
[![enter image description here](https://i.stack.imgur.com/IE4eq.jpg)](https://i.stack.imgur.com/IE4eq.jpg)
[![enter image description here](https://i.stack.imgur.com/LY47R.jpg)](https://i.stack.imgur.com/LY47R.jpg)
**Levelling the X-Axis Gantry**
As Oscar in the comments has mentioned, I have read some other forum posts that described the cause of uneven lines and similar inconsistencies as what I am noticing, as being due to the X-axis Gantry that moves up and down as not being level.
I used a digital caliper and measured the x axis gantry relative to the frame of the 3D printer. So for example, I put my caliper against the base metal extrusion and then against the x-axis gantry. I did this on both sides.
The side without the Z-Axis lead screw (right side) was above the side with the Z-Axis lead screw (left side) by about 1.7mm. I'm surprised that CHEP and some other build videos never mentioned to check this, but it does seem logical to consider. Making the brackets flush is NOT adequate. When I do make it flush, then one side is higher than the other. The build videos say to make it flush. This will make things OFF.
To adjust this, I took off the gantry, slightly loosened the bolts on both side plates, so that it was stiff enough that it wouldn't move easily, but could make subtle adjustments by twisting it hard enough. I then put the gantry back on the printer, did some measurements and corresponding adjustments. I then carefully threaded the gantry off and tightened the plates.
Currently, my left and right side have a difference of .17mm. I figured I won't get anything better by hand. I'll do another test print tonight. 1.7mm vs .17mm is a reasonable difference. | According to ['The-EG' comment](https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382) in this GitHub issue, [Add Creality Ender 2 Pro config #633](https://github.com/MarlinFirmware/Configurations/pull/633), you can often determine the stepper drivers by one of a few ways:
1. Listen to the sound. The 'TMC22\*\*' will sound much quieter
2. Look for a marking in Sharpie on the SD Card reader
```
C = HR4998
E = A4988
A = TMC2208
B = TMC2209
H = TMC2225
```
3. Remove the heat sync
<https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295>
After removing the heat sync, it appears that the Chip is actually a `MS35775`
[![Closeup of MS35775 on board](https://i.stack.imgur.com/0o5mK.jpg "Closeup of MS35775 on board")](https://i.stack.imgur.com/0o5mK.jpg "Closeup of MS35775 on board") |
18,629 | <p>I have a 3018 Pro CNC and being trying cutting a contour of a simple circular part:</p>
<p><a href="https://i.stack.imgur.com/w3mDe.png" rel="nofollow noreferrer" title="Screenshot of Fusion 360 model and route"><img src="https://i.stack.imgur.com/w3mDe.png" alt="Screenshot of Fusion 360 model and route" title="Screenshot of Fusion 360 model and route" /></a></p>
<p>G-code:</p>
<pre><code>(TestKnobContour)
(T1 D=1 CR=0 - ZMIN=-3 - flat end mill)
G90 G94
G17
G21
G90
(2D Contour1)
Z15
S5000 M3
G54
G0 X10.8 Y0.1
Z15
G1 Z5 F10.0
Z1 F10.0
Z-2.9
X10.792 Z-2.938 F10.0
X10.771 Z-2.971
X10.738 Z-2.992
X10.7 Z-3
X10.6
X10.562 Y0.092
X10.529 Y0.071
X10.508 Y0.038
X10.5 Y0
G2 X9.851 Y-3.634 I-10.5 J0
G1 Z-2.75
G2 X8.983 Y-5.436 I-9.851 J3.634
G1 Z-3 F10.0
G2 X3.301 Y-9.968 I-8.983 J5.436 F10.0
G1 Z-2.75
G2 X1.351 Y-10.413 I-3.301 J9.968
G1 Z-3 F10.0
G2 X-5.735 Y-8.795 I-1.351 J10.413 F10.0
G1 Z-2.75
G2 X-7.299 Y-7.548 I5.735 J8.795
G1 Z-3 F10.0
G2 X-10.452 Y-1 I7.299 J7.548 F10.0
G1 Z-2.75
G2 X-10.452 Y1 I10.452 J1
G1 Z-3 F10.0
G2 X-7.299 Y7.548 I10.452 J-1 F10.0
G1 Z-2.75
G2 X-5.735 Y8.795 I7.299 J-7.548
G1 Z-3 F10.0
G2 X1.351 Y10.413 I5.735 J-8.795 F10.0
G1 Z-2.75
G2 X3.301 Y9.968 I-1.351 J-10.413
G1 Z-3 F10.0
G2 X8.983 Y5.436 I-3.301 J-9.968 F10.0
G1 Z-2.75
G2 X9.851 Y3.634 I-8.983 J-5.436
G1 Z-3 F10.0
G2 X10.5 Y0 I-9.851 J-3.634 F10.0
G1 X10.508 Y-0.038
X10.529 Y-0.071
X10.562 Y-0.092
X10.6 Y-0.1
X10.7
X10.738 Z-2.992
X10.771 Z-2.971
X10.792 Z-2.938
X10.8 Z-2.9
G0 Z15
M5
X0 Y0 Z0
M30
</code></pre>
<p>Candle shows that everything is fine for this G-code:</p>
<p><a href="https://i.stack.imgur.com/jZ4p3.png" rel="nofollow noreferrer" title="Screenshot of Candle software"><img src="https://i.stack.imgur.com/jZ4p3.png" alt="Screenshot of Candle software" title="Screenshot of Candle software" /></a></p>
<p>However, I am getting weird results (see top right):</p>
<p><a href="https://i.stack.imgur.com/76m5S.jpg" rel="nofollow noreferrer" title="Photo of milled circles with irregularities"><img src="https://i.stack.imgur.com/76m5S.jpg" alt="Photo of milled circles with irregularities" title="Photo of milled circles with irregularities" /></a></p>
<p>What can I do for troubleshooting?</p>
| [
{
"answer_id": 18645,
"author": "cmm",
"author_id": 2082,
"author_profile": "https://3dprinting.stackexchange.com/users/2082",
"pm_score": 2,
"selected": false,
"text": "<p>It is hard to be sure from the picture. When I wrote this answer, material you were cutting looked like clear plastic. When I reviewed it now, the material looks more like aluminum. It doesn't really matter, since the melting point of aluminum is well within the range of both high speed steel (HSS) and carbide.</p>\n<p>What follows is a list of possibilities and things to check.</p>\n<ol>\n<li><p>check the mounting of the spindle. Does it hang rigidly as you push the tooltip in x, y, and any point in the circle, or does it tip more in one direction than another? This could be caused by a loose mounting screw.</p>\n</li>\n<li><p>Are you actually cutting, or are you melting the material? It is very easy for a tool, especially a tight spiral 4-flute tool, to heat above the melting/softening point, and to then push through the material rather than removing it as chips. Using a tool with fewer flutes at a slower speed can sometimes help. You may also want to cool it with some water -- not enough to make a mess of the machine, but enough to help cool the tool. This happens easily with plastic, and also with aluminum. I have several times had to peel bits of solidified aluminum from inside the flutes of a carbide cutter.</p>\n</li>\n<li><p>It doesn't look like backlash. The 45-degree angle is curious. To see if it varies with or without load, try putting a marking pen in the collet and draw similar circles. It doesn't look like a primary software or hardware problem, since the inner circles were round. Only the outermost circle has the flat spot.</p>\n</li>\n<li><p>If the departure from a circle is only under load, reduce the load. Step the tool into the work by 1/2 of what you are doing now. How does that change the result?</p>\n</li>\n<li><p>Chips remaining near the cut can join in the melt. Try blowing compressed air on the cut while it is cutting, both for cooling, and to remove chips.</p>\n</li>\n</ol>\n<p>Some things it is unlikely to be, if the shape was intended to be a complete circle, and if the outer pass is the last pass performed:</p>\n<ul>\n<li>Skipping steps due to insufficient stepper motor torque</li>\n<li>Belt slipping (or lead screws skipping)</li>\n<li>Loose belts or backlash in mechanical shaft connections.</li>\n</ul>\n"
},
{
"answer_id": 18650,
"author": "Davo",
"author_id": 4922,
"author_profile": "https://3dprinting.stackexchange.com/users/4922",
"pm_score": 1,
"selected": false,
"text": "<p>Parts of the circle are at different heights. When I rendered your 30 or so actual G1 and G2 lines, here's what I got. It looks like a circle from above, but form the sde you can see depth changes. What are those coordinate lines with no G0 ot G1 or G2 or G3 command for?</p>\n<p><a href=\"https://i.stack.imgur.com/fbVWo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fbVWo.png\" alt=\"Top view\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/EctYT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EctYT.png\" alt=\"Angled view\" /></a></p>\n<p>=============================</p>\n<p>Okay, here's a simple gcode I just made by hand do to something similar. Granted, I used all nice round numbers, but this is an example of what I think you're looking for. You'll have to change it as needed; perhaps more paths if your tool is less wide; more iterations at deeper depths, or even different coordinates. Enjoy.</p>\n<p><a href=\"https://i.stack.imgur.com/ZT0gD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZT0gD.png\" alt=\"Screenshot of Rendering and Gcode\" /></a></p>\n<pre><code>G0 X30 Y30 ; move to start XY\nM3 T12 S50 ; spindle on 50%\nG1 Z-0.5 E1 ; down to depth1\nG2 X50 Y50 J20.0 E1 ; arc\nG1 X30 Y30 E1 ; corner\nG1 X30 Y35 E1 ; move inward\nG2 X45 Y50 J15 E1 ; arc\nG1 X30 Y35 E1 ; corner\nG1 X30 Y40 E1 ; move inward\nG2 X40 Y50 J10 E1 ; arc\nG1 X30 Y40 ; corner\nG1 X30 Y45 ; move inward\nG2 X35 Y50 J5 E1 ; arc\nG1 X30 Y45 E1 ; corner\nG1 X30 Y50 E1 ; move inward\nG0 Z 10 ; move up to clear\nM3 T12 S0 ; spindle off\n</code></pre>\n<p>=================================</p>\n<p>Or, if I've made a mistake and you want simple circles:</p>\n<p><a href=\"https://i.stack.imgur.com/pPuvg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pPuvg.png\" alt=\"Screenshot of circles rendered and gcode\" /></a></p>\n<pre><code>G0 X30 Y30 ; move to start XY\nM3 T12 S50 ; spindle on 50%\nG1 Z-0.5 E1 ; down to depth1\nG2 X30 Y30 J20.0 E1 ; arc\nG1 X30 Y35 E1 ; move inward\nG2 X30 Y35 J15 E1 ; arc\nG1 X30 Y40 E1 ; move inward\nG2 X30 Y40 J10 E1 ; arc\nG1 X30 Y45 ; move inward\nG2 X30 Y45 J5 E1 ; arc\nG1 X30 Y50 E1 ; move inward\nG0 Z 10 ; move up to clear\nM3 T12 S0 ; spindle off\n</code></pre>\n"
},
{
"answer_id": 18686,
"author": "0scar",
"author_id": 5740,
"author_profile": "https://3dprinting.stackexchange.com/users/5740",
"pm_score": 3,
"selected": true,
"text": "<p>I've ran the code on my own CNC machine. I slightly adapted the code as my machine doesn't understand the movement without the instruction code:</p>\n<pre><code>Z1 F10.0\nZ-2.9\nX10.792 Z-2.938 F10.0\nX10.771 Z-2.971\nX10.738 Z-2.992\nX10.7 Z-3\nX10.6\nX10.562 Y0.092\nX10.529 Y0.071\nX10.508 Y0.038\nX10.5 Y0\n</code></pre>\n<p>is changed to</p>\n<pre><code>G1 Z1 F10.0\nG1 Z-2.9\nG1 X10.792 Z-2.938 F10.0\nG1 X10.771 Z-2.971\nG1 X10.738 Z-2.992\nG1 X10.7 Z-3\nG1 X10.6\nG1 X10.562 Y0.092\nG1 X10.529 Y0.071\nG1 X10.508 Y0.038\nG1 X10.5 Y0\netc...\n</code></pre>\n<p>As I used an engraver bit, I made sure the depth was touching the wood (engraving) when running at the lowest depth. The contour it drew was a perfect circle.</p>\n<p><a href=\"https://i.stack.imgur.com/aYvdw.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aYvdw.jpg\" alt=\"enter image description here\" /></a></p>\n<p>The code is therefor working as it should (carve a circle, in the photo above, the circle started at the hole in the top left and followed a clockwise path), the result from your milling exercise shows that the final segment of the circle is not giving you a circle segment, instead the milling path is sort of straight. I've seen such paths where the steppers are not powerful enough to mill through the material. As a result they skip steps, and in this case it results in a sort of straight path. You should try running a dry run (in air), or in softer material (this will determine if the code is producing a cirlce in your machine as well), and add more passes to milling the knob (for the final product).</p>\n"
}
] | 2021/12/24 | [
"https://3dprinting.stackexchange.com/questions/18629",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/8008/"
] | I have a 3018 Pro CNC and being trying cutting a contour of a simple circular part:
[![Screenshot of Fusion 360 model and route](https://i.stack.imgur.com/w3mDe.png "Screenshot of Fusion 360 model and route")](https://i.stack.imgur.com/w3mDe.png "Screenshot of Fusion 360 model and route")
G-code:
```
(TestKnobContour)
(T1 D=1 CR=0 - ZMIN=-3 - flat end mill)
G90 G94
G17
G21
G90
(2D Contour1)
Z15
S5000 M3
G54
G0 X10.8 Y0.1
Z15
G1 Z5 F10.0
Z1 F10.0
Z-2.9
X10.792 Z-2.938 F10.0
X10.771 Z-2.971
X10.738 Z-2.992
X10.7 Z-3
X10.6
X10.562 Y0.092
X10.529 Y0.071
X10.508 Y0.038
X10.5 Y0
G2 X9.851 Y-3.634 I-10.5 J0
G1 Z-2.75
G2 X8.983 Y-5.436 I-9.851 J3.634
G1 Z-3 F10.0
G2 X3.301 Y-9.968 I-8.983 J5.436 F10.0
G1 Z-2.75
G2 X1.351 Y-10.413 I-3.301 J9.968
G1 Z-3 F10.0
G2 X-5.735 Y-8.795 I-1.351 J10.413 F10.0
G1 Z-2.75
G2 X-7.299 Y-7.548 I5.735 J8.795
G1 Z-3 F10.0
G2 X-10.452 Y-1 I7.299 J7.548 F10.0
G1 Z-2.75
G2 X-10.452 Y1 I10.452 J1
G1 Z-3 F10.0
G2 X-7.299 Y7.548 I10.452 J-1 F10.0
G1 Z-2.75
G2 X-5.735 Y8.795 I7.299 J-7.548
G1 Z-3 F10.0
G2 X1.351 Y10.413 I5.735 J-8.795 F10.0
G1 Z-2.75
G2 X3.301 Y9.968 I-1.351 J-10.413
G1 Z-3 F10.0
G2 X8.983 Y5.436 I-3.301 J-9.968 F10.0
G1 Z-2.75
G2 X9.851 Y3.634 I-8.983 J-5.436
G1 Z-3 F10.0
G2 X10.5 Y0 I-9.851 J-3.634 F10.0
G1 X10.508 Y-0.038
X10.529 Y-0.071
X10.562 Y-0.092
X10.6 Y-0.1
X10.7
X10.738 Z-2.992
X10.771 Z-2.971
X10.792 Z-2.938
X10.8 Z-2.9
G0 Z15
M5
X0 Y0 Z0
M30
```
Candle shows that everything is fine for this G-code:
[![Screenshot of Candle software](https://i.stack.imgur.com/jZ4p3.png "Screenshot of Candle software")](https://i.stack.imgur.com/jZ4p3.png "Screenshot of Candle software")
However, I am getting weird results (see top right):
[![Photo of milled circles with irregularities](https://i.stack.imgur.com/76m5S.jpg "Photo of milled circles with irregularities")](https://i.stack.imgur.com/76m5S.jpg "Photo of milled circles with irregularities")
What can I do for troubleshooting? | I've ran the code on my own CNC machine. I slightly adapted the code as my machine doesn't understand the movement without the instruction code:
```
Z1 F10.0
Z-2.9
X10.792 Z-2.938 F10.0
X10.771 Z-2.971
X10.738 Z-2.992
X10.7 Z-3
X10.6
X10.562 Y0.092
X10.529 Y0.071
X10.508 Y0.038
X10.5 Y0
```
is changed to
```
G1 Z1 F10.0
G1 Z-2.9
G1 X10.792 Z-2.938 F10.0
G1 X10.771 Z-2.971
G1 X10.738 Z-2.992
G1 X10.7 Z-3
G1 X10.6
G1 X10.562 Y0.092
G1 X10.529 Y0.071
G1 X10.508 Y0.038
G1 X10.5 Y0
etc...
```
As I used an engraver bit, I made sure the depth was touching the wood (engraving) when running at the lowest depth. The contour it drew was a perfect circle.
[![enter image description here](https://i.stack.imgur.com/aYvdw.jpg)](https://i.stack.imgur.com/aYvdw.jpg)
The code is therefor working as it should (carve a circle, in the photo above, the circle started at the hole in the top left and followed a clockwise path), the result from your milling exercise shows that the final segment of the circle is not giving you a circle segment, instead the milling path is sort of straight. I've seen such paths where the steppers are not powerful enough to mill through the material. As a result they skip steps, and in this case it results in a sort of straight path. You should try running a dry run (in air), or in softer material (this will determine if the code is producing a cirlce in your machine as well), and add more passes to milling the knob (for the final product). |
18,639 | <p>I recently got a KP3S Kingroon 3D printer and have been trying to set it up.</p>
<p>After a couple of test prints, the Y-axis seems to only move in one direction. At first, I thought it was a motor issue, but when I go into the manual move directions for the Y-axis it seems that both inputs lead to the motor spinning in the same direction.</p>
<p>We have ruled out endstops as a possible issue. I think it might be a hardware issue but lack the skills to confirm the exact issue.</p>
<pre><code>Send:17:40:57.724: @moveRel Y10.00
Send:17:40:57.724: N31 G1 Y10.00 F6000
Send:17:40:57.728: @updatePrinterState
Send:17:41:00.824: @moveRel Y-10.00
Send:17:41:00.824: N35 G1 Y0.00 F6000
Send:17:41:00.828: @updatePrinterState
Send:17:41:07.445: @moveRel Y10.00
Send:17:41:07.445: N43 G1 Y10.00 F6000
Send:17:41:07.449: @updatePrinterState
Send:17:41:09.482: @moveRel Y-10.00
Send:17:41:09.482: N46 G1 Y0.00 F6000
Send:17:41:09.486: @updatePrinterState
</code></pre>
<p>Even though it states that it is increasing and decreasing by 10 it only decreases by 10.</p>
<p>I have updated the firmware to Marlin. I tested switching X and Y inputs and believe the breakdown occurs at the Y input signal.</p>
<p>attached is a picture of the mother board.</p>
<p><a href="https://i.stack.imgur.com/nhmP2.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nhmP2.gif" alt="picture of mother board" /></a></p>
<p>I am unsure of how to best fix this?</p>
| [
{
"answer_id": 18640,
"author": "0scar",
"author_id": 5740,
"author_profile": "https://3dprinting.stackexchange.com/users/5740",
"pm_score": 0,
"selected": false,
"text": "<p>The question body has changed to rule out broken endstops. As a generic answer for steppers only going into a single direction, if an axis of a 3D printer only moves in one direction it usually implies that the end stop of that axis is triggered. If triggered, the firmware doesn’t allow the stepper to move to the direction of the end stop.</p>\n<p>Check the end stop lever and cables. Optionally connect a USB cable and send the G-code <a href=\"https://reprap.org/wiki/G-code#M119:_Get_Endstop_Status\" rel=\"nofollow noreferrer\"><code>M119</code></a> over a <a href=\"https://3dprinting.stackexchange.com/questions/10573/what-is-a-printer-console-terminal\">terminal</a>.</p>\n<p>If the endstops are functioning correctly (reporting “open” or “triggered” corresponding to the state of the endstop), a Google search on the World Wide Web shows that people that had these exact problems had issues with the controller board, replacing the board helped their issue. If this is a recent purchase it is advised to contact the seller for support rather than fiddling with the board or the firmware.</p>\n<p>In case the board has a spare unused stepper driver (not very unlikely if you have <a href=\"https://www.google.nl/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&ved=2ahUKEwiX5PGlv4b1AhURDuwKHU5JBuQQFnoECBMQAQ&url=https%3A%2F%2Fnl.aliexpress.com%2Fitem%2F1005001621822311.html&usg=AOvVaw1uT5ZgSK04dlnQvoBgHSKF\" rel=\"nofollow noreferrer\">this controller board</a>), the firmware could be altered to use the spare for Y movement. <a href=\"https://3dprinting.stackexchange.com/a/5786/\">E.g. <code>E1</code> could be used for <code>Y</code>.</a></p>\n"
},
{
"answer_id": 18699,
"author": "doombringer175",
"author_id": 32439,
"author_profile": "https://3dprinting.stackexchange.com/users/32439",
"pm_score": 3,
"selected": true,
"text": "<p>The answer might just be replace the mother board.</p>\n<p>If I understood everything correctly there are 5 things to check to break down the problem:</p>\n<ul>\n<li>the motor,</li>\n<li>the cable,</li>\n<li>the stepper connection,</li>\n<li>the software input, and</li>\n<li>the firmware.</li>\n</ul>\n<p>Using Repetier I disproved that the software was broken. By switching the X stepper and Y stepper cables, the motor and connection cable were proven to work. By flashing new firmware it was shown that it was without question that the firmware was the issue.</p>\n<p>The backup extractor (E1) is not operational on this board. So it is either the stepper of the mother board.</p>\n"
}
] | 2021/12/26 | [
"https://3dprinting.stackexchange.com/questions/18639",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/32439/"
] | I recently got a KP3S Kingroon 3D printer and have been trying to set it up.
After a couple of test prints, the Y-axis seems to only move in one direction. At first, I thought it was a motor issue, but when I go into the manual move directions for the Y-axis it seems that both inputs lead to the motor spinning in the same direction.
We have ruled out endstops as a possible issue. I think it might be a hardware issue but lack the skills to confirm the exact issue.
```
Send:17:40:57.724: @moveRel Y10.00
Send:17:40:57.724: N31 G1 Y10.00 F6000
Send:17:40:57.728: @updatePrinterState
Send:17:41:00.824: @moveRel Y-10.00
Send:17:41:00.824: N35 G1 Y0.00 F6000
Send:17:41:00.828: @updatePrinterState
Send:17:41:07.445: @moveRel Y10.00
Send:17:41:07.445: N43 G1 Y10.00 F6000
Send:17:41:07.449: @updatePrinterState
Send:17:41:09.482: @moveRel Y-10.00
Send:17:41:09.482: N46 G1 Y0.00 F6000
Send:17:41:09.486: @updatePrinterState
```
Even though it states that it is increasing and decreasing by 10 it only decreases by 10.
I have updated the firmware to Marlin. I tested switching X and Y inputs and believe the breakdown occurs at the Y input signal.
attached is a picture of the mother board.
[![picture of mother board](https://i.stack.imgur.com/nhmP2.gif)](https://i.stack.imgur.com/nhmP2.gif)
I am unsure of how to best fix this? | The answer might just be replace the mother board.
If I understood everything correctly there are 5 things to check to break down the problem:
* the motor,
* the cable,
* the stepper connection,
* the software input, and
* the firmware.
Using Repetier I disproved that the software was broken. By switching the X stepper and Y stepper cables, the motor and connection cable were proven to work. By flashing new firmware it was shown that it was without question that the firmware was the issue.
The backup extractor (E1) is not operational on this board. So it is either the stepper of the mother board. |
18,704 | <p>I need to 3D print several composites. The constituent materials are photopolymer resins. The composites are very similar to a Rubik's cube. Considering it that way, each voxel (every small piece of the Rubik's cube) is either entirely printed by material A or B.</p>
<p>I have the binary files ready for the parts. More specifically speaking, I have 3D binary tensors corresponding to each composite topology. In my tensors, each of the elements represents a voxel, and their values (binary) indicate the material that should be assigned to that specific voxel. For instance, a 1 or 0 value located at the I, J, K position of the binary tensor simply means that in that composite, the voxel located at that I, J, K position should be printed with material A or B entirely.</p>
<p>I believe for 3D printing these composites, the <a href="https://www.stratasys.com/3d-printers/objet-350-500-connex3" rel="nofollow noreferrer">Stratasys Objet500 Connex3 printer</a> would be a good choice. However, I have no idea how to prepare my files for 3D printing the structures. If it was a CAD file, I could use slicer software, but I do not know how I can print the structures using these binary tensors. I would appreciate any help regarding this matter.</p>
| [
{
"answer_id": 18706,
"author": "Trish",
"author_id": 8884,
"author_profile": "https://3dprinting.stackexchange.com/users/8884",
"pm_score": 0,
"selected": false,
"text": "<p>Stratasys industrial machines generally use proprietary software to prepare the print files for printing and don't use common slicers like Ultimaker Cura or Prusa-slicer.</p>\n<p>The software that is suggested by the manufacturer for both arranging and preparing prints on their machines of the Objet type is <a href=\"https://grabcad.com/print\" rel=\"nofollow noreferrer\">GrabCAD</a>, a free software. The project is owned by Stratasys, so it is pretty much on point to all of Stratasys' machine's capabilities.</p>\n"
},
{
"answer_id": 18708,
"author": "fred_dot_u",
"author_id": 854,
"author_profile": "https://3dprinting.stackexchange.com/users/854",
"pm_score": 1,
"selected": false,
"text": "<p>It appears that your question is directed to solving the problem of converting your file of parameters to a 3D printable form. I'm far from an OpenSCAD wizard, but I suspect that your parameters file could be read into a properly coded OpenSCAD document to create the necessary STL to be printed.</p>\n<p>Your reference of I, J, K is better considered as X, Y, Z and requires an additional value to determine material A, B or nul. If your voxels are uniform size as I expect, the coding is likely not to be particularly complex (for more skilled individuals).</p>\n<p>pseudocode:</p>\n<pre><code>read entry\ntranslate by x, y, z\ncheck for print material a\ncreate voxel\nrepeat to EOF\nexport STL\n</code></pre>\n<p>repeat for material b</p>\n<p>It's important to note that a typical STL file requires the object to be a fully manifold creation. If the STL appears, for example, as a QR code, some of the voxels will be floating and may not produce. This is also dependent on the printer selected, as an SLS printer would be able to produce such a design, which would fall apart once removed from the print chamber. These are aspects not covered in the question.</p>\n"
}
] | 2022/01/09 | [
"https://3dprinting.stackexchange.com/questions/18704",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/32618/"
] | I need to 3D print several composites. The constituent materials are photopolymer resins. The composites are very similar to a Rubik's cube. Considering it that way, each voxel (every small piece of the Rubik's cube) is either entirely printed by material A or B.
I have the binary files ready for the parts. More specifically speaking, I have 3D binary tensors corresponding to each composite topology. In my tensors, each of the elements represents a voxel, and their values (binary) indicate the material that should be assigned to that specific voxel. For instance, a 1 or 0 value located at the I, J, K position of the binary tensor simply means that in that composite, the voxel located at that I, J, K position should be printed with material A or B entirely.
I believe for 3D printing these composites, the [Stratasys Objet500 Connex3 printer](https://www.stratasys.com/3d-printers/objet-350-500-connex3) would be a good choice. However, I have no idea how to prepare my files for 3D printing the structures. If it was a CAD file, I could use slicer software, but I do not know how I can print the structures using these binary tensors. I would appreciate any help regarding this matter. | It appears that your question is directed to solving the problem of converting your file of parameters to a 3D printable form. I'm far from an OpenSCAD wizard, but I suspect that your parameters file could be read into a properly coded OpenSCAD document to create the necessary STL to be printed.
Your reference of I, J, K is better considered as X, Y, Z and requires an additional value to determine material A, B or nul. If your voxels are uniform size as I expect, the coding is likely not to be particularly complex (for more skilled individuals).
pseudocode:
```
read entry
translate by x, y, z
check for print material a
create voxel
repeat to EOF
export STL
```
repeat for material b
It's important to note that a typical STL file requires the object to be a fully manifold creation. If the STL appears, for example, as a QR code, some of the voxels will be floating and may not produce. This is also dependent on the printer selected, as an SLS printer would be able to produce such a design, which would fall apart once removed from the print chamber. These are aspects not covered in the question. |
18,757 | <p>I'm running a stock Ender 5 pro with the filament that came with it, and using Creality Slicer 4.8.2, but I'm only able to get reliable bed adhesion if I increase the bed temperature from 50 to 60 °C for the bottom layer and decrease the print head speed by about 75 % from the default profile for the Ender 5.</p>
<p>The machine is absolutely stock, and is fresh out of the box except for bed levelling.</p>
<p>I used the default bed leveling print and that came out well, so I'm reasonably certain that it's not a bed leveling issue. The problem seems to be with models that I've made myself in blender and exported as STL files.</p>
<p>In all cases the raft that was generated by the Creality software has printed out perfectly, but the print has only partially gone down when it came to the model itself. <img src="https://i.stack.imgur.com/sdXA1.jpg" alt="enter image description here" /></p>
| [
{
"answer_id": 18758,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 11157,
"author_profile": "https://3dprinting.stackexchange.com/users/11157",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming Creality's stock firmware still doesn't have Linear Advance enabled, there's a fairly hard requirement to go slow on the first layer. This is because, as the toolhead accelerates up to higher speed without advancing the extruder extra to compensate for the backpressure in the filament-path/nozzle, you'll have an interval of underextrusion, giving less contact area for the extruded material to cling to the bed at the same time there's added force pulling it in a direction parallel to the bed surface. This becomes less critical to adhesion starting with the second layer, since the new material is bonding to itself rather than just trying to stick to a bed.</p>\n<p>Having the bed hot will help it stick better and maybe even help reduce the pressure at the nozzle by reducing the heat loss, so it might work around the problem. But in general, you don't want to be in a situation where a few degrees of temperature difference are the cutoff between a failed print and a successful one.</p>\n<p>Anyway, do all the usual stuff to improve bed adhesion, and especially make sure your bed height is as close to perfect as you can get it, if you want moderately fast printing to work. But don't be surprised if you need to upgrade to a version of Marlin with Linear Advance (or to Klipper) to get successful high-speed first layers.</p>\n"
},
{
"answer_id": 18760,
"author": "0scar",
"author_id": 5740,
"author_profile": "https://3dprinting.stackexchange.com/users/5740",
"pm_score": 1,
"selected": false,
"text": "<p>Looking at the image, the deposited filament lines do not connect. If we consider that you have the correct filament width in your slicer and the correct amount of steps per millimeter for the extruder or no problem with extruding is present, your initial bed to nozzle gap might be too large, level with a thinner piece of paper or subtract a few tenths, see <a href=\"https://3dprinting.stackexchange.com/a/4746/\">this answer</a> for redefining the Z-height. Alternatively use a slicer option called “Z offset setting”, see <a href=\"https://3dprinting.stackexchange.com/a/7265/\">this answer</a>.</p>\n<blockquote>\n<p>Why does the first layer only adhere to bed if I increase the temperature by 10 °C and drop the speed by 75 %</p>\n</blockquote>\n<p>If the nozzle gap is a little too large, the filament doesn't get squished enough for proper adhesion. This is seen as non-connecting filament lines. It looks as if the nozzle is under-extruding, but if that has been checked, a larger initial gap has the same effect. If you increase bed and or hot end temperature and slow down, the filament gets time to adhere properly, even when the gap is larger.</p>\n"
},
{
"answer_id": 18764,
"author": "Criggie",
"author_id": 12956,
"author_profile": "https://3dprinting.stackexchange.com/users/12956",
"pm_score": 3,
"selected": true,
"text": "<p>Your bed is too low - raise it by turning the knobs underneath.</p>\n<p>The first layer should not look like strings sitting on the bed as per your photo. Instead it should be a wider strip that looks somewhat like an electronic circuit trace, or like someone has pushed wet paint out of a tube that is being wiped across the surface.</p>\n<p>My method is to head the bed with "preheat" in the menu, and let it sit at printing temp for at least 5 minutes. This avoids the heater being at temp but the top of the glass bed being cool.</p>\n<p>Then start your job. As the brim or skirt is printed, actively watch it in person and twiddle the height knobs a quarter turn at a time. You want the "end view" or cross sectional view of the printed filament to be like this:</p>\n<pre><code> _____<==>_____\n</code></pre>\n<p>and not like this</p>\n<pre><code> ______0______\n</code></pre>\n<p>and definitely not like this</p>\n<pre><code> 0\n_______________\n</code></pre>\n<p>If the head starts scratching the bed, you've gone too far so lower the bed back down again (effectively raising the print head a little)</p>\n<hr />\n<p>Here's a print in progress trying to show a better brim. Notice eachgstrand is ovalised and mushed down. That brim will come off in one piece afterward.</p>\n<p><a href=\"https://i.stack.imgur.com/Vis5Z.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Vis5Z.jpg\" alt=\"enter image description here\" /></a></p>\n"
}
] | 2022/01/16 | [
"https://3dprinting.stackexchange.com/questions/18757",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/29097/"
] | I'm running a stock Ender 5 pro with the filament that came with it, and using Creality Slicer 4.8.2, but I'm only able to get reliable bed adhesion if I increase the bed temperature from 50 to 60 °C for the bottom layer and decrease the print head speed by about 75 % from the default profile for the Ender 5.
The machine is absolutely stock, and is fresh out of the box except for bed levelling.
I used the default bed leveling print and that came out well, so I'm reasonably certain that it's not a bed leveling issue. The problem seems to be with models that I've made myself in blender and exported as STL files.
In all cases the raft that was generated by the Creality software has printed out perfectly, but the print has only partially gone down when it came to the model itself. ![enter image description here](https://i.stack.imgur.com/sdXA1.jpg) | Your bed is too low - raise it by turning the knobs underneath.
The first layer should not look like strings sitting on the bed as per your photo. Instead it should be a wider strip that looks somewhat like an electronic circuit trace, or like someone has pushed wet paint out of a tube that is being wiped across the surface.
My method is to head the bed with "preheat" in the menu, and let it sit at printing temp for at least 5 minutes. This avoids the heater being at temp but the top of the glass bed being cool.
Then start your job. As the brim or skirt is printed, actively watch it in person and twiddle the height knobs a quarter turn at a time. You want the "end view" or cross sectional view of the printed filament to be like this:
```
_____<==>_____
```
and not like this
```
______0______
```
and definitely not like this
```
0
_______________
```
If the head starts scratching the bed, you've gone too far so lower the bed back down again (effectively raising the print head a little)
---
Here's a print in progress trying to show a better brim. Notice eachgstrand is ovalised and mushed down. That brim will come off in one piece afterward.
[![enter image description here](https://i.stack.imgur.com/Vis5Z.jpg)](https://i.stack.imgur.com/Vis5Z.jpg) |
18,761 | <p>Is there a machine (for hobbyists) that will make filament based on the type of plastic I put in. I will sort the plastic before I will put it in the machine.</p>
<p>I have seen the <a href="http://filabot.com" rel="nofollow noreferrer">filabot</a> but this uses only plastic from previous prints not plastic types Polyethylene Terephthalate (PET or PETE) or High-Density Polyethylene (HDPE) (these are the #1 or #2 plastic types listed at <a href="https://plasticoceans.org/7-types-of-plastic/" rel="nofollow noreferrer">plasticoceans.org</a>).</p>
<p>To reiterate:</p>
<ul>
<li>I am asking if there is a machine that can turn a plastic bottle into usable filament.</li>
<li>I want to know if there is a machine (currently on the market) that will make filament, based on the type of plastic I put in.</li>
</ul>
<hr />
<p>I <em>will</em> sort the plastic <em>before</em> I will put it in the machine... so,</p>
<pre><code>sorted waste in ---> sorted filament out
</code></pre>
| [
{
"answer_id": 18762,
"author": "user10489",
"author_id": 28397,
"author_profile": "https://3dprinting.stackexchange.com/users/28397",
"pm_score": 0,
"selected": false,
"text": "<p>The source of the plastic doesn't matter a lot.</p>\n<p>What matters is the plastic's composition and chemistry and how well shredded it is.</p>\n<p>Issues are:</p>\n<ul>\n<li>Is it a thermoplast that can be remelted?</li>\n<li>Is the working melt temperature range compatible with your printer and/or the filament forming machine?</li>\n<li>Is the plastic chemically compatible with the components of the machines and the print platform you are using in the 3d printer? (If it isn't, it either will stick when it shouldn't or won't stick when it should.)</li>\n<li>Is the plastic shredded enough for the filament reforming machine to use it?</li>\n<li>Is the flexibility of the remelted plastic suitable for 3d printing, or does it need volatile plasticizers added to make it soft enough to handle as filament?</li>\n</ul>\n<p>Other factors may also be a problem. For example, PLA, TPU, and PETG are fairly temperature stable, but other plastics have high thermal expansion rates that can cause warping during 3d printing. There are a few ways to compensate for that however.</p>\n<p>If the plastic is contaminated with other plastics or non-soluble inks or labels, this must be removed first, or the results may be weak or not melt evenly or leave debris in the extrusion nozzle.</p>\n<p>Not only must the plastic be chemically compatible, but also there are tuning parameters such as temperature profiles, cooling speed, and extrusion speed that have to be calibrated to the plastic to get good filament.</p>\n<p>If all of these things are OK then it might be possible to use a machine to reform plastic from any source into filament.</p>\n"
},
{
"answer_id": 18768,
"author": "Caleb",
"author_id": 1690,
"author_profile": "https://3dprinting.stackexchange.com/users/1690",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n<p>I am asking if there is a machine that can turn a plastic bottle into usable filament.</p>\n</blockquote>\n<p>I've seen several projects (<a href=\"https://hackaday.com/2021/06/29/petbot-turn-pet-bottles-into-filament/\" rel=\"nofollow noreferrer\">one example</a>, and <a href=\"https://youtu.be/Eecbdb0bQWQ\" rel=\"nofollow noreferrer\">another</a>) where plastic bottles are sliced into long tapes, and the tape is then fed through an extruder. It's a somewhat simpler process than shredding bottles and then melting and extruding the shreds; since the tape is already a long strand, you're really just reforming it into a round filament suitable for use in a printer. Forming the tape from the bottle requires little more than a razor blade and a handful of hardware, and you can pull the tape through the extruder instead of forcing shreds through with a screw.</p>\n<p>Some of the drawbacks are that the process can't use the top and bottom of the bottle, and getting consistent results still requires some automation. Also, the process as shown only creates filament from a single bottle, so the length of the filament is limited by the size of the bottle.</p>\n<blockquote>\n<p>I want to know if there is a machine (currently on the market) that will make filament, based on the type of plastic I put in.</p>\n</blockquote>\n<p>The Filabot extruder that you mentioned will accept and extrude a wide variety of plastics, and the same should be true of any commercial or DIY extruder as long as it can get hot enough to melt the material you're supplying. Also, you can only extrude thermoplastic materials; thermoset materials won't work. By definition, thermoplastic materials are those that become soft and malleable when heated, while thermoset materials don't. So you can make filament from PLA, ABS, PET, PEEK, and many others. The material you supply might not always work well for FDM printing, though, or might work better in some printers than in others. For example, filament made from a PET soda bottle will be harder and more brittle than the PETG that's preferred for 3D printing, so you might have better luck using it in a printer with a direct extruder rather than one with a Bowden setup.</p>\n"
},
{
"answer_id": 18772,
"author": "Trish",
"author_id": 8884,
"author_profile": "https://3dprinting.stackexchange.com/users/8884",
"pm_score": 2,
"selected": false,
"text": "<p>There are 2 parameters you need to have good control over when printing any filament:</p>\n<ul>\n<li>Melting temperature</li>\n<li>Diameter</li>\n</ul>\n<p>Of these, the melting temperature is directly correlated to the chemical composition of the polymer blend in the filament while diameter control is part of the manufacturing process.</p>\n<p>And for 3D printing, we need to take a look at the usability of the material itself. For example, pure PET is not easy to print at all and as used in bottles might be unprintable. PETG (a glycol modified PET) on the other hand is much easier to print - and <a href=\"https://3dprinting.stackexchange.com/a/7856/8884\">most filaments sold under PET actually are PETG or PETT.</a></p>\n<h1>Troubles of recycling</h1>\n<p>The melting point of a <em>blend</em> of polymers is often difficult to gauge before doing experiments and in case of recycled material, there are problems with recreating the exact same blend when using small batches unless you use exactly one material as the base for your manufacturing. This brings us to the big problem: errors in the base material. These come in several types:</p>\n<ul>\n<li>Misidentification</li>\n<li>Contaminants</li>\n<li>Degradation</li>\n</ul>\n<p>Let's address these piece by piece:</p>\n<h2>Misidentified base material</h2>\n<p>Misidentification is when you chuck material into the wrong bin and then process it as if it was the stuff the bin was for. For example, if you'd chuck a chunk of ABS into the PLA bin, your blend will not come out as PLA but as some kind of higher melting composite of the two. The exact details of the result depend on the mixture and how well you mix the processed raw material, but in effect, you just made <a href=\"https://3dprinting.stackexchange.com/questions/4982/what-is-pla-how-is-it-different-from-pla\">some kind of PLA+</a>.</p>\n<p>This can be overcome by testing and good training as well as knowing the base material well. For example, there is an Austrian company that takes back ski-shoes. Only the hard shells of a particular manufacturer (which used a red ABS) are shredded, pelletized, mixed with some virgin ABS and color for stability and uniformity, then turned into filament, and then printed into flutes.</p>\n<p>Another ski-shoe manufacturer takes back their own shoes and recycles the shells back into the current manufacturing, but is silent on what their shells are made from but that they are a long-chain polymer.</p>\n<p>When trying to differentiate between PET and PETG, you can not do that unless you do a chemical analysis of every bottle - which leads to a huge problem in reprocessing: PETG melts well before PET and clumps it up, acting as a contaminant (see <a href=\"https://3dprinting.stackexchange.com/questions/7855/can-i-3d-print-a-pet-bottle\">here</a> for more details)!</p>\n<h2>Contaminants</h2>\n<p>Contaminants are a problem that comes with a bad base material. in general, there are two types of contaminants: Chemical and Physical.</p>\n<p>Physical contaminants can be avoided by removing them before and after shredding. In the case of Skishoes (that's why I chose that example) is, you'd remove the soft shells and the metal latches, disposing of them in separate ways. Then the plastic shells are roughly sized up, cleaned, and dried before further processing. Most physical contaminants can result in partial clogging during filament production, resulting in an uneven filament. Uneven filament or such containing non-melting particles can result in print failure, for example from being stuck in the extruder or clogging of the nozzle.</p>\n<p>Chemical contamination is arguably worse. PET bottles for example: what if the user before used to store chemicals in them that can't be separated from the polymer easily? In the best case, the contaminating raw material is removed, in the worst, it ends up in the stream. This introduced contaminated plastic ends up melting somewhat evenly into a larger portion of the recycled plastic, altering the properties in hard to predict ways. As a countermeasure in industrial PET recycling, the batches are huge and get well mixed before the new plastic product is made. By diluting the chemical contaminants on a vast batch, the effects of the contaminant are vastly reduced and evened out. This is also why even in the case of the recycled ABS-shoes-into-flutes, they mix in some degree of virgin ABS pellets - to buffer against chemical contamination.</p>\n<h2>Degradation</h2>\n<p>Not all polymers are suitable for recycling and some of them alter their properties depending on their surroundings. What actually happens depends on the material in question, but let's look at PLA as one example.</p>\n<p>While PLA doesn't exactly <em>break down</em> in nature unless put into a high-temperature environment, prolonged UV exposure can bleach out the contained coloration and some blends do become more brittle, others do not encounter this. <a href=\"https://www.youtube.com/watch?v=qqNfa_zExRU\" rel=\"nofollow noreferrer\">Angus/Makers Muse</a> had several prints exposed to the harsh Australian sun for up to several years and concluded the worst enemy of PLA over time is the UV light.</p>\n<p>A different type of <em>degradation</em> can happen from the environment. The one side of this is cold embrittlement, which means parts become more brittle in cold. This had some experiments done on by <a href=\"https://youtu.be/w0JVXvSSEWs\" rel=\"nofollow noreferrer\">Stefan/CNC Kitchen</a>. The other side of this is softening, for example by sitting in a hot car. Usually, this type of degradation is not lasting but could result in embedding contaminants into the mix by embedding them in the plastic, so see there.</p>\n<h1>Is it a good idea?</h1>\n<p>Well, from an ecological standpoint, it certainly is a good idea to recycle plastic. But with all the troubles to get any good filament, will it be viable under all viewpoints? You certainly can't sell filament which is of very varying quality unless you make it dirt cheap. Also, all this machinery takes a lot of power and initial investment before you can produce your first spool - which means it might not be economical or profitable.</p>\n<h1>economical viability</h1>\n<p>So, let's go back to the main question:</p>\n<blockquote>\n<p>[Is there] a machine that can turn a plastic bottle into usable filament? [...] [Is it] currently on the market?</p>\n</blockquote>\n<p>Yes, you can certainly extrude plastic from bottles into filament shape, and the tools are out there - for a price. However, not all bottles might be useable due to the chemical composition and you will need to make larger batches to reduce chemical contamination.</p>\n<p>On an industrial scale, the process consists of several steps: sorting, cleaning, shredding, pelletizing, mixing, extruding, and finally spooling the filament.</p>\n<p>Of these, the steps of shredding, pelletizing, and the combo of extruding & spooling need dedicated machinery. Even if hobby projects exist that manage to do this with well-known polymer blends, e.g. recycling 3D prints, such is usually heavy industrial machinery. In hobby-grade machinery, quality control is often problematic, as filament diameter control is the crux, and the price tag to get even filament without readjusting the machine every few minutes is high.</p>\n<p>The Shredder might be the cheapest part, only costing several thousand euros professionally and a couple of hundred in hobby grade. A proper pelletizing machine that turns the shreds into pellets for the filament extruder has a price tag of about 10 000 € and I have not yet found a hobbyist kit. A basic inquiry on the absolute minimum investment into a professional filament manufacturing stream without pelletizer came up with about 14 000 GBP (ca. 16 800 € / 19 000 USD) plus shipping, while hobbyist kits for only one of the two seem to come up with price tags between 500 and 3000 €.</p>\n<p>This brings the minimum investment using hobby-grade machinery to roundabout 3000 € but without a pelletizer, while an industrial setup comes out starting at about 25 000 GBP (ca. 30 000 € / 34 000 USD).</p>\n<h3>Cheaper options?</h3>\n<p>There are machines out there that turn PET bottles directly into filament by cutting them up directly before entering a filament formation system. This setup is called Pulltrusion, and it turns a plastic strip into an almost-cylindrical, folded-over filament.</p>\n<p>While no industrial size machine of this is available, <a href=\"https://youtu.be/N06FWr06iOI\" rel=\"nofollow noreferrer\">Stefan/CNC Kitchen</a> just released a video investigating the device to manufacture such filament and then tested the print properties of such a filament. <a href=\"https://www.youtube.com/channel/UCsv9RMNQvMnIgBzMo57i7NA\" rel=\"nofollow noreferrer\">Joshua/JRT3D</a> operated the machine in question and manufactured the samples. The base machine is the PetBot engineered by <a href=\"https://www.youtube.com/user/neskashev\" rel=\"nofollow noreferrer\">Roman Naskashev</a>, which is commercially available for about 400 € assembled plus shipping and import taxes from Russia. Joshua also managed to re-engineer a similar machine using the same method from a 3D printer, so the price point for a self-made machine might be lower.</p>\n<p>Each bottle weighs about 20 grams, but neither the mouth nor the bottom can be used, resulting in not 100% useability. The process also means, you can't get any deposit for the bottle back. Assuming an useable portion of about 50%, this would in Germany result in a price of 25 cents per 10 grams, so about 25 € per kilogram - which for PET filament would be quite competitive. Some bottles have larger useable portions than others, and others might not require a deposit, making these a very good price, to maybe even free filament.</p>\n<p>Do note that the manufacturing path creates a filament that is not solid but contains a void, which is accounted for by increasing the flow multiplier, and it does require a higher temperature than PETG: with settings of 265 °C for the nozzle, 80 °C for the bed and a 130 % flow rate, 30 mm/s extrusion rate, Stefan could use an otherwise PETG profile to gain good results.</p>\n<p>However, the higher base temperature requires an All-Metal hotend, which is part of why PET is hard to print with many machines. Other problems are the PET's crystallizing properties, which makes the melting properties at times hard to predict and can induce clogging. Also, Layer adhesion can be problematic.</p>\n<p>The biggest problem is the tiny production size of each spool: even if one would manage 15 grams per bottle in filament, this means that one needs to change the spool 66 to 100 times more often, making larger prints nearly impossible unless one comes up with a good solution for splicing the short pieces.</p>\n<h3>Final conclusion</h3>\n<p>While the tools are available, the price tag for a full recycling chain of raw material into filament, either as a hobby or industrially, can be kind of high. This means it might not be economical unless you can manufacture large batches <em>and</em> beat the price point of fresh filament.</p>\n<p>However, with small batches and the proper tooling, it might be somewhat viable <strong>depending</strong> on bottle size and deposit system.</p>\n"
}
] | 2022/01/17 | [
"https://3dprinting.stackexchange.com/questions/18761",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/31762/"
] | Is there a machine (for hobbyists) that will make filament based on the type of plastic I put in. I will sort the plastic before I will put it in the machine.
I have seen the [filabot](http://filabot.com) but this uses only plastic from previous prints not plastic types Polyethylene Terephthalate (PET or PETE) or High-Density Polyethylene (HDPE) (these are the #1 or #2 plastic types listed at [plasticoceans.org](https://plasticoceans.org/7-types-of-plastic/)).
To reiterate:
* I am asking if there is a machine that can turn a plastic bottle into usable filament.
* I want to know if there is a machine (currently on the market) that will make filament, based on the type of plastic I put in.
---
I *will* sort the plastic *before* I will put it in the machine... so,
```
sorted waste in ---> sorted filament out
``` | >
> I am asking if there is a machine that can turn a plastic bottle into usable filament.
>
>
>
I've seen several projects ([one example](https://hackaday.com/2021/06/29/petbot-turn-pet-bottles-into-filament/), and [another](https://youtu.be/Eecbdb0bQWQ)) where plastic bottles are sliced into long tapes, and the tape is then fed through an extruder. It's a somewhat simpler process than shredding bottles and then melting and extruding the shreds; since the tape is already a long strand, you're really just reforming it into a round filament suitable for use in a printer. Forming the tape from the bottle requires little more than a razor blade and a handful of hardware, and you can pull the tape through the extruder instead of forcing shreds through with a screw.
Some of the drawbacks are that the process can't use the top and bottom of the bottle, and getting consistent results still requires some automation. Also, the process as shown only creates filament from a single bottle, so the length of the filament is limited by the size of the bottle.
>
> I want to know if there is a machine (currently on the market) that will make filament, based on the type of plastic I put in.
>
>
>
The Filabot extruder that you mentioned will accept and extrude a wide variety of plastics, and the same should be true of any commercial or DIY extruder as long as it can get hot enough to melt the material you're supplying. Also, you can only extrude thermoplastic materials; thermoset materials won't work. By definition, thermoplastic materials are those that become soft and malleable when heated, while thermoset materials don't. So you can make filament from PLA, ABS, PET, PEEK, and many others. The material you supply might not always work well for FDM printing, though, or might work better in some printers than in others. For example, filament made from a PET soda bottle will be harder and more brittle than the PETG that's preferred for 3D printing, so you might have better luck using it in a printer with a direct extruder rather than one with a Bowden setup. |
19,025 | <p>I'd like to force Klipper to perform power on (using <code>M80</code>) before homing. For this purpose I'm trying to override <code>G28</code>:</p>
<pre><code>[gcode_macro G28]
rename_existing: G28_BASE
gcode:
M80
G28_BASE { rawparams }
</code></pre>
<p>But for some reason this does not work, I'm getting the following error:</p>
<pre><code>G-Code macro rename of different types ('G28' vs 'G28_BASE')
</code></pre>
<p>Isn't <code>G28</code> overridable? Is there any other way to achieve the desired behavior?</p>
| [
{
"answer_id": 19026,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 11157,
"author_profile": "https://3dprinting.stackexchange.com/users/11157",
"pm_score": 3,
"selected": true,
"text": "<p>Because of the way parameters work differently (<code>Sx</code> vs <code>NAME=x</code>) for gcode style commands vs Klipper extended ones, the rename has to be to the "same type" of command. <code>G28_BASE</code> does not fit the pattern to be considered a "gcode style" one. Use <code>G9028</code> or <code>G28.1</code> or something instead and it should work.</p>\n"
},
{
"answer_id": 19097,
"author": "FarO",
"author_id": 2338,
"author_profile": "https://3dprinting.stackexchange.com/users/2338",
"pm_score": 1,
"selected": false,
"text": "<p>Besides using a different macro, it is also possible to use <a href=\"https://www.klipper3d.org/Config_Reference.html#homing_override\" rel=\"nofollow noreferrer\">[homing_override]</a> which allows you to redefine the homing sequence.</p>\n<p>You can write a simple homing_override like (untested!)</p>\n<pre><code>[homing_override]\naxes: xyz\ngcode:\n M80\n G28\n</code></pre>\n<p>and you are done.</p>\n<p>Be aware that this very simple override will home all axes every time homing is called: "G28 X0" will home also Y and Z. You can put checks to home only what is requested, see <a href=\"https://github.com/zellneralex/klipper_config/blob/master/homing.cfg\" rel=\"nofollow noreferrer\">here</a> but it become more involved.</p>\n"
}
] | 2022/02/27 | [
"https://3dprinting.stackexchange.com/questions/19025",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/5033/"
] | I'd like to force Klipper to perform power on (using `M80`) before homing. For this purpose I'm trying to override `G28`:
```
[gcode_macro G28]
rename_existing: G28_BASE
gcode:
M80
G28_BASE { rawparams }
```
But for some reason this does not work, I'm getting the following error:
```
G-Code macro rename of different types ('G28' vs 'G28_BASE')
```
Isn't `G28` overridable? Is there any other way to achieve the desired behavior? | Because of the way parameters work differently (`Sx` vs `NAME=x`) for gcode style commands vs Klipper extended ones, the rename has to be to the "same type" of command. `G28_BASE` does not fit the pattern to be considered a "gcode style" one. Use `G9028` or `G28.1` or something instead and it should work. |
19,048 | <p>OK here's some background of the problem:</p>
<p>Symptoms:</p>
<ul>
<li><p>All retracts on the extruder produce a screeching noise. The extruder extrudes normally all other times.</p>
</li>
<li><p>Any fast move on the Z-axis also produces a screeching noise and the Z-axis will move normally at all other times.</p>
</li>
<li><p>This appears to happen regardless of any printing state whether the heaters are on or not it will still occur it even happens during the ABL process.</p>
</li>
</ul>
<p>Specifications of the printer:</p>
<ul>
<li>Mainboard: MKS Gen L V2</li>
<li>Drivers: TMC2209 UART</li>
<li>Stepper motors: Stepperonline 17HS15-1504S 1.8 deg 1.5A</li>
<li>Pulleys: GT2 16T</li>
<li>Leadscrew: 2 mm pitch T8</li>
<li>Hotend: E3D V6</li>
</ul>
<p>OK so basically I performed an upgrade of my stepper drivers as well as the leadscrew and pulleys on my 3D printer which was originally a Tevo tornado and at the start of every print I would experience a loud screeching noise coming from the Z-axis and I originally identified it to be a single line in my G-code that would only trigger the screech if it was preceded by another line and by commenting out the first line I was able to start printing</p>
<p>Lines in question:</p>
<pre><code>G1 X3 Y1 Z15 F9000 ; Move safe Z height to shear strings
G0 X1 Y1 Z0.2 F9000 ; Move in 1mm from edge and up [z] 0.2mm
</code></pre>
<p>However, while I was able to start printing, I soon found out that the extruder was doing the same thing with every retract it would create a loud screech and the filament wouldn't be retracted this caused heavy stringing as well as poor layer adhesion resulting in prints failing. I figured the problem was with the version of Marlin I was using so I attempted to use the latest bug fix. However, I was still experiencing the same problems. I attempted to see if the stepper current was the problem and after identifying that the stepper current was not the cause of the problem, I figured I needed to replace the stepper motors and after replacing the stepper motors the problem still remained. I figured the problem must be with Marlin so I attempted to use Klipper. However, I am still experiencing the same and now I can't even complete a mesh bed leveling as the movements that Klipper uses are triggering the loud screeching and causing the steppers to freeze up.</p>
<p>I am unsure as to what could be causing this as I think I've checked everything that could be causing it so I'm not quite sure how to proceed I've also made a video that should show the problem in action. So I guess I'm wondering what's my next troubleshooting step?</p>
<p><div class="youtube-embed"><div>
<iframe width="640px" height="395px" src="https://www.youtube.com/embed/v_vXF8f9GdQ?start=0"></iframe>
</div></div></p>
<p>EDIT: Updates</p>
<p>I have tried changing the drivers back to TMC2208s there have been no changes on both Kilpper and Marlin.</p>
<p>I tried switching to an MKS Gen L V2.1 in case it was a mainboard problem. sill experiencing problems</p>
<p>Marlin Config</p>
<p>Configuration.H
<a href="https://paste-bin.xyz/41662" rel="nofollow noreferrer">https://paste-bin.xyz/41662</a></p>
<p>Configuration_ADV.H
<a href="https://paste-bin.xyz/41663" rel="nofollow noreferrer">https://paste-bin.xyz/41663</a></p>
<p>Klipper Config
<a href="https://paste-bin.xyz/41677" rel="nofollow noreferrer">https://paste-bin.xyz/41677</a></p>
<p>Edit:</p>
<p>The only other thing I think I can try is running the TMC2209s in standalone mode</p>
| [
{
"answer_id": 19030,
"author": "Zeiss Ikon",
"author_id": 28508,
"author_profile": "https://3dprinting.stackexchange.com/users/28508",
"pm_score": 3,
"selected": false,
"text": "<p>If you have an empty spool of the same brand, you could weigh the empty spool and the one you're trying to "measure" to get an approximate weight of the remaining filament. Divide by the (presumably available from manufacturer) weight per meter to get a rough length in meters, if that's more useful to you than weight.</p>\n"
},
{
"answer_id": 19034,
"author": "user10489",
"author_id": 28397,
"author_profile": "https://3dprinting.stackexchange.com/users/28397",
"pm_score": 2,
"selected": false,
"text": "<p>If you are down to one layer of filament, count the number of loops left on the spool, and multiply by the circumference of the spool to get the length. (<span class=\"math-container\">$ \\pi \\times diameter \\times loops $</span>)</p>\n<p>This can work if you have more than one layer and know the core diameter and the outer diameter of the filament left, but there would be some integration and a lot of estimation.</p>\n"
},
{
"answer_id": 19035,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 11157,
"author_profile": "https://3dprinting.stackexchange.com/users/11157",
"pm_score": 2,
"selected": false,
"text": "<p>Some filament vendors put a window to see the remaining spooled filament with a decal showing graduations to match how much is left based on the diameter visible. You could do the same as a printed (in the paper sense) insert you slip along the <em>inside</em> of any spool between the filament and outer wall. You just need to compute the relationship between diameter and amount of filament based on the filament diameter and the number of turns per layer. Or you could just copy the design from a vendor who does this and figure it will be close enough.</p>\n"
},
{
"answer_id": 19038,
"author": "FarO",
"author_id": 2338,
"author_profile": "https://3dprinting.stackexchange.com/users/2338",
"pm_score": 2,
"selected": false,
"text": "<p>If you use klipper you can use <a href=\"https://github.com/zellneralex/klipper_config/blob/master/printtime.cfg\" rel=\"nofollow noreferrer\">this script</a> (by zellneralex) to calculate the filament length used since the last manual reset. Obviously it works with a single spool, if you switch spools it doesn't work.</p>\n<p>If you want to know how much filament is left in the spool, the exact formula based on inner radius of the spool <span class=\"math-container\">$r_{int}$</span> and outer radius of the spool when new <span class=\"math-container\">$r_{ext}$</span> and based on the current outer radius of the remaining filament <span class=\"math-container\">$x$</span> should be:</p>\n<p><span class=\"math-container\">$$ 100 \\left( \\frac{x-r_{int}}{r_{ext}-r_{int}} \\right)^2 $$</span></p>\n<p>You can see that you get 100% when <span class=\"math-container\">$x=r_{ext}$</span> (spool is new) and 0% when <span class=\"math-container\">$x=r_{int}$</span>.</p>\n<p>It's a simple integration in <span class=\"math-container\">$(x-x_0)\\,dx$</span>.</p>\n"
},
{
"answer_id": 19040,
"author": "Perry Webb",
"author_id": 15075,
"author_profile": "https://3dprinting.stackexchange.com/users/15075",
"pm_score": 0,
"selected": false,
"text": "<p>Besides using the window on a spool that estimates the amount of filament left, I've used large calipers to measure the diameter of an empty spool and the diameter of the filament left on the spool.</p>\n"
},
{
"answer_id": 19043,
"author": "Paul",
"author_id": 33375,
"author_profile": "https://3dprinting.stackexchange.com/users/33375",
"pm_score": 1,
"selected": false,
"text": "<p>I made an Excel spreadsheet that calculates this based on the spool dimensions. You can download it <a href=\"http://www.brownsbrain.com/Length%20on%20Spool%20Public.xlsx\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>There are products available that will keep track of the length of spools once you give it a starting length. The starting length could come from the spreadsheet.</p>\n"
},
{
"answer_id": 19311,
"author": "Ole Mak",
"author_id": 33983,
"author_profile": "https://3dprinting.stackexchange.com/users/33983",
"pm_score": 0,
"selected": false,
"text": "<p>Why not use a database online with a filament consumption counter?\nSee this <a href=\"https://www.etsy.com/ca/listing/1216011789/fdb-22-3d-printers-filament-consumption?ga_order=most_relevant&ga_search_type=all&ga_view_type=gallery&ga_search_query=FDB-22&ref=sr_gallery-1-1&organic_search_click=1\" rel=\"nofollow noreferrer\">link</a>.</p>\n<p>You can create a database without buying counters. I have two printers an Ender and Mega Zero and 2 counters that automatically consume the selected filaments.</p>\n<p>Very cool tool. I love it</p>\n"
}
] | 2022/03/04 | [
"https://3dprinting.stackexchange.com/questions/19048",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/33395/"
] | OK here's some background of the problem:
Symptoms:
* All retracts on the extruder produce a screeching noise. The extruder extrudes normally all other times.
* Any fast move on the Z-axis also produces a screeching noise and the Z-axis will move normally at all other times.
* This appears to happen regardless of any printing state whether the heaters are on or not it will still occur it even happens during the ABL process.
Specifications of the printer:
* Mainboard: MKS Gen L V2
* Drivers: TMC2209 UART
* Stepper motors: Stepperonline 17HS15-1504S 1.8 deg 1.5A
* Pulleys: GT2 16T
* Leadscrew: 2 mm pitch T8
* Hotend: E3D V6
OK so basically I performed an upgrade of my stepper drivers as well as the leadscrew and pulleys on my 3D printer which was originally a Tevo tornado and at the start of every print I would experience a loud screeching noise coming from the Z-axis and I originally identified it to be a single line in my G-code that would only trigger the screech if it was preceded by another line and by commenting out the first line I was able to start printing
Lines in question:
```
G1 X3 Y1 Z15 F9000 ; Move safe Z height to shear strings
G0 X1 Y1 Z0.2 F9000 ; Move in 1mm from edge and up [z] 0.2mm
```
However, while I was able to start printing, I soon found out that the extruder was doing the same thing with every retract it would create a loud screech and the filament wouldn't be retracted this caused heavy stringing as well as poor layer adhesion resulting in prints failing. I figured the problem was with the version of Marlin I was using so I attempted to use the latest bug fix. However, I was still experiencing the same problems. I attempted to see if the stepper current was the problem and after identifying that the stepper current was not the cause of the problem, I figured I needed to replace the stepper motors and after replacing the stepper motors the problem still remained. I figured the problem must be with Marlin so I attempted to use Klipper. However, I am still experiencing the same and now I can't even complete a mesh bed leveling as the movements that Klipper uses are triggering the loud screeching and causing the steppers to freeze up.
I am unsure as to what could be causing this as I think I've checked everything that could be causing it so I'm not quite sure how to proceed I've also made a video that should show the problem in action. So I guess I'm wondering what's my next troubleshooting step?
EDIT: Updates
I have tried changing the drivers back to TMC2208s there have been no changes on both Kilpper and Marlin.
I tried switching to an MKS Gen L V2.1 in case it was a mainboard problem. sill experiencing problems
Marlin Config
Configuration.H
<https://paste-bin.xyz/41662>
Configuration\_ADV.H
<https://paste-bin.xyz/41663>
Klipper Config
<https://paste-bin.xyz/41677>
Edit:
The only other thing I think I can try is running the TMC2209s in standalone mode | If you have an empty spool of the same brand, you could weigh the empty spool and the one you're trying to "measure" to get an approximate weight of the remaining filament. Divide by the (presumably available from manufacturer) weight per meter to get a rough length in meters, if that's more useful to you than weight. |
19,353 | <p>Most of the guides I can find are just canned responses to specific questions. Instead I'm looking for something meant to teach good fundamental understanding and core needed skills. Beginner's guides are common in other hobbies but I am having trouble finding one for 3d printing.</p>
| [
{
"answer_id": 19354,
"author": "Kilisi",
"author_id": 31811,
"author_profile": "https://3dprinting.stackexchange.com/users/31811",
"pm_score": 0,
"selected": false,
"text": "<p>Thera are plenty of such guides. But from necessity they deal with specifics, there are too many things to cover otherwise.</p>\n<p>Multiple types of printers, multiple brands, multiple slicers, multiple ways of modelling etc,. With more all the time. Reading up on something that tells me how to model and slice in Freecad & Creality, when I'm using Blender & Cura is a waste of time.</p>\n<p>Generic instructions that apply to everything are so vague as to be essentially useless. (Plenty of those online though)</p>\n"
},
{
"answer_id": 19357,
"author": "Criggie",
"author_id": 12956,
"author_profile": "https://3dprinting.stackexchange.com/users/12956",
"pm_score": 2,
"selected": true,
"text": "<p>Here's a brief outline I threw out in chat once. I'm marking this as a "community Wiki" answer so feel free to edit.</p>\n<p>It is not a full Primer, so should date better than a Word6.0 manual.</p>\n<hr />\n<p>Start by reading the instructions that came with your printer. There's a high chance that some assembly is required, and if you get something wrong then things may nor work right later. Some brands come complete, some are better than others in this regard. Take your time.</p>\n<p>For most people, they spend the first couple of weeks failing prints for multiple reasons. For me it was bed levelling and getting the first layer-adhesion, and filament tension.</p>\n<p>So work on getting the bed levelled, work out how much gluestick or tape your filament needs to work, and what temperatures work in your environment.</p>\n<p>I use 210 °C on the hotend for PLA+ and 60 °C bed temp, though others get away with 190 °C on the hotend and 50 °C on the bed. My printer is in a garage though.</p>\n<p>Try and print a 20 mm cube or a benchy.</p>\n<p>After that, explore <a href=\"http://thingiverse.com\" rel=\"nofollow noreferrer\">http://thingiverse.com</a> or <a href=\"http://thangs.com\" rel=\"nofollow noreferrer\">http://thangs.com</a> looking for pre-made stuff that you would benefit from. Start small.</p>\n<p>The Grab Toy Infinite is a great starter - it's very forgiving about tolerances, and kids like it. Expect rough handling to break it.</p>\n<p>When you're happy printing other people's things, identify some needs of your own. In fact, make up a document / draught email / notepad of ideas of things to print. I add stuff to mine all the time.</p>\n<p>When you've got a need that no one else can fill, you can start designing your own item and do the whole</p>\n<pre><code>idea --> ||: (re)design --> implement --> test --> curse :|| success!! loop. \n</code></pre>\n<p>Many people bang on about expensive fancy software, but you can make a perfectly adequate part using <a href=\"http://tinkercad.com/\" rel=\"nofollow noreferrer\">http://tinkercad.com/</a> as a grounding.</p>\n<p>For example, I had too many spare hacksaw blades and none of the "holders" I could buy were perfect, nor even close. Here's my output:</p>\n<p><a href=\"https://www.tinkercad.com/things/9yQMmxRv4Lz-spare-hacksaw-blade-holder\" rel=\"nofollow noreferrer\">https://www.tinkercad.com/things/9yQMmxRv4Lz-spare-hacksaw-blade-holder</a></p>\n<p>Like many things in making, expect to fail and learn and do it again.</p>\n<p>Sometimes it looks like we buy printers to print things for the printers for printing things for the printers...repeat.</p>\n<p>Look for needs in your life and design something to fill them. It's most satisfying.</p>\n<p>There's a huge gap between Functional prints, which do a job, and pretty prints which are just to look nice.</p>\n<p>Functional things are great - you can therefore justify the cost of more printer upgrades. LOOK AT ALL THE MONEY WE SAVED!</p>\n<p>But overall enjoy yourself and the time you spend making things.</p>\n"
}
] | 2022/05/07 | [
"https://3dprinting.stackexchange.com/questions/19353",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/34019/"
] | Most of the guides I can find are just canned responses to specific questions. Instead I'm looking for something meant to teach good fundamental understanding and core needed skills. Beginner's guides are common in other hobbies but I am having trouble finding one for 3d printing. | Here's a brief outline I threw out in chat once. I'm marking this as a "community Wiki" answer so feel free to edit.
It is not a full Primer, so should date better than a Word6.0 manual.
---
Start by reading the instructions that came with your printer. There's a high chance that some assembly is required, and if you get something wrong then things may nor work right later. Some brands come complete, some are better than others in this regard. Take your time.
For most people, they spend the first couple of weeks failing prints for multiple reasons. For me it was bed levelling and getting the first layer-adhesion, and filament tension.
So work on getting the bed levelled, work out how much gluestick or tape your filament needs to work, and what temperatures work in your environment.
I use 210 °C on the hotend for PLA+ and 60 °C bed temp, though others get away with 190 °C on the hotend and 50 °C on the bed. My printer is in a garage though.
Try and print a 20 mm cube or a benchy.
After that, explore <http://thingiverse.com> or <http://thangs.com> looking for pre-made stuff that you would benefit from. Start small.
The Grab Toy Infinite is a great starter - it's very forgiving about tolerances, and kids like it. Expect rough handling to break it.
When you're happy printing other people's things, identify some needs of your own. In fact, make up a document / draught email / notepad of ideas of things to print. I add stuff to mine all the time.
When you've got a need that no one else can fill, you can start designing your own item and do the whole
```
idea --> ||: (re)design --> implement --> test --> curse :|| success!! loop.
```
Many people bang on about expensive fancy software, but you can make a perfectly adequate part using <http://tinkercad.com/> as a grounding.
For example, I had too many spare hacksaw blades and none of the "holders" I could buy were perfect, nor even close. Here's my output:
<https://www.tinkercad.com/things/9yQMmxRv4Lz-spare-hacksaw-blade-holder>
Like many things in making, expect to fail and learn and do it again.
Sometimes it looks like we buy printers to print things for the printers for printing things for the printers...repeat.
Look for needs in your life and design something to fill them. It's most satisfying.
There's a huge gap between Functional prints, which do a job, and pretty prints which are just to look nice.
Functional things are great - you can therefore justify the cost of more printer upgrades. LOOK AT ALL THE MONEY WE SAVED!
But overall enjoy yourself and the time you spend making things. |
19,359 | <p>Looking to print a new part for a home appliance. There's going to need to be a new model created with the customizations made, but the model (after printing) will have to fit where the old part was. Is there any 3D modeling software that is better for this purpose? Will I just have to guess at proper proportions and hand-adjust the scaling of each dimension and angle through trial and error until a version fits?</p>
| [
{
"answer_id": 19354,
"author": "Kilisi",
"author_id": 31811,
"author_profile": "https://3dprinting.stackexchange.com/users/31811",
"pm_score": 0,
"selected": false,
"text": "<p>Thera are plenty of such guides. But from necessity they deal with specifics, there are too many things to cover otherwise.</p>\n<p>Multiple types of printers, multiple brands, multiple slicers, multiple ways of modelling etc,. With more all the time. Reading up on something that tells me how to model and slice in Freecad & Creality, when I'm using Blender & Cura is a waste of time.</p>\n<p>Generic instructions that apply to everything are so vague as to be essentially useless. (Plenty of those online though)</p>\n"
},
{
"answer_id": 19357,
"author": "Criggie",
"author_id": 12956,
"author_profile": "https://3dprinting.stackexchange.com/users/12956",
"pm_score": 2,
"selected": true,
"text": "<p>Here's a brief outline I threw out in chat once. I'm marking this as a "community Wiki" answer so feel free to edit.</p>\n<p>It is not a full Primer, so should date better than a Word6.0 manual.</p>\n<hr />\n<p>Start by reading the instructions that came with your printer. There's a high chance that some assembly is required, and if you get something wrong then things may nor work right later. Some brands come complete, some are better than others in this regard. Take your time.</p>\n<p>For most people, they spend the first couple of weeks failing prints for multiple reasons. For me it was bed levelling and getting the first layer-adhesion, and filament tension.</p>\n<p>So work on getting the bed levelled, work out how much gluestick or tape your filament needs to work, and what temperatures work in your environment.</p>\n<p>I use 210 °C on the hotend for PLA+ and 60 °C bed temp, though others get away with 190 °C on the hotend and 50 °C on the bed. My printer is in a garage though.</p>\n<p>Try and print a 20 mm cube or a benchy.</p>\n<p>After that, explore <a href=\"http://thingiverse.com\" rel=\"nofollow noreferrer\">http://thingiverse.com</a> or <a href=\"http://thangs.com\" rel=\"nofollow noreferrer\">http://thangs.com</a> looking for pre-made stuff that you would benefit from. Start small.</p>\n<p>The Grab Toy Infinite is a great starter - it's very forgiving about tolerances, and kids like it. Expect rough handling to break it.</p>\n<p>When you're happy printing other people's things, identify some needs of your own. In fact, make up a document / draught email / notepad of ideas of things to print. I add stuff to mine all the time.</p>\n<p>When you've got a need that no one else can fill, you can start designing your own item and do the whole</p>\n<pre><code>idea --> ||: (re)design --> implement --> test --> curse :|| success!! loop. \n</code></pre>\n<p>Many people bang on about expensive fancy software, but you can make a perfectly adequate part using <a href=\"http://tinkercad.com/\" rel=\"nofollow noreferrer\">http://tinkercad.com/</a> as a grounding.</p>\n<p>For example, I had too many spare hacksaw blades and none of the "holders" I could buy were perfect, nor even close. Here's my output:</p>\n<p><a href=\"https://www.tinkercad.com/things/9yQMmxRv4Lz-spare-hacksaw-blade-holder\" rel=\"nofollow noreferrer\">https://www.tinkercad.com/things/9yQMmxRv4Lz-spare-hacksaw-blade-holder</a></p>\n<p>Like many things in making, expect to fail and learn and do it again.</p>\n<p>Sometimes it looks like we buy printers to print things for the printers for printing things for the printers...repeat.</p>\n<p>Look for needs in your life and design something to fill them. It's most satisfying.</p>\n<p>There's a huge gap between Functional prints, which do a job, and pretty prints which are just to look nice.</p>\n<p>Functional things are great - you can therefore justify the cost of more printer upgrades. LOOK AT ALL THE MONEY WE SAVED!</p>\n<p>But overall enjoy yourself and the time you spend making things.</p>\n"
}
] | 2022/05/08 | [
"https://3dprinting.stackexchange.com/questions/19359",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/34019/"
] | Looking to print a new part for a home appliance. There's going to need to be a new model created with the customizations made, but the model (after printing) will have to fit where the old part was. Is there any 3D modeling software that is better for this purpose? Will I just have to guess at proper proportions and hand-adjust the scaling of each dimension and angle through trial and error until a version fits? | Here's a brief outline I threw out in chat once. I'm marking this as a "community Wiki" answer so feel free to edit.
It is not a full Primer, so should date better than a Word6.0 manual.
---
Start by reading the instructions that came with your printer. There's a high chance that some assembly is required, and if you get something wrong then things may nor work right later. Some brands come complete, some are better than others in this regard. Take your time.
For most people, they spend the first couple of weeks failing prints for multiple reasons. For me it was bed levelling and getting the first layer-adhesion, and filament tension.
So work on getting the bed levelled, work out how much gluestick or tape your filament needs to work, and what temperatures work in your environment.
I use 210 °C on the hotend for PLA+ and 60 °C bed temp, though others get away with 190 °C on the hotend and 50 °C on the bed. My printer is in a garage though.
Try and print a 20 mm cube or a benchy.
After that, explore <http://thingiverse.com> or <http://thangs.com> looking for pre-made stuff that you would benefit from. Start small.
The Grab Toy Infinite is a great starter - it's very forgiving about tolerances, and kids like it. Expect rough handling to break it.
When you're happy printing other people's things, identify some needs of your own. In fact, make up a document / draught email / notepad of ideas of things to print. I add stuff to mine all the time.
When you've got a need that no one else can fill, you can start designing your own item and do the whole
```
idea --> ||: (re)design --> implement --> test --> curse :|| success!! loop.
```
Many people bang on about expensive fancy software, but you can make a perfectly adequate part using <http://tinkercad.com/> as a grounding.
For example, I had too many spare hacksaw blades and none of the "holders" I could buy were perfect, nor even close. Here's my output:
<https://www.tinkercad.com/things/9yQMmxRv4Lz-spare-hacksaw-blade-holder>
Like many things in making, expect to fail and learn and do it again.
Sometimes it looks like we buy printers to print things for the printers for printing things for the printers...repeat.
Look for needs in your life and design something to fill them. It's most satisfying.
There's a huge gap between Functional prints, which do a job, and pretty prints which are just to look nice.
Functional things are great - you can therefore justify the cost of more printer upgrades. LOOK AT ALL THE MONEY WE SAVED!
But overall enjoy yourself and the time you spend making things. |
19,380 | <p>I want to put relief text on curved surface but can't find way to do that in OpenSCAD. I'm aware it's possible to bend text in Blender and then <code>import stl</code>, but I don't like this workflow. I found sort of working solution but it's not perfect.</p>
<pre><code>$fn=50;
module bend_text(caption, angle, text_height, text_width, text_depth, steps=10, k=1) {
dh = text_height / steps;
r = text_height / (angle * PI / 180);
h0 = - text_height / 2;
translate([0, 0, -r])
rotate([angle / 2, 0, 0])
for(i=[0:steps-1]) {
rotate([-i * angle/steps, 0, 0])
translate([0, -(dh * i + h0), r / k])
intersection() {
linear_extrude(text_depth)
text(caption, valign="center", halign="center");
translate([0, dh * i + h0, 0])
cube([text_width, dh, text_width], center=true);
}
}
}
bend_text("test", angle=90, text_height=9, text_width=30, text_depth=1, steps=10, k=1.1);
</code></pre>
<p><a href="https://i.stack.imgur.com/0zq1h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0zq1h.png" alt="test" /></a></p>
<p>Is there better way?</p>
| [
{
"answer_id": 19364,
"author": "Criggie",
"author_id": 12956,
"author_profile": "https://3dprinting.stackexchange.com/users/12956",
"pm_score": 3,
"selected": true,
"text": "<p>Yes - you should be able to turn the extruder by hand when it is unplugged and therefore not powered.</p>\n<p>The V2 comes with a blue plastic knob for this purpose, it may be too small to turn the shaft by hand.</p>\n<p>When powered and "steppers enabled" the motors need a lot more force to overcome, but even that can be done by hand or a machine crash.</p>\n<p>If you can't turn the extruder at all, its probably toast. That you've tested other ports on the board is excellent problem solving.</p>\n<p>Whatever damaged the motor has likely damaged the board too, or vise versa.</p>\n<p>You likely need both parts replaced to get this printer working again. Could be expensive - you might want to compare cost of parts with cost of a new printer, remembering there may be other non-functional components still undiscovered.</p>\n<p>Plausibly, with a dead extruder, you could slap a laser on this unit and make it a dedicated burner. The creality laser module is around $50 USD.</p>\n"
},
{
"answer_id": 19366,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 11157,
"author_profile": "https://3dprinting.stackexchange.com/users/11157",
"pm_score": 1,
"selected": false,
"text": "<p>Criggie's answer is basically correct, but I disagree with the conclusion that it:</p>\n<blockquote>\n<p>Could be expensive - you might want to compare cost of parts with cost of a new printer, remembering there may be other non-functional components still undiscovered.</p>\n</blockquote>\n<p>If you want to turn the Ender 3 into a decent printer, the controller board is one of the components you want to replace anyway, since it comes with either (old models) extremely loud and poorly performing A4988 stepper drivers or (newer models) TMC2208 stepper drivers hard-wired in a mode where they don't work well and malfunction if you enable Linear Advance (which is critical to getting decent prints on a bowden extruder system). Good boardsthat are exact fits for the housing and cable connectors, with TMC2209 steppers that lack the above problems, can be had for $35 or so.</p>\n<p>If the motor is dead, that's a pain but not expensive to replace. Equivalent motors are available for $15 or so all over the place, or you could make the upgrade to a light-weight geared direct drive extruder with pancake stepper instead of the large NEMA 17 (which negates pretty much all of the disadvantages of direct drive and gives you a much better printer than you started with).</p>\n"
}
] | 2022/05/12 | [
"https://3dprinting.stackexchange.com/questions/19380",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/34129/"
] | I want to put relief text on curved surface but can't find way to do that in OpenSCAD. I'm aware it's possible to bend text in Blender and then `import stl`, but I don't like this workflow. I found sort of working solution but it's not perfect.
```
$fn=50;
module bend_text(caption, angle, text_height, text_width, text_depth, steps=10, k=1) {
dh = text_height / steps;
r = text_height / (angle * PI / 180);
h0 = - text_height / 2;
translate([0, 0, -r])
rotate([angle / 2, 0, 0])
for(i=[0:steps-1]) {
rotate([-i * angle/steps, 0, 0])
translate([0, -(dh * i + h0), r / k])
intersection() {
linear_extrude(text_depth)
text(caption, valign="center", halign="center");
translate([0, dh * i + h0, 0])
cube([text_width, dh, text_width], center=true);
}
}
}
bend_text("test", angle=90, text_height=9, text_width=30, text_depth=1, steps=10, k=1.1);
```
[![test](https://i.stack.imgur.com/0zq1h.png)](https://i.stack.imgur.com/0zq1h.png)
Is there better way? | Yes - you should be able to turn the extruder by hand when it is unplugged and therefore not powered.
The V2 comes with a blue plastic knob for this purpose, it may be too small to turn the shaft by hand.
When powered and "steppers enabled" the motors need a lot more force to overcome, but even that can be done by hand or a machine crash.
If you can't turn the extruder at all, its probably toast. That you've tested other ports on the board is excellent problem solving.
Whatever damaged the motor has likely damaged the board too, or vise versa.
You likely need both parts replaced to get this printer working again. Could be expensive - you might want to compare cost of parts with cost of a new printer, remembering there may be other non-functional components still undiscovered.
Plausibly, with a dead extruder, you could slap a laser on this unit and make it a dedicated burner. The creality laser module is around $50 USD. |
19,411 | <p>Ender 3 Pro, PLA, temps 200 °C and 60 °C.</p>
<p>I want to not heat the nozzle until after Auto Bed Leveling (CR Touch) is complete. I can do that in the start G-code, but by then, Cura has already heated the nozzle to the temp specified under material and filament starts oozing out during bed leveling. I'd rather set a variable to that value and call it with <code>M104</code> when I'm ready.</p>
<p>This is the start of Cura's g-code:</p>
<pre><code>;FLAVOR:Marlin
;TIME:2888
;Filament used: 1.96332m
;Layer height: 0.2
;MINX:93.266
;MINY:10.195
;MINZ:0.2
;MAXX:126.734
;MAXY:210.658
;MAXZ:4.2
;Generated with Cura_SteamEngine 4.13.1
M140 S60
M105
M190 S60
M104 S200
M105
M109 S200
M82 ;absolute extrusion mode
; Ender 3 Custom Start G-code
G92 E0 ; Reset Extruder
G28 ; Home all axes
G29 ; Auto Bed Level (CR Touch)
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position
G1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line
G1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little
G1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line
G92 E0 ; Reset Extruder
...
</code></pre>
<p>The lines right after "Generated with Cura_SteamEngine" are the ones I'd like to change but I can't find them in the Cura app. I know that 60 °C and 200 °C are the temps defined for bed and nozzle. Cura inserts them as constants for the <code>M140</code> and <code>M104</code> commands. I'd like Cura to set variables to those values (like <code>{bed_temp} = 60</code>) so I can refer to that variable when I insert the <code>M140</code> command in my Custom Start G-code. Can that be done?</p>
<p>A related question was asked a few years ago and part of the start code example then was:</p>
<pre><code>; Ender 3 Custom Start G-code
M104 S{material_print_temperature_layer_0} ; Set Extruder temperature
M140 S{material_bed_temperature_layer_0} ; Set Heat Bed temperature
G28 ; Home all axes
G29 ; BLTOUCH Mesh Generation
M190 S{material_bed_temperature_layer_0} ; Wait for Heat Bed temperature
M109 S{material_print_temperature_layer_0} ; Wait for Extruder temperature
</code></pre>
<p>The variable <code>{material_bed_temperature_layer_0}</code> was already set but I don't know where or how that was done.</p>
| [
{
"answer_id": 19412,
"author": "0scar",
"author_id": 5740,
"author_profile": "https://3dprinting.stackexchange.com/users/5740",
"pm_score": 0,
"selected": false,
"text": "<p>Go to the <code>Settings</code> -> <code>Printers</code> menu from the top menu,</p>\n<p><a href=\"https://i.stack.imgur.com/jmivX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jmivX.png\" alt=\"enter image description here\" /></a></p>\n<p>select your active printer (or <code>Activate</code> it) and manage your printer trough <code>Machine Settings</code>.</p>\n<p><a href=\"https://i.stack.imgur.com/L3CUC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L3CUC.png\" alt=\"enter image description here\" /></a></p>\n<p>It will open the printer settings,</p>\n<p><a href=\"https://i.stack.imgur.com/rBjqg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rBjqg.png\" alt=\"enter image description here\" /></a></p>\n<p>there you are able to change the lines you want in the <code>Start G-code</code> section.</p>\n<p>Note the default Start G-code doesn't include heating up the bed and core, you need to add these after the <code>G29</code> in your case. Personally I use heat up bed and continue (<code>M140</code>), than heat up core and wait till temperature is reached (<code>M109</code>), then heat up and wait until bed temperature is reached (<code>M190</code>).</p>\n"
},
{
"answer_id": 19418,
"author": "RayW",
"author_id": 34216,
"author_profile": "https://3dprinting.stackexchange.com/users/34216",
"pm_score": 2,
"selected": false,
"text": "<p>I've sorted this out. <em>IF</em> I include my own heating commands in my start G-Code, Cura knows to NOT add its own heating commands at the start of the G-Code file.</p>\n<p>The variables I was referring to have dedicated names.\n<code>material_print_temperature_layer_0</code> is the printing (extruder/nozzle) temp set under Material in Cura.\n<code>material_bed_temperature_layer_0</code> is the build plate temp set under Material in Cura.</p>\n<p>Cura substitutes the values of those variables for the variable names in the G-code file.</p>\n<p>So to avoid filament ooze during auto bed leveling, I set the nozzle temp to 150 °C (hot, but lower than the defined printing temp and low enough to avoid ooze). I set the bed temp to its defined temp.</p>\n<p>Then I auto-level the bed.</p>\n<p>Then I heat the nozzle up to its defined printing temp and start the print job.</p>\n<p>This is my Start G-code:</p>\n<pre><code>; Ender 3 Custom Start G-code\nG92 E0 ; Reset Extruder\nG28 ; Home all axes\nM104 S150 ; Set Extruder temperature for bed leveling\nM140 S{material_bed_temperature_layer_0} ; Set Heat Bed temperature\nM109 S150 ; Wait for Extruder temperature for bed leveling\nM190 S{material_bed_temperature_layer_0} ; Wait for Heat Bed temperature\nG29 ; Auto Bed Level (CR Touch)\nM104 S{material_print_temperature_layer_0} ; Set Extruder temperature\nM109 S{material_print_temperature_layer_0} ; Wait for Extruder temperature\nG1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed\nG1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position\nG1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line\nG1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little\nG1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line\nG92 E0 ; Reset Extruder\nG1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed\nG1 X5 Y20 Z0.3 F5000.0 ; Move over to prevent blob squish\n</code></pre>\n<p>And this is how Cura writes the G-code file:</p>\n<pre><code>;FLAVOR:Marlin\n;TIME:2888\n;Filament used: 1.96332m\n;Layer height: 0.2\n;MINX:93.266\n;MINY:10.195\n;MINZ:0.2\n;MAXX:126.734\n;MAXY:210.658\n;MAXZ:4.2\n;Generated with Cura_SteamEngine 4.13.1\nM82 ;absolute extrusion mode\n; Ender 3 Custom Start G-code\nG92 E0 ; Reset Extruder\nG28 ; Home all axes\nM104 S150 ; Set Extruder temperature for bed leveling\nM140 S60 ; Set Heat Bed temperature\nM109 S150 ; Wait for Extruder temperature for bed leveling\nM190 S60 ; Wait for Heat Bed temperature\nG29 ; Auto Bed Level (CR Touch)\nM104 S200 ; Set Extruder temperature\nM109 S200 ; Wait for Extruder temperature\nG1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed\nG1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position\nG1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line\nG1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little\nG1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line\nG92 E0 ; Reset Extruder\nG1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed\nG1 X5 Y20 Z0.3 F5000.0 ; Move over to prevent blob squish\nG92 E0\n...\n</code></pre>\n<p>I hope this helps someone with a similar question.</p>\n<p>Cheers.</p>\n"
}
] | 2022/05/21 | [
"https://3dprinting.stackexchange.com/questions/19411",
"https://3dprinting.stackexchange.com",
"https://3dprinting.stackexchange.com/users/34216/"
] | Ender 3 Pro, PLA, temps 200 °C and 60 °C.
I want to not heat the nozzle until after Auto Bed Leveling (CR Touch) is complete. I can do that in the start G-code, but by then, Cura has already heated the nozzle to the temp specified under material and filament starts oozing out during bed leveling. I'd rather set a variable to that value and call it with `M104` when I'm ready.
This is the start of Cura's g-code:
```
;FLAVOR:Marlin
;TIME:2888
;Filament used: 1.96332m
;Layer height: 0.2
;MINX:93.266
;MINY:10.195
;MINZ:0.2
;MAXX:126.734
;MAXY:210.658
;MAXZ:4.2
;Generated with Cura_SteamEngine 4.13.1
M140 S60
M105
M190 S60
M104 S200
M105
M109 S200
M82 ;absolute extrusion mode
; Ender 3 Custom Start G-code
G92 E0 ; Reset Extruder
G28 ; Home all axes
G29 ; Auto Bed Level (CR Touch)
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position
G1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line
G1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little
G1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line
G92 E0 ; Reset Extruder
...
```
The lines right after "Generated with Cura\_SteamEngine" are the ones I'd like to change but I can't find them in the Cura app. I know that 60 °C and 200 °C are the temps defined for bed and nozzle. Cura inserts them as constants for the `M140` and `M104` commands. I'd like Cura to set variables to those values (like `{bed_temp} = 60`) so I can refer to that variable when I insert the `M140` command in my Custom Start G-code. Can that be done?
A related question was asked a few years ago and part of the start code example then was:
```
; Ender 3 Custom Start G-code
M104 S{material_print_temperature_layer_0} ; Set Extruder temperature
M140 S{material_bed_temperature_layer_0} ; Set Heat Bed temperature
G28 ; Home all axes
G29 ; BLTOUCH Mesh Generation
M190 S{material_bed_temperature_layer_0} ; Wait for Heat Bed temperature
M109 S{material_print_temperature_layer_0} ; Wait for Extruder temperature
```
The variable `{material_bed_temperature_layer_0}` was already set but I don't know where or how that was done. | I've sorted this out. *IF* I include my own heating commands in my start G-Code, Cura knows to NOT add its own heating commands at the start of the G-Code file.
The variables I was referring to have dedicated names.
`material_print_temperature_layer_0` is the printing (extruder/nozzle) temp set under Material in Cura.
`material_bed_temperature_layer_0` is the build plate temp set under Material in Cura.
Cura substitutes the values of those variables for the variable names in the G-code file.
So to avoid filament ooze during auto bed leveling, I set the nozzle temp to 150 °C (hot, but lower than the defined printing temp and low enough to avoid ooze). I set the bed temp to its defined temp.
Then I auto-level the bed.
Then I heat the nozzle up to its defined printing temp and start the print job.
This is my Start G-code:
```
; Ender 3 Custom Start G-code
G92 E0 ; Reset Extruder
G28 ; Home all axes
M104 S150 ; Set Extruder temperature for bed leveling
M140 S{material_bed_temperature_layer_0} ; Set Heat Bed temperature
M109 S150 ; Wait for Extruder temperature for bed leveling
M190 S{material_bed_temperature_layer_0} ; Wait for Heat Bed temperature
G29 ; Auto Bed Level (CR Touch)
M104 S{material_print_temperature_layer_0} ; Set Extruder temperature
M109 S{material_print_temperature_layer_0} ; Wait for Extruder temperature
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position
G1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line
G1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little
G1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line
G92 E0 ; Reset Extruder
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X5 Y20 Z0.3 F5000.0 ; Move over to prevent blob squish
```
And this is how Cura writes the G-code file:
```
;FLAVOR:Marlin
;TIME:2888
;Filament used: 1.96332m
;Layer height: 0.2
;MINX:93.266
;MINY:10.195
;MINZ:0.2
;MAXX:126.734
;MAXY:210.658
;MAXZ:4.2
;Generated with Cura_SteamEngine 4.13.1
M82 ;absolute extrusion mode
; Ender 3 Custom Start G-code
G92 E0 ; Reset Extruder
G28 ; Home all axes
M104 S150 ; Set Extruder temperature for bed leveling
M140 S60 ; Set Heat Bed temperature
M109 S150 ; Wait for Extruder temperature for bed leveling
M190 S60 ; Wait for Heat Bed temperature
G29 ; Auto Bed Level (CR Touch)
M104 S200 ; Set Extruder temperature
M109 S200 ; Wait for Extruder temperature
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X0.1 Y20 Z0.3 F5000.0 ; Move to start position
G1 X0.1 Y200.0 Z0.3 F1500.0 E15 ; Draw the first line
G1 X0.4 Y200.0 Z0.3 F5000.0 ; Move to side a little
G1 X0.4 Y20 Z0.3 F1500.0 E30 ; Draw the second line
G92 E0 ; Reset Extruder
G1 Z2.0 F3000 ; Move Z Axis up little to prevent scratching of Heat Bed
G1 X5 Y20 Z0.3 F5000.0 ; Move over to prevent blob squish
G92 E0
...
```
I hope this helps someone with a similar question.
Cheers. |
4 | <p>I want to assign the decimal variable "trans" to the double variable "this.Opacity".</p>
<pre class="lang-cs prettyprint-override"><code>decimal trans = trackBar1.Value / 5000;
this.Opacity = trans;
</code></pre>
<p>When I build the app it gives the following error:</p>
<blockquote>
<p>Cannot implicitly convert type decimal to double</p>
</blockquote>
| [
{
"answer_id": 7,
"author": "Kevin Dente",
"author_id": 9,
"author_profile": "https://Stackoverflow.com/users/9",
"pm_score": 10,
"selected": true,
"text": "<p>An explicit cast to <code>double</code> like this isn't necessary:</p>\n\n<pre><code>double trans = (double) trackBar1.Value / 5000.0;\n</code></pre>\n\n<p>Identifying the constant as <code>5000.0</code> (or as <code>5000d</code>) is sufficient:</p>\n\n<pre><code>double trans = trackBar1.Value / 5000.0;\ndouble trans = trackBar1.Value / 5000d;\n</code></pre>\n"
},
{
"answer_id": 78,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 6,
"selected": false,
"text": "<p>It sounds like <code>this.Opacity</code> is a double value, and the compiler doesn't like you trying to cram a decimal value into it.</p>\n"
},
{
"answer_id": 86,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 7,
"selected": false,
"text": "<p><strong>A more generic answer for the generic question "Decimal vs Double?":</strong></p>\n<p><strong>Decimal</strong> is for monetary calculations to preserve precision. <strong>Double</strong> is for scientific calculations that do not get affected by small differences. Since Double is a type that is native to the CPU (internal representation is stored in <em>base 2</em>), calculations made with Double perform better than Decimal (which is represented in <em>base 10</em> internally).</p>\n"
},
{
"answer_id": 2791,
"author": "andynil",
"author_id": 446,
"author_profile": "https://Stackoverflow.com/users/446",
"pm_score": 6,
"selected": false,
"text": "<p>In my opinion, it is desirable to be as explicit as possible. This adds clarity to the code and aids your fellow programmers who may eventually read it.</p>\n<p>In addition to (or instead of) appending a <code>.0</code> to the number, you can use <code>decimal.ToDouble()</code>.</p>\n<p>Here are some examples:</p>\n<pre><code>// Example 1\ndouble transparency = trackBar1.Value/5000;\nthis.Opacity = decimal.ToDouble(transparency);\n\n// Example 2 - with inline temp\nthis.Opacity = decimal.ToDouble(trackBar1.Value/5000);\n</code></pre>\n"
},
{
"answer_id": 7263,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 7,
"selected": false,
"text": "<p>Your code worked fine in VB.NET because it implicitly does any casts, while C# has both implicit and explicit ones.</p>\n\n<p>In C# the conversion from decimal to double is explicit as you lose accuracy. For instance 1.1 can't be accurately expressed as a double, but can as a decimal (see \"<a href=\"http://bizvprog.blogspot.com/2008/05/floating-point-numbers-more-inaccurate.html\" rel=\"noreferrer\">Floating point numbers - more inaccurate than you think</a>\" for the reason why).</p>\n\n<p>In VB the conversion was added for you by the compiler:</p>\n\n<pre><code>decimal trans = trackBar1.Value / 5000m;\nthis.Opacity = (double) trans;\n</code></pre>\n\n<p>That <code>(double)</code> has to be explicitly stated in C#, but can be <em>implied</em> by VB's more 'forgiving' compiler.</p>\n"
},
{
"answer_id": 110198,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 7,
"selected": false,
"text": "<p>Why are you dividing by 5000? Just set the TrackBar's Minimum and Maximum values between 0 and 100 and then divide the Value by 100 for the Opacity percentage. The minimum 20 example below prevents the form from becoming completely invisible:</p>\n\n<pre><code>private void Form1_Load(object sender, System.EventArgs e)\n{\n TrackBar1.Minimum = 20;\n TrackBar1.Maximum = 100;\n\n TrackBar1.LargeChange = 10;\n TrackBar1.SmallChange = 1;\n TrackBar1.TickFrequency = 5;\n}\n\nprivate void TrackBar1_Scroll(object sender, System.EventArgs e)\n{\n this.Opacity = TrackBar1.Value / 100;\n}\n</code></pre>\n"
},
{
"answer_id": 305467,
"author": "Dinah",
"author_id": 356,
"author_profile": "https://Stackoverflow.com/users/356",
"pm_score": 6,
"selected": false,
"text": "<p>You should use <code>5000.0</code> instead of <code>5000</code>.</p>\n"
},
{
"answer_id": 594436,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": false,
"text": "<p>You have two problems.</p>\n<p>Firstly, <code>Opacity</code> requires a double, not a decimal value. The compiler is telling you that while there is a conversion between decimal and double, it is an explicit conversion that you need to specify in order for it to work.</p>\n<p>Secondly, <code>TrackBar.Value</code> is an integer value and dividing an int by an int results in an int no matter what type of variable you assign it to. In this case there is an implicit cast from int to decimal or double, because there is no loss of precision when you do the cast. So the compiler doesn't complain. But the value you get is always 0, presumably, since <code>trackBar.Value</code> is always less than 5000.</p>\n<p>The solution is to change your code to use double (the native type for Opacity) and do floating point arithmetic by explicitly making the constant a double, which will have the effect of promoting the arithmetic or casting <code>trackBar.Value</code> to double, which will do the same thing or both. You don't need the intermediate variable unless it is used elsewhere. My guess is the compiler would optimize it away anyway.</p>\n<pre><code>trackBar.Opacity = (double)trackBar.Value / 5000.0;\n</code></pre>\n"
},
{
"answer_id": 7262112,
"author": "Darin Dimitrov",
"author_id": 29407,
"author_profile": "https://Stackoverflow.com/users/29407",
"pm_score": 6,
"selected": false,
"text": "<p>The <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.opacity\" rel=\"noreferrer\">Opacity</a> property is of double type:</p>\n\n<pre><code>double trans = trackBar1.Value / 5000.0;\nthis.Opacity = trans;\n</code></pre>\n\n<p>or simply:</p>\n\n<pre><code>this.Opacity = trackBar1.Value / 5000.0;\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>this.Opacity = trackBar1.Value / 5000d;\n</code></pre>\n\n<p>Notice that I am using <code>5000.0</code> (or <code>5000d</code>) to force a double division because <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.trackbar.value\" rel=\"noreferrer\"><code>trackBar1.Value</code></a> is an integer and it would perform an integer division and the result would be an integer.</p>\n"
},
{
"answer_id": 7262131,
"author": "ChrisF",
"author_id": 59303,
"author_profile": "https://Stackoverflow.com/users/59303",
"pm_score": 6,
"selected": false,
"text": "<p>Assuming you are using WinForms, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.opacity\" rel=\"noreferrer\"><code>Form.Opacity</code></a> is of type <code>double</code>, so you should use:</p>\n\n<pre><code>double trans = trackBar1.Value / 5000.0;\nthis.Opacity = trans;\n</code></pre>\n\n<p>Unless you need the value elsewhere, it's simpler to write:</p>\n\n<pre><code>this.Opacity = trackBar1.Value / 5000.0;\n</code></pre>\n\n<p>The reason the control doesn't work when you changed your code to simply be a double was because you had:</p>\n\n<pre><code>double trans = trackbar1.Value / 5000;\n</code></pre>\n\n<p>which interpreted the <code>5000</code> as an integer, and because <code>trackbar1.Value</code> is also an integer your <code>trans</code> value was always zero. By explicitly making the numeric a floating point value by adding the <code>.0</code> the compiler can now interpret it as a double and perform the proper calculation.</p>\n"
},
{
"answer_id": 9579950,
"author": "Danny Fox",
"author_id": 1091828,
"author_profile": "https://Stackoverflow.com/users/1091828",
"pm_score": 6,
"selected": false,
"text": "<p>The best solution is:</p>\n\n<pre><code>this.Opacity = decimal.ToDouble(trackBar1.Value/5000);\n</code></pre>\n"
},
{
"answer_id": 10568821,
"author": "Darryl",
"author_id": 1391700,
"author_profile": "https://Stackoverflow.com/users/1391700",
"pm_score": 6,
"selected": false,
"text": "<p>Since <code>Opacity</code> is a double value, I would just use a double from the outset and not cast at all, but be sure to use a double when dividing so you don't lose any precision:</p>\n<pre><code>Opacity = trackBar1.Value / 5000.0;\n</code></pre>\n"
},
{
"answer_id": 71840515,
"author": "Arnold Brown",
"author_id": 5049244,
"author_profile": "https://Stackoverflow.com/users/5049244",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Try the following code:</strong></p>\n<h3>Decimal values</h3>\n<pre><code>decimal d1 = 3234.3434m;\n</code></pre>\n<h3>Convert to double</h3>\n<pre><code>double r1 = Decimal.ToDouble(d1);\n</code></pre>\n"
},
{
"answer_id": 72996737,
"author": "David Rodrigues",
"author_id": 5768360,
"author_profile": "https://Stackoverflow.com/users/5768360",
"pm_score": 1,
"selected": false,
"text": "<p>OG Fact: <code>Double</code> type represents a wider range of possible values than <code>Decimal</code>.</p>\n<p><strong>Casting as Double</strong></p>\n<pre><code>decimal trans = trackBar1.Value / 5000m;\nthis.Opacity = (double) trans;\n</code></pre>\n<p><strong>Type Conversion</strong></p>\n<pre><code>decimal trans = trackBar1.Value / 5000m;\nthis.Opacity = decimal.ToDouble(trans);\n</code></pre>\n<p><strong>No explicit Cast/Conversion</strong></p>\n<p>In this case, adding 'd' in the end of the constant <code>5000d</code> or ".0" <code>5000.0</code> will identify the required Type. When there is no constant in the operation, just multiply your <code>decimal</code> variable by <code>1.0</code> or <code>1d</code>.</p>\n"
}
] | 2008/07/31 | [
"https://Stackoverflow.com/questions/4",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8/"
] | I want to assign the decimal variable "trans" to the double variable "this.Opacity".
```cs
decimal trans = trackBar1.Value / 5000;
this.Opacity = trans;
```
When I build the app it gives the following error:
>
> Cannot implicitly convert type decimal to double
>
>
> | An explicit cast to `double` like this isn't necessary:
```
double trans = (double) trackBar1.Value / 5000.0;
```
Identifying the constant as `5000.0` (or as `5000d`) is sufficient:
```
double trans = trackBar1.Value / 5000.0;
double trans = trackBar1.Value / 5000d;
``` |
9 | <p>Given a <code>DateTime</code> representing a person's birthday, how do I calculate their age in years?</p>
| [
{
"answer_id": 22,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 6,
"selected": false,
"text": "<p>The best way that I know of because of leap years and everything is:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime birthDate = new DateTime(2000,3,1);\nint age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);\n</code></pre>\n"
},
{
"answer_id": 229,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 7,
"selected": false,
"text": "<p>Another function, not by me but found on the web and refined it a bit:</p>\n\n<pre><code>public static int GetAge(DateTime birthDate)\n{\n DateTime n = DateTime.Now; // To avoid a race condition around midnight\n int age = n.Year - birthDate.Year;\n\n if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))\n age--;\n\n return age;\n}\n</code></pre>\n\n<p>Just two things that come into my mind: What about people from countries that do not use the Gregorian calendar? DateTime.Now is in the server-specific culture I think. I have absolutely zero knowledge about actually working with Asian calendars and I do not know if there is an easy way to convert dates between calendars, but just in case you're wondering about those Chinese guys from the year 4660 :-)</p>\n"
},
{
"answer_id": 1404,
"author": "Mike Polen",
"author_id": 212,
"author_profile": "https://Stackoverflow.com/users/212",
"pm_score": 12,
"selected": true,
"text": "<p>An easy to understand and simple solution.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>// Save today's date.\nvar today = DateTime.Today;\n\n// Calculate the age.\nvar age = today.Year - birthdate.Year;\n\n// Go back to the year in which the person was born in case of a leap year\nif (birthdate.Date > today.AddYears(-age)) age--;\n</code></pre>\n<p>However, this assumes you are looking for the <em>western</em> idea of the age and not using <a href=\"https://en.wikipedia.org/wiki/East_Asian_age_reckoning\" rel=\"noreferrer\"><em>East Asian reckoning</em></a>.</p>\n"
},
{
"answer_id": 3261,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 6,
"selected": false,
"text": "<p>This is the version we use here. It works, and it's fairly simple. It's the same idea as Jeff's but I think it's a little clearer because it separates out the logic for subtracting one, so it's a little easier to understand.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static int GetAge(this DateTime dateOfBirth, DateTime dateAsAt)\n{\n return dateAsAt.Year - dateOfBirth.Year - (dateOfBirth.DayOfYear < dateAsAt.DayOfYear ? 0 : 1);\n}\n</code></pre>\n\n<p>You could expand the ternary operator to make it even clearer, if you think that sort of thing is unclear.</p>\n\n<p>Obviously this is done as an extension method on <code>DateTime</code>, but clearly you can grab that one line of code that does the work and put it anywhere. Here we have another overload of the Extension method that passes in <code>DateTime.Now</code>, just for completeness.</p>\n"
},
{
"answer_id": 11942,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 10,
"selected": false,
"text": "<p>This is a strange way to do it, but if you format the date to <code>yyyymmdd</code> and subtract the date of birth from the current date then drop the last 4 digits you've got the age :)</p>\n\n<p>I don't know C#, but I believe this will work in any language.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>20080814 - 19800703 = 280111 \n</code></pre>\n\n<p>Drop the last 4 digits = <code>28</code>.</p>\n\n<p>C# Code:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>int now = int.Parse(DateTime.Now.ToString(\"yyyyMMdd\"));\nint dob = int.Parse(dateOfBirth.ToString(\"yyyyMMdd\"));\nint age = (now - dob) / 10000;\n</code></pre>\n\n<p>Or alternatively without all the type conversion in the form of an extension method. Error checking omitted:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static Int32 GetAge(this DateTime dateOfBirth)\n{\n var today = DateTime.Today;\n\n var a = (today.Year * 100 + today.Month) * 100 + today.Day;\n var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day;\n\n return (a - b) / 10000;\n}\n</code></pre>\n"
},
{
"answer_id": 24242,
"author": "user2601",
"author_id": 2601,
"author_profile": "https://Stackoverflow.com/users/2601",
"pm_score": 5,
"selected": false,
"text": "<p>I have created a SQL Server User Defined Function to calculate someone's age, given their birthdate. This is useful when you need it as part of a query:</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Data.Sql;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\n\npublic partial class UserDefinedFunctions\n{\n [SqlFunction(DataAccess = DataAccessKind.Read)]\n public static SqlInt32 CalculateAge(string strBirthDate)\n {\n DateTime dtBirthDate = new DateTime();\n dtBirthDate = Convert.ToDateTime(strBirthDate);\n DateTime dtToday = DateTime.Now;\n\n // get the difference in years\n int years = dtToday.Year - dtBirthDate.Year;\n\n // subtract another year if we're before the\n // birth day in the current year\n if (dtToday.Month < dtBirthDate.Month || (dtToday.Month == dtBirthDate.Month && dtToday.Day < dtBirthDate.Day))\n years=years-1;\n\n int intCustomerAge = years;\n return intCustomerAge;\n }\n};\n</code></pre>\n"
},
{
"answer_id": 141644,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I think the TimeSpan has all that we need in it, without having to resort to 365.25 (or any other approximation). Expanding on Aug's example:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime myBD = new DateTime(1980, 10, 10);\nTimeSpan difference = DateTime.Now.Subtract(myBD);\n\ntextBox1.Text = difference.Years + \" years \" + difference.Months + \" Months \" + difference.Days + \" days\";\n</code></pre>\n"
},
{
"answer_id": 168703,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 7,
"selected": false,
"text": "<p>My suggestion</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>int age = (int) ((DateTime.Now - bday).TotalDays/365.242199);\n</code></pre>\n\n<p>That seems to have the year changing on the right date. (I spot tested up to age 107.)</p>\n"
},
{
"answer_id": 877247,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>I've spent some time working on this and came up with this to calculate someone's age in years, months and days. I've tested against the Feb 29th problem and leap years and it seems to work, I'd appreciate any feedback:</p>\n\n<pre><code>public void LoopAge(DateTime myDOB, DateTime FutureDate)\n{\n int years = 0;\n int months = 0;\n int days = 0;\n\n DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);\n\n DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);\n\n while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)\n {\n months++;\n\n if (months > 12)\n {\n years++;\n months = months - 12;\n }\n }\n\n if (FutureDate.Day >= myDOB.Day)\n {\n days = days + FutureDate.Day - myDOB.Day;\n }\n else\n {\n months--;\n\n if (months < 0)\n {\n years--;\n months = months + 12;\n }\n\n days +=\n DateTime.DaysInMonth(\n FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month\n ) + FutureDate.Day - myDOB.Day;\n\n }\n\n //add an extra day if the dob is a leap day\n if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)\n {\n //but only if the future date is less than 1st March\n if (FutureDate >= new DateTime(FutureDate.Year, 3, 1))\n days++;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 877516,
"author": "SillyMonkey",
"author_id": 88600,
"author_profile": "https://Stackoverflow.com/users/88600",
"pm_score": 6,
"selected": false,
"text": "<p>Here's a one-liner:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;\n</code></pre>\n"
},
{
"answer_id": 1011981,
"author": "Rajeshwaran S P",
"author_id": 21995,
"author_profile": "https://Stackoverflow.com/users/21995",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a solution.</p>\n\n<pre><code>DateTime dateOfBirth = new DateTime(2000, 4, 18);\nDateTime currentDate = DateTime.Now;\n\nint ageInYears = 0;\nint ageInMonths = 0;\nint ageInDays = 0;\n\nageInDays = currentDate.Day - dateOfBirth.Day;\nageInMonths = currentDate.Month - dateOfBirth.Month;\nageInYears = currentDate.Year - dateOfBirth.Year;\n\nif (ageInDays < 0)\n{\n ageInDays += DateTime.DaysInMonth(currentDate.Year, currentDate.Month);\n ageInMonths = ageInMonths--;\n\n if (ageInMonths < 0)\n {\n ageInMonths += 12;\n ageInYears--;\n }\n}\n\nif (ageInMonths < 0)\n{\n ageInMonths += 12;\n ageInYears--;\n}\n\nConsole.WriteLine(\"{0}, {1}, {2}\", ageInYears, ageInMonths, ageInDays);\n</code></pre>\n"
},
{
"answer_id": 1595311,
"author": "RMA",
"author_id": 193184,
"author_profile": "https://Stackoverflow.com/users/193184",
"pm_score": 9,
"selected": false,
"text": "<p>Here is a test snippet:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime bDay = new DateTime(2000, 2, 29);\nDateTime now = new DateTime(2009, 2, 28);\nMessageBox.Show(string.Format(\"Test {0} {1} {2}\",\n CalculateAgeWrong1(bDay, now), // outputs 9\n CalculateAgeWrong2(bDay, now), // outputs 9\n CalculateAgeCorrect(bDay, now), // outputs 8\n CalculateAgeCorrect2(bDay, now))); // outputs 8\n</code></pre>\n\n<p>Here you have the methods:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public int CalculateAgeWrong1(DateTime birthDate, DateTime now)\n{\n return new DateTime(now.Subtract(birthDate).Ticks).Year - 1;\n}\n\npublic int CalculateAgeWrong2(DateTime birthDate, DateTime now)\n{\n int age = now.Year - birthDate.Year;\n\n if (now < birthDate.AddYears(age))\n age--;\n\n return age;\n}\n\npublic int CalculateAgeCorrect(DateTime birthDate, DateTime now)\n{\n int age = now.Year - birthDate.Year;\n\n if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))\n age--;\n\n return age;\n}\n\npublic int CalculateAgeCorrect2(DateTime birthDate, DateTime now)\n{\n int age = now.Year - birthDate.Year;\n\n // For leap years we need this\n if (birthDate > now.AddYears(-age)) \n age--;\n // Don't use:\n // if (birthDate.AddYears(age) > now) \n // age--;\n\n return age;\n}\n</code></pre>\n"
},
{
"answer_id": 1811311,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 2,
"selected": false,
"text": "<p>This may work:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public override bool IsValid(DateTime value)\n{\n _dateOfBirth = value;\n var yearsOld = (double) (DateTime.Now.Subtract(_dateOfBirth).TotalDays/365);\n if (yearsOld > 18)\n return true;\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 1913553,
"author": "Frederik Gheysels",
"author_id": 55774,
"author_profile": "https://Stackoverflow.com/users/55774",
"pm_score": 2,
"selected": false,
"text": "<p>I've created an Age struct, which looks like this:</p>\n\n<pre><code>public struct Age : IEquatable<Age>, IComparable<Age>\n{\n private readonly int _years;\n private readonly int _months;\n private readonly int _days;\n\n public int Years { get { return _years; } }\n public int Months { get { return _months; } }\n public int Days { get { return _days; } }\n\n public Age( int years, int months, int days ) : this()\n {\n _years = years;\n _months = months;\n _days = days;\n }\n\n public static Age CalculateAge( DateTime dateOfBirth, DateTime date )\n {\n // Here is some logic that ressembles Mike's solution, although it\n // also takes into account months & days.\n // Ommitted for brevity.\n return new Age (years, months, days);\n }\n\n // Ommited Equality, Comparable, GetHashCode, functionality for brevity.\n}\n</code></pre>\n"
},
{
"answer_id": 1928680,
"author": "Jon",
"author_id": 234611,
"author_profile": "https://Stackoverflow.com/users/234611",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a little code sample for C# I knocked up, be careful around the edge cases specifically leap years, not all the above solutions take them into account. Pushing the answer out as a DateTime can cause problems as you could end up trying to put too many days into a specific month e.g. 30 days in Feb.</p>\n\n<pre><code>public string LoopAge(DateTime myDOB, DateTime FutureDate)\n{\n int years = 0;\n int months = 0;\n int days = 0;\n\n DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);\n\n DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);\n\n while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)\n {\n months++;\n if (months > 12)\n {\n years++;\n months = months - 12;\n }\n }\n\n if (FutureDate.Day >= myDOB.Day)\n {\n days = days + FutureDate.Day - myDOB.Day;\n }\n else\n {\n months--;\n if (months < 0)\n {\n years--;\n months = months + 12;\n }\n days = days + (DateTime.DaysInMonth(FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month) + FutureDate.Day) - myDOB.Day;\n\n }\n\n //add an extra day if the dob is a leap day\n if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)\n {\n //but only if the future date is less than 1st March\n if(FutureDate >= new DateTime(FutureDate.Year, 3,1))\n days++;\n }\n\n return \"Years: \" + years + \" Months: \" + months + \" Days: \" + days;\n}\n</code></pre>\n"
},
{
"answer_id": 2280982,
"author": "Elmer",
"author_id": 173109,
"author_profile": "https://Stackoverflow.com/users/173109",
"pm_score": 5,
"selected": false,
"text": "<p>I use this:</p>\n\n<pre><code>public static class DateTimeExtensions\n{\n public static int Age(this DateTime birthDate)\n {\n return Age(birthDate, DateTime.Now);\n }\n\n public static int Age(this DateTime birthDate, DateTime offsetDate)\n {\n int result=0;\n result = offsetDate.Year - birthDate.Year;\n\n if (offsetDate.DayOfYear < birthDate.DayOfYear)\n {\n result--;\n }\n\n return result;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3513146,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Keeping it simple (and possibly stupid:)).</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime birth = new DateTime(1975, 09, 27, 01, 00, 00, 00);\nTimeSpan ts = DateTime.Now - birth;\nConsole.WriteLine(\"You are approximately \" + ts.TotalSeconds.ToString() + \" seconds old.\");\n</code></pre>\n"
},
{
"answer_id": 3652116,
"author": "AEMLoviji",
"author_id": 440670,
"author_profile": "https://Stackoverflow.com/users/440670",
"pm_score": 4,
"selected": false,
"text": "<pre><code>private int GetAge(int _year, int _month, int _day\n{\n DateTime yourBirthDate= new DateTime(_year, _month, _day);\n\n DateTime todaysDateTime = DateTime.Today;\n int noOfYears = todaysDateTime.Year - yourBirthDate.Year;\n\n if (DateTime.Now.Month < yourBirthDate.Month ||\n (DateTime.Now.Month == yourBirthDate.Month && DateTime.Now.Day < yourBirthDate.Day))\n {\n noOfYears--;\n }\n\n return noOfYears;\n}\n</code></pre>\n"
},
{
"answer_id": 3869003,
"author": "Nicholas Carey",
"author_id": 467473,
"author_profile": "https://Stackoverflow.com/users/467473",
"pm_score": 4,
"selected": false,
"text": "<p>The simplest way I've ever found is this. It works correctly for the US and western europe locales. Can't speak to other locales, especially places like China. 4 extra compares, at most, following the initial computation of age.</p>\n\n<pre><code>public int AgeInYears(DateTime birthDate, DateTime referenceDate)\n{\n Debug.Assert(referenceDate >= birthDate, \n \"birth date must be on or prior to the reference date\");\n\n DateTime birth = birthDate.Date;\n DateTime reference = referenceDate.Date;\n int years = (reference.Year - birth.Year);\n\n //\n // an offset of -1 is applied if the birth date has \n // not yet occurred in the current year.\n //\n if (reference.Month > birth.Month);\n else if (reference.Month < birth.Month) \n --years;\n else // in birth month\n {\n if (reference.Day < birth.Day)\n --years;\n }\n\n return years ;\n}\n</code></pre>\n\n<p>I was looking over the answers to this and noticed that nobody has made reference to regulatory/legal implications of leap day births. For instance, <a href=\"https://en.wikipedia.org/wiki/February_29#Births\" rel=\"noreferrer\">per Wikipedia</a>, if you're born on February 29th in various jurisdictions, you're non-leap year birthday varies:</p>\n\n<ul>\n<li>In the United Kingdom and Hong Kong: it's the ordinal day of the year, so the next day, March 1st is your birthday.</li>\n<li>In New Zealand: it's the previous day, February 28th for the purposes of driver licencing, and March 1st for other purposes.</li>\n<li>Taiwan: it's February 28th.</li>\n</ul>\n\n<p>And as near as I can tell, in the US, the statutes are silent on the matter, leaving it up to the common law and to how various regulatory bodies define things in their regulations.</p>\n\n<p>To that end, an improvement:</p>\n\n<pre><code>public enum LeapDayRule\n{\n OrdinalDay = 1 ,\n LastDayOfMonth = 2 ,\n}\n\nstatic int ComputeAgeInYears(DateTime birth, DateTime reference, LeapYearBirthdayRule ruleInEffect)\n{\n bool isLeapYearBirthday = CultureInfo.CurrentCulture.Calendar.IsLeapDay(birth.Year, birth.Month, birth.Day);\n DateTime cutoff;\n\n if (isLeapYearBirthday && !DateTime.IsLeapYear(reference.Year))\n {\n switch (ruleInEffect)\n {\n case LeapDayRule.OrdinalDay:\n cutoff = new DateTime(reference.Year, 1, 1)\n .AddDays(birth.DayOfYear - 1);\n break;\n\n case LeapDayRule.LastDayOfMonth:\n cutoff = new DateTime(reference.Year, birth.Month, 1)\n .AddMonths(1)\n .AddDays(-1);\n break;\n\n default:\n throw new InvalidOperationException();\n }\n }\n else\n {\n cutoff = new DateTime(reference.Year, birth.Month, birth.Day);\n }\n\n int age = (reference.Year - birth.Year) + (reference >= cutoff ? 0 : -1);\n return age < 0 ? 0 : age;\n}\n</code></pre>\n\n<p>It should be noted that this code assumes:</p>\n\n<ul>\n<li>A western (European) reckoning of age, and</li>\n<li>A calendar, like the Gregorian calendar that inserts a single leap day at the end of a month.</li>\n</ul>\n"
},
{
"answer_id": 5054317,
"author": "camelCasus",
"author_id": 624612,
"author_profile": "https://Stackoverflow.com/users/624612",
"pm_score": 7,
"selected": false,
"text": "<p>The simple answer to this is to apply <code>AddYears</code> as shown below because this is the only native method to add years to the 29th of Feb. of leap years and obtain the correct result of the 28th of Feb. for common years. </p>\n\n<p>Some feel that 1th of Mar. is the birthday of leaplings but neither .Net nor any official rule supports this, nor does common logic explain why some born in February should have 75% of their birthdays in another month.</p>\n\n<p>Further, an Age method lends itself to be added as an extension to <code>DateTime</code>. By this you can obtain the age in the simplest possible way:</p>\n\n<ol>\n<li>List item</li>\n</ol>\n\n<p><strong>int age = birthDate.Age();</strong></p>\n\n<pre><code>public static class DateTimeExtensions\n{\n /// <summary>\n /// Calculates the age in years of the current System.DateTime object today.\n /// </summary>\n /// <param name=\"birthDate\">The date of birth</param>\n /// <returns>Age in years today. 0 is returned for a future date of birth.</returns>\n public static int Age(this DateTime birthDate)\n {\n return Age(birthDate, DateTime.Today);\n }\n\n /// <summary>\n /// Calculates the age in years of the current System.DateTime object on a later date.\n /// </summary>\n /// <param name=\"birthDate\">The date of birth</param>\n /// <param name=\"laterDate\">The date on which to calculate the age.</param>\n /// <returns>Age in years on a later day. 0 is returned as minimum.</returns>\n public static int Age(this DateTime birthDate, DateTime laterDate)\n {\n int age;\n age = laterDate.Year - birthDate.Year;\n\n if (age > 0)\n {\n age -= Convert.ToInt32(laterDate.Date < birthDate.Date.AddYears(age));\n }\n else\n {\n age = 0;\n }\n\n return age;\n }\n}\n</code></pre>\n\n<p>Now, run this test:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n RunTest();\n }\n\n private static void RunTest()\n {\n DateTime birthDate = new DateTime(2000, 2, 28);\n DateTime laterDate = new DateTime(2011, 2, 27);\n string iso = \"yyyy-MM-dd\";\n\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n Console.WriteLine(\"Birth date: \" + birthDate.AddDays(i).ToString(iso) + \" Later date: \" + laterDate.AddDays(j).ToString(iso) + \" Age: \" + birthDate.AddDays(i).Age(laterDate.AddDays(j)).ToString());\n }\n }\n\n Console.ReadKey();\n }\n}\n</code></pre>\n\n<p>The critical date example is this:</p>\n\n<p><strong>Birth date: 2000-02-29 Later date: 2011-02-28 Age: 11</strong></p>\n\n<p>Output:</p>\n\n<pre><code>{\n Birth date: 2000-02-28 Later date: 2011-02-27 Age: 10\n Birth date: 2000-02-28 Later date: 2011-02-28 Age: 11\n Birth date: 2000-02-28 Later date: 2011-03-01 Age: 11\n Birth date: 2000-02-29 Later date: 2011-02-27 Age: 10\n Birth date: 2000-02-29 Later date: 2011-02-28 Age: 11\n Birth date: 2000-02-29 Later date: 2011-03-01 Age: 11\n Birth date: 2000-03-01 Later date: 2011-02-27 Age: 10\n Birth date: 2000-03-01 Later date: 2011-02-28 Age: 10\n Birth date: 2000-03-01 Later date: 2011-03-01 Age: 11\n}\n</code></pre>\n\n<p>And for the later date 2012-02-28:</p>\n\n<pre><code>{\n Birth date: 2000-02-28 Later date: 2012-02-28 Age: 12\n Birth date: 2000-02-28 Later date: 2012-02-29 Age: 12\n Birth date: 2000-02-28 Later date: 2012-03-01 Age: 12\n Birth date: 2000-02-29 Later date: 2012-02-28 Age: 11\n Birth date: 2000-02-29 Later date: 2012-02-29 Age: 12\n Birth date: 2000-02-29 Later date: 2012-03-01 Age: 12\n Birth date: 2000-03-01 Later date: 2012-02-28 Age: 11\n Birth date: 2000-03-01 Later date: 2012-02-29 Age: 11\n Birth date: 2000-03-01 Later date: 2012-03-01 Age: 12\n}\n</code></pre>\n"
},
{
"answer_id": 5229568,
"author": "Doron",
"author_id": 649407,
"author_profile": "https://Stackoverflow.com/users/649407",
"pm_score": 4,
"selected": false,
"text": "<p>How about this solution? </p>\n\n<pre><code>static string CalcAge(DateTime birthDay)\n{\n DateTime currentDate = DateTime.Now; \n int approximateAge = currentDate.Year - birthDay.Year;\n int daysToNextBirthDay = (birthDay.Month * 30 + birthDay.Day) - \n (currentDate.Month * 30 + currentDate.Day) ;\n\n if (approximateAge == 0 || approximateAge == 1)\n { \n int month = Math.Abs(daysToNextBirthDay / 30);\n int days = Math.Abs(daysToNextBirthDay % 30);\n\n if (month == 0)\n return \"Your age is: \" + daysToNextBirthDay + \" days\";\n\n return \"Your age is: \" + month + \" months and \" + days + \" days\"; ;\n }\n\n if (daysToNextBirthDay > 0)\n return \"Your age is: \" + --approximateAge + \" Years\";\n\n return \"Your age is: \" + approximateAge + \" Years\"; ;\n}\n</code></pre>\n"
},
{
"answer_id": 5623077,
"author": "Marcel Toth",
"author_id": 702199,
"author_profile": "https://Stackoverflow.com/users/702199",
"pm_score": 6,
"selected": false,
"text": "<p>2 Main problems to solve are:</p>\n\n<p><strong>1. Calculate Exact age</strong> - in years, months, days, etc.</p>\n\n<p><strong>2. Calculate Generally perceived age</strong> - people usually do not care how old they exactly are, they just care when their birthday in the current year is.</p>\n\n<hr>\n\n<p>Solution for <strong>1</strong> is obvious:</p>\n\n<pre><code>DateTime birth = DateTime.Parse(\"1.1.2000\");\nDateTime today = DateTime.Today; //we usually don't care about birth time\nTimeSpan age = today - birth; //.NET FCL should guarantee this as precise\ndouble ageInDays = age.TotalDays; //total number of days ... also precise\ndouble daysInYear = 365.2425; //statistical value for 400 years\ndouble ageInYears = ageInDays / daysInYear; //can be shifted ... not so precise\n</code></pre>\n\n<hr>\n\n<p>Solution for <strong>2</strong> is the one which is not so precise in determing total age, but is perceived as precise by people. People also usually use it, when they calculate their age \"manually\":</p>\n\n<pre><code>DateTime birth = DateTime.Parse(\"1.1.2000\");\nDateTime today = DateTime.Today;\nint age = today.Year - birth.Year; //people perceive their age in years\n\nif (today.Month < birth.Month ||\n ((today.Month == birth.Month) && (today.Day < birth.Day)))\n{\n age--; //birthday in current year not yet reached, we are 1 year younger ;)\n //+ no birthday for 29.2. guys ... sorry, just wrong date for birth\n}\n</code></pre>\n\n<p>Notes to 2.:</p>\n\n<ul>\n<li>This is my preferred solution</li>\n<li>We cannot use DateTime.DayOfYear or TimeSpans, as they shift number of days in leap years</li>\n<li>I have put there little more lines for readability</li>\n</ul>\n\n<p>Just one more note ... I would create 2 static overloaded methods for it, one for universal usage, second for usage-friendliness:</p>\n\n<pre><code>public static int GetAge(DateTime bithDay, DateTime today) \n{ \n //chosen solution method body\n}\n\npublic static int GetAge(DateTime birthDay) \n{ \n return GetAge(birthDay, DateTime.Now);\n}\n</code></pre>\n"
},
{
"answer_id": 5989087,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The following approach (extract from <a href=\"https://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET\" rel=\"noreferrer\">Time Period Library for .NET</a> class <em>DateDiff</em>) considers the calendar of the culture info:</p>\n\n<pre><code>// ----------------------------------------------------------------------\nprivate static int YearDiff( DateTime date1, DateTime date2 )\n{\n return YearDiff( date1, date2, DateTimeFormatInfo.CurrentInfo.Calendar );\n} // YearDiff\n\n// ----------------------------------------------------------------------\nprivate static int YearDiff( DateTime date1, DateTime date2, Calendar calendar )\n{\n if ( date1.Equals( date2 ) )\n {\n return 0;\n }\n\n int year1 = calendar.GetYear( date1 );\n int month1 = calendar.GetMonth( date1 );\n int year2 = calendar.GetYear( date2 );\n int month2 = calendar.GetMonth( date2 );\n\n // find the the day to compare\n int compareDay = date2.Day;\n int compareDaysPerMonth = calendar.GetDaysInMonth( year1, month1 );\n if ( compareDay > compareDaysPerMonth )\n {\n compareDay = compareDaysPerMonth;\n }\n\n // build the compare date\n DateTime compareDate = new DateTime( year1, month2, compareDay,\n date2.Hour, date2.Minute, date2.Second, date2.Millisecond );\n if ( date2 > date1 )\n {\n if ( compareDate < date1 )\n {\n compareDate = compareDate.AddYears( 1 );\n }\n }\n else\n {\n if ( compareDate > date1 )\n {\n compareDate = compareDate.AddYears( -1 );\n }\n }\n return year2 - calendar.GetYear( compareDate );\n} // YearDiff\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>// ----------------------------------------------------------------------\npublic void CalculateAgeSamples()\n{\n PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2009, 02, 28 ) );\n // > Birthdate=29.02.2000, Age at 28.02.2009 is 8 years\n PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2012, 02, 28 ) );\n // > Birthdate=29.02.2000, Age at 28.02.2012 is 11 years\n} // CalculateAgeSamples\n\n// ----------------------------------------------------------------------\npublic void PrintAge( DateTime birthDate, DateTime moment )\n{\n Console.WriteLine( \"Birthdate={0:d}, Age at {1:d} is {2} years\", birthDate, moment, YearDiff( birthDate, moment ) );\n} // PrintAge\n</code></pre>\n"
},
{
"answer_id": 6075141,
"author": "B2K",
"author_id": 763112,
"author_profile": "https://Stackoverflow.com/users/763112",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a DateTime extender that adds the age calculation to the DateTime object.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static class AgeExtender\n{\n public static int GetAge(this DateTime dt)\n {\n int d = int.Parse(dt.ToString(\"yyyyMMdd\"));\n int t = int.Parse(DateTime.Today.ToString(\"yyyyMMdd\"));\n return (t-d)/10000;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6719204,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 3,
"selected": false,
"text": "<p>I've made one small change to <a href=\"https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c/1404#1404\">Mark Soen's</a> answer: I've rewriten the third line so that the expression can be parsed a bit more easily.</p>\n\n<pre><code>public int AgeInYears(DateTime bday)\n{\n DateTime now = DateTime.Today;\n int age = now.Year - bday.Year; \n if (bday.AddYears(age) > now) \n age--;\n return age;\n}\n</code></pre>\n\n<p>I've also made it into a function for the sake of clarity.</p>\n"
},
{
"answer_id": 7046204,
"author": "Dylan Hayes",
"author_id": 892460,
"author_profile": "https://Stackoverflow.com/users/892460",
"pm_score": 3,
"selected": false,
"text": "<p>I used ScArcher2's solution for an accurate Year calculation of a persons age but I needed to take it further and calculate their Months and Days along with the Years.</p>\n\n<pre><code> public static Dictionary<string,int> CurrentAgeInYearsMonthsDays(DateTime? ndtBirthDate, DateTime? ndtReferralDate)\n {\n //----------------------------------------------------------------------\n // Can't determine age if we don't have a dates.\n //----------------------------------------------------------------------\n if (ndtBirthDate == null) return null;\n if (ndtReferralDate == null) return null;\n\n DateTime dtBirthDate = Convert.ToDateTime(ndtBirthDate);\n DateTime dtReferralDate = Convert.ToDateTime(ndtReferralDate);\n\n //----------------------------------------------------------------------\n // Create our Variables\n //----------------------------------------------------------------------\n Dictionary<string, int> dYMD = new Dictionary<string,int>();\n int iNowDate, iBirthDate, iYears, iMonths, iDays;\n string sDif = \"\";\n\n //----------------------------------------------------------------------\n // Store off current date/time and DOB into local variables\n //---------------------------------------------------------------------- \n iNowDate = int.Parse(dtReferralDate.ToString(\"yyyyMMdd\"));\n iBirthDate = int.Parse(dtBirthDate.ToString(\"yyyyMMdd\"));\n\n //----------------------------------------------------------------------\n // Calculate Years\n //----------------------------------------------------------------------\n sDif = (iNowDate - iBirthDate).ToString();\n iYears = int.Parse(sDif.Substring(0, sDif.Length - 4));\n\n //----------------------------------------------------------------------\n // Store Years in Return Value\n //----------------------------------------------------------------------\n dYMD.Add(\"Years\", iYears);\n\n //----------------------------------------------------------------------\n // Calculate Months\n //----------------------------------------------------------------------\n if (dtBirthDate.Month > dtReferralDate.Month)\n iMonths = 12 - dtBirthDate.Month + dtReferralDate.Month - 1;\n else\n iMonths = dtBirthDate.Month - dtReferralDate.Month;\n\n //----------------------------------------------------------------------\n // Store Months in Return Value\n //----------------------------------------------------------------------\n dYMD.Add(\"Months\", iMonths);\n\n //----------------------------------------------------------------------\n // Calculate Remaining Days\n //----------------------------------------------------------------------\n if (dtBirthDate.Day > dtReferralDate.Day)\n //Logic: Figure out the days in month previous to the current month, or the admitted month.\n // Subtract the birthday from the total days which will give us how many days the person has lived since their birthdate day the previous month.\n // then take the referral date and simply add the number of days the person has lived this month.\n\n //If referral date is january, we need to go back to the following year's December to get the days in that month.\n if (dtReferralDate.Month == 1)\n iDays = DateTime.DaysInMonth(dtReferralDate.Year - 1, 12) - dtBirthDate.Day + dtReferralDate.Day; \n else\n iDays = DateTime.DaysInMonth(dtReferralDate.Year, dtReferralDate.Month - 1) - dtBirthDate.Day + dtReferralDate.Day; \n else\n iDays = dtReferralDate.Day - dtBirthDate.Day; \n\n //----------------------------------------------------------------------\n // Store Days in Return Value\n //----------------------------------------------------------------------\n dYMD.Add(\"Days\", iDays);\n\n return dYMD;\n}\n</code></pre>\n"
},
{
"answer_id": 8816564,
"author": "Moshe L",
"author_id": 1056259,
"author_profile": "https://Stackoverflow.com/users/1056259",
"pm_score": 2,
"selected": false,
"text": "<p>I want to add Hebrew calendar calculations (or other System.Globalization calendar can be used in the same way), using rewrited functions from this thread:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Public Shared Function CalculateAge(BirthDate As DateTime) As Integer\n Dim HebCal As New System.Globalization.HebrewCalendar ()\n Dim now = DateTime.Now()\n Dim iAge = HebCal.GetYear(now) - HebCal.GetYear(BirthDate)\n Dim iNowMonth = HebCal.GetMonth(now), iBirthMonth = HebCal.GetMonth(BirthDate)\n If iNowMonth < iBirthMonth Or (iNowMonth = iBirthMonth AndAlso HebCal.GetDayOfMonth(now) < HebCal.GetDayOfMonth(BirthDate)) Then iAge -= 1\n Return iAge\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 9431192,
"author": "musefan",
"author_id": 838807,
"author_profile": "https://Stackoverflow.com/users/838807",
"pm_score": 3,
"selected": false,
"text": "<p>This is simple and appears to be accurate for my needs. I am making an assumption for the purpose of leap years that regardless of when the person chooses to celebrate the birthday they are not technically a year older until 365 days have passed since their last birthday (i.e 28th February does not make them a year older).</p>\n<pre><code>DateTime now = DateTime.Today;\nDateTime birthday = new DateTime(1991, 02, 03);//3rd feb\n\nint age = now.Year - birthday.Year;\n\nif (now.Month < birthday.Month || (now.Month == birthday.Month && now.Day < birthday.Day))//not had bday this year yet\n age--;\n\nreturn age;\n</code></pre>\n"
},
{
"answer_id": 11328202,
"author": "Narasimha",
"author_id": 254790,
"author_profile": "https://Stackoverflow.com/users/254790",
"pm_score": 2,
"selected": false,
"text": "<p>Try this solution, it's working.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>int age = (Int32.Parse(DateTime.Today.ToString(\"yyyyMMdd\")) - \n Int32.Parse(birthday.ToString(\"yyyyMMdd rawrrr\"))) / 10000;\n</code></pre>\n"
},
{
"answer_id": 13531544,
"author": "flindeberg",
"author_id": 691294,
"author_profile": "https://Stackoverflow.com/users/691294",
"pm_score": 4,
"selected": false,
"text": "<p>This is not a direct answer, but more of a philosophical reasoning about the problem at hand from a quasi-scientific point of view.</p>\n\n<p>I would argue that the question does not specify the unit nor culture in which to measure age, most answers seem to assume an integer annual representation. The SI-unit for time is <code>second</code>, ergo the correct generic answer should be (of course assuming normalized <code>DateTime</code> and taking no regard whatsoever to relativistic effects):</p>\n\n<pre><code>var lifeInSeconds = (DateTime.Now.Ticks - then.Ticks)/TickFactor;\n</code></pre>\n\n<p>In the Christian way of calculating age in years:</p>\n\n<pre><code>var then = ... // Then, in this case the birthday\nvar now = DateTime.UtcNow;\nint age = now.Year - then.Year;\nif (now.AddYears(-age) < then) age--;\n</code></pre>\n\n<p>In finance there is a similar problem when calculating something often referred to as the <em>Day Count Fraction</em>, which roughly is a number of years for a given period. And the age issue is really a time measuring issue.</p>\n\n<p>Example for the actual/actual (counting all days \"correctly\") convention:</p>\n\n<pre><code>DateTime start, end = .... // Whatever, assume start is before end\n\ndouble startYearContribution = 1 - (double) start.DayOfYear / (double) (DateTime.IsLeapYear(start.Year) ? 366 : 365);\ndouble endYearContribution = (double)end.DayOfYear / (double)(DateTime.IsLeapYear(end.Year) ? 366 : 365);\ndouble middleContribution = (double) (end.Year - start.Year - 1);\n\ndouble DCF = startYearContribution + endYearContribution + middleContribution;\n</code></pre>\n\n<p>Another quite common way to measure time generally is by \"serializing\" (the dude who named this date convention must seriously have been trippin'):</p>\n\n<pre><code>DateTime start, end = .... // Whatever, assume start is before end\nint days = (end - start).Days;\n</code></pre>\n\n<p>I wonder how long we have to go before a relativistic age in seconds becomes more useful than the rough approximation of earth-around-sun-cycles during one's lifetime so far :) Or in other words, when a period must be given a location or a function representing motion for itself to be valid :)</p>\n"
},
{
"answer_id": 13645039,
"author": "rockXrock",
"author_id": 1254006,
"author_profile": "https://Stackoverflow.com/users/1254006",
"pm_score": 4,
"selected": false,
"text": "<p>Do we need to consider people who is smaller than 1 year? as Chinese culture, we describe small babies' age as 2 months or 4 weeks. </p>\n\n<p>Below is my implementation, it is not as simple as what I imagined, especially to deal with date like 2/28. </p>\n\n<pre><code>public static string HowOld(DateTime birthday, DateTime now)\n{\n if (now < birthday)\n throw new ArgumentOutOfRangeException(\"birthday must be less than now.\");\n\n TimeSpan diff = now - birthday;\n int diffDays = (int)diff.TotalDays;\n\n if (diffDays > 7)//year, month and week\n {\n int age = now.Year - birthday.Year;\n\n if (birthday > now.AddYears(-age))\n age--;\n\n if (age > 0)\n {\n return age + (age > 1 ? \" years\" : \" year\");\n }\n else\n {// month and week\n DateTime d = birthday;\n int diffMonth = 1;\n\n while (d.AddMonths(diffMonth) <= now)\n {\n diffMonth++;\n }\n\n age = diffMonth-1;\n\n if (age == 1 && d.Day > now.Day)\n age--;\n\n if (age > 0)\n {\n return age + (age > 1 ? \" months\" : \" month\");\n }\n else\n {\n age = diffDays / 7;\n return age + (age > 1 ? \" weeks\" : \" week\");\n }\n }\n }\n else if (diffDays > 0)\n {\n int age = diffDays;\n return age + (age > 1 ? \" days\" : \" day\");\n }\n else\n {\n int age = diffDays;\n return \"just born\";\n }\n}\n</code></pre>\n\n<p>This implementation has passed below test cases.</p>\n\n<pre><code>[TestMethod]\npublic void TestAge()\n{\n string age = HowOld(new DateTime(2011, 1, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 year\", age);\n\n age = HowOld(new DateTime(2011, 11, 30), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 year\", age);\n\n age = HowOld(new DateTime(2001, 1, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"11 years\", age);\n\n age = HowOld(new DateTime(2012, 1, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"10 months\", age);\n\n age = HowOld(new DateTime(2011, 12, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"11 months\", age);\n\n age = HowOld(new DateTime(2012, 10, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 month\", age);\n\n age = HowOld(new DateTime(2008, 2, 28), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"1 year\", age);\n\n age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"11 months\", age);\n\n age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 3, 28));\n Assert.AreEqual(\"1 year\", age);\n\n age = HowOld(new DateTime(2009, 1, 28), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"1 month\", age);\n\n age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1));\n Assert.AreEqual(\"1 month\", age);\n\n // NOTE.\n // new DateTime(2008, 1, 31).AddMonths(1) == new DateTime(2009, 2, 28);\n // new DateTime(2008, 1, 28).AddMonths(1) == new DateTime(2009, 2, 28);\n age = HowOld(new DateTime(2009, 1, 31), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"4 weeks\", age);\n\n age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"3 weeks\", age);\n\n age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1));\n Assert.AreEqual(\"1 month\", age);\n\n age = HowOld(new DateTime(2012, 11, 5), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"3 weeks\", age);\n\n age = HowOld(new DateTime(2012, 11, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"4 weeks\", age);\n\n age = HowOld(new DateTime(2012, 11, 20), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 week\", age);\n\n age = HowOld(new DateTime(2012, 11, 25), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"5 days\", age);\n\n age = HowOld(new DateTime(2012, 11, 29), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 day\", age);\n\n age = HowOld(new DateTime(2012, 11, 30), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"just born\", age);\n\n age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"8 years\", age);\n\n age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 3, 1));\n Assert.AreEqual(\"9 years\", age);\n\n Exception e = null;\n\n try\n {\n age = HowOld(new DateTime(2012, 12, 1), new DateTime(2012, 11, 30));\n }\n catch (ArgumentOutOfRangeException ex)\n {\n e = ex;\n }\n\n Assert.IsTrue(e != null);\n}\n</code></pre>\n\n<p>Hope it's helpful.</p>\n"
},
{
"answer_id": 14125249,
"author": "Stranger",
"author_id": 1462452,
"author_profile": "https://Stackoverflow.com/users/1462452",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a very simple and easy to follow example. </p>\n\n<pre><code>private int CalculateAge()\n{\n//get birthdate\n DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);\n int byear = dtBirth.Year;\n int bmonth = dtBirth.Month;\n int bday = dtBirth.Day;\n DateTime dtToday = DateTime.Now;\n int tYear = dtToday.Year;\n int tmonth = dtToday.Month;\n int tday = dtToday.Day;\n int age = tYear - byear;\n if (bmonth < tmonth)\n age--;\n else if (bmonth == tmonth && bday>tday)\n {\n age--;\n }\nreturn age;\n}\n</code></pre>\n"
},
{
"answer_id": 16142434,
"author": "Matthew Watson",
"author_id": 106159,
"author_profile": "https://Stackoverflow.com/users/106159",
"pm_score": 5,
"selected": false,
"text": "<p>Here's yet another answer:</p>\n<pre><code>public static int AgeInYears(DateTime birthday, DateTime today)\n{\n return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;\n}\n</code></pre>\n<p>This has been extensively unit-tested. It does look a bit "magic". The number 372 is the number of days there would be in a year if every month had 31 days.</p>\n<p>The explanation of why it works (<a href=\"https://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/ba4a98af-aab3-4c59-bdee-611334e502f2\" rel=\"noreferrer\">lifted from here</a>) is:</p>\n<blockquote>\n<p>Let's set <code>Yn = DateTime.Now.Year, Yb = birthday.Year, Mn = DateTime.Now.Month, Mb = birthday.Month, Dn = DateTime.Now.Day, Db = birthday.Day</code></p>\n<p><code>age = Yn - Yb + (31*(Mn - Mb) + (Dn - Db)) / 372</code></p>\n<p>We know that what we need is either <code>Yn-Yb</code> if the date has already been reached, <code>Yn-Yb-1</code> if it has not.</p>\n<p>a) If <code>Mn<Mb</code>, we have <code>-341 <= 31*(Mn-Mb) <= -31 and -30 <= Dn-Db <= 30</code></p>\n<p><code>-371 <= 31*(Mn - Mb) + (Dn - Db) <= -1</code></p>\n<p>With integer division</p>\n<p><code>(31*(Mn - Mb) + (Dn - Db)) / 372 = -1</code></p>\n<p>b) If <code>Mn=Mb</code> and <code>Dn<Db</code>, we have <code>31*(Mn - Mb) = 0 and -30 <= Dn-Db <= -1</code></p>\n<p>With integer division, again</p>\n<p><code>(31*(Mn - Mb) + (Dn - Db)) / 372 = -1</code></p>\n<p>c) If <code>Mn>Mb</code>, we have <code>31 <= 31*(Mn-Mb) <= 341 and -30 <= Dn-Db <= 30</code></p>\n<p><code>1 <= 31*(Mn - Mb) + (Dn - Db) <= 371</code></p>\n<p>With integer division</p>\n<p><code>(31*(Mn - Mb) + (Dn - Db)) / 372 = 0</code></p>\n<p>d) If <code>Mn=Mb</code> and <code>Dn>Db</code>, we have <code>31*(Mn - Mb) = 0 and 1 <= Dn-Db <= 3</code>0</p>\n<p>With integer division, again</p>\n<p><code>(31*(Mn - Mb) + (Dn - Db)) / 372 = 0</code></p>\n<p>e) If <code>Mn=Mb</code> and <code>Dn=Db</code>, we have <code>31*(Mn - Mb) + Dn-Db = 0</code></p>\n<p>and therefore <code>(31*(Mn - Mb) + (Dn - Db)) / 372 = 0</code></p>\n</blockquote>\n"
},
{
"answer_id": 18682920,
"author": "vulcan raven",
"author_id": 863980,
"author_profile": "https://Stackoverflow.com/users/863980",
"pm_score": 2,
"selected": false,
"text": "<p>With fewer conversions and UtcNow, this code can take care of someone born on the Feb 29 in a leap year:</p>\n\n<pre><code>public int GetAge(DateTime DateOfBirth)\n{\n var Now = DateTime.UtcNow;\n return Now.Year - DateOfBirth.Year -\n (\n (\n Now.Month > DateOfBirth.Month ||\n (Now.Month == DateOfBirth.Month && Now.Day >= DateOfBirth.Day)\n ) ? 0 : 1\n );\n}\n</code></pre>\n"
},
{
"answer_id": 18895699,
"author": "Archit",
"author_id": 2435287,
"author_profile": "https://Stackoverflow.com/users/2435287",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>How come the MSDN help did not tell you that? It looks so obvious:</p>\n</blockquote>\n\n<pre class=\"lang-cs prettyprint-override\"><code>System.DateTime birthTime = AskTheUser(myUser); // :-)\nSystem.DateTime now = System.DateTime.Now;\nSystem.TimeSpan age = now - birthTime; // As simple as that\ndouble ageInDays = age.TotalDays; // Will you convert to whatever you want yourself?\n</code></pre>\n"
},
{
"answer_id": 18898663,
"author": "Dakotah Hicock",
"author_id": 1226335,
"author_profile": "https://Stackoverflow.com/users/1226335",
"pm_score": 4,
"selected": false,
"text": "<pre class=\"lang-cs prettyprint-override\"><code>TimeSpan diff = DateTime.Now - birthdayDateTime;\nstring age = String.Format(\"{0:%y} years, {0:%M} months, {0:%d}, days old\", diff);\n</code></pre>\n\n<p>I'm not sure how exactly you'd like it returned to you, so I just made a readable string.</p>\n"
},
{
"answer_id": 18924226,
"author": "Jacqueline Loriault",
"author_id": 2778315,
"author_profile": "https://Stackoverflow.com/users/2778315",
"pm_score": 5,
"selected": false,
"text": "<p>This gives \"more detail\" to this question. Maybe this is what you're looking for</p>\n\n<pre><code>DateTime birth = new DateTime(1974, 8, 29);\nDateTime today = DateTime.Now;\nTimeSpan span = today - birth;\nDateTime age = DateTime.MinValue + span;\n\n// Make adjustment due to MinValue equalling 1/1/1\nint years = age.Year - 1;\nint months = age.Month - 1;\nint days = age.Day - 1;\n\n// Print out not only how many years old they are but give months and days as well\nConsole.Write(\"{0} years, {1} months, {2} days\", years, months, days);\n</code></pre>\n"
},
{
"answer_id": 20348258,
"author": "Dhaval Panchal",
"author_id": 2368967,
"author_profile": "https://Stackoverflow.com/users/2368967",
"pm_score": -1,
"selected": false,
"text": "<p>To calculate the age with nearest age:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var ts = DateTime.Now - new DateTime(1988, 3, 19);\nvar age = Math.Round(ts.Days / 365.0);\n</code></pre>\n"
},
{
"answer_id": 20715576,
"author": "Matt Johnson-Pint",
"author_id": 634824,
"author_profile": "https://Stackoverflow.com/users/634824",
"pm_score": 4,
"selected": false,
"text": "<p>This classic question is deserving of a <a href=\"https://nodatime.org\" rel=\"noreferrer\">Noda Time</a> solution.</p>\n\n<pre><code>static int GetAge(LocalDate dateOfBirth)\n{\n Instant now = SystemClock.Instance.Now;\n\n // The target time zone is important.\n // It should align with the *current physical location* of the person\n // you are talking about. When the whereabouts of that person are unknown,\n // then you use the time zone of the person who is *asking* for the age.\n // The time zone of birth is irrelevant!\n\n DateTimeZone zone = DateTimeZoneProviders.Tzdb[\"America/New_York\"];\n\n LocalDate today = now.InZone(zone).Date;\n\n Period period = Period.Between(dateOfBirth, today, PeriodUnits.Years);\n\n return (int) period.Years;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>LocalDate dateOfBirth = new LocalDate(1976, 8, 27);\nint age = GetAge(dateOfBirth);\n</code></pre>\n\n<p>You might also be interested in the following improvements:</p>\n\n<ul>\n<li><p>Passing in the clock as an <code>IClock</code>, instead of using <code>SystemClock.Instance</code>, would improve testability.</p></li>\n<li><p>The target time zone will likely change, so you'd want a <code>DateTimeZone</code> parameter as well.</p></li>\n</ul>\n\n<p>See also my blog post on this subject: <a href=\"https://codeofmatt.com/2014/04/09/handling-birthdays-and-other-anniversaries/\" rel=\"noreferrer\">Handling Birthdays, and Other Anniversaries</a></p>\n"
},
{
"answer_id": 21276626,
"author": "DareDevil",
"author_id": 1147352,
"author_profile": "https://Stackoverflow.com/users/1147352",
"pm_score": 4,
"selected": false,
"text": "<p>I have a customized method to calculate age, plus a bonus validation message just in case it helps:</p>\n\n<pre><code>public void GetAge(DateTime dob, DateTime now, out int years, out int months, out int days)\n{\n years = 0;\n months = 0;\n days = 0;\n\n DateTime tmpdob = new DateTime(dob.Year, dob.Month, 1);\n DateTime tmpnow = new DateTime(now.Year, now.Month, 1);\n\n while (tmpdob.AddYears(years).AddMonths(months) < tmpnow)\n {\n months++;\n if (months > 12)\n {\n years++;\n months = months - 12;\n }\n }\n\n if (now.Day >= dob.Day)\n days = days + now.Day - dob.Day;\n else\n {\n months--;\n if (months < 0)\n {\n years--;\n months = months + 12;\n }\n days += DateTime.DaysInMonth(now.AddMonths(-1).Year, now.AddMonths(-1).Month) + now.Day - dob.Day;\n }\n\n if (DateTime.IsLeapYear(dob.Year) && dob.Month == 2 && dob.Day == 29 && now >= new DateTime(now.Year, 3, 1))\n days++;\n\n} \n\nprivate string ValidateDate(DateTime dob) //This method will validate the date\n{\n int Years = 0; int Months = 0; int Days = 0;\n\n GetAge(dob, DateTime.Now, out Years, out Months, out Days);\n\n if (Years < 18)\n message = Years + \" is too young. Please try again on your 18th birthday.\";\n else if (Years >= 65)\n message = Years + \" is too old. Date of Birth must not be 65 or older.\";\n else\n return null; //Denotes validation passed\n}\n</code></pre>\n\n<p>Method call here and pass out datetime value (MM/dd/yyyy if server set to USA locale). Replace this with anything a messagebox or any container to display:</p>\n\n<pre><code>DateTime dob = DateTime.Parse(\"03/10/1982\"); \n\nstring message = ValidateDate(dob);\n\nlbldatemessage.Visible = !StringIsNullOrWhitespace(message);\nlbldatemessage.Text = message ?? \"\"; //Ternary if message is null then default to empty string\n</code></pre>\n\n<p>Remember you can format the message any way you like.</p>\n"
},
{
"answer_id": 25014539,
"author": "Pratik Bhoir",
"author_id": 2772550,
"author_profile": "https://Stackoverflow.com/users/2772550",
"pm_score": -1,
"selected": false,
"text": "<p>A one-liner answer:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime dateOfBirth = Convert.ToDateTime(\"01/16/1990\");\nvar age = ((DateTime.Now - dateOfBirth).Days) / 365;\n</code></pre>\n"
},
{
"answer_id": 26529035,
"author": "mjb",
"author_id": 520848,
"author_profile": "https://Stackoverflow.com/users/520848",
"pm_score": 4,
"selected": false,
"text": "<p>This is one of the most accurate answers that is able to resolve the birthday of 29th of Feb compared to any year of 28th Feb.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public int GetAge(DateTime birthDate)\n{\n int age = DateTime.Now.Year - birthDate.Year;\n\n if (birthDate.DayOfYear > DateTime.Now.DayOfYear)\n age--;\n\n return age;\n}\n\n\n\n\n</code></pre>\n"
},
{
"answer_id": 28567336,
"author": "dav_i",
"author_id": 1185053,
"author_profile": "https://Stackoverflow.com/users/1185053",
"pm_score": 2,
"selected": false,
"text": "<p>Just because I don't think the top answer is that clear:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static int GetAgeByLoop(DateTime birthday)\n{\n var age = -1;\n\n for (var date = birthday; date < DateTime.Today; date = date.AddYears(1))\n {\n age++;\n }\n\n return age;\n}\n</code></pre>\n"
},
{
"answer_id": 30145502,
"author": "mind_overflow",
"author_id": 3889784,
"author_profile": "https://Stackoverflow.com/users/3889784",
"pm_score": -1,
"selected": false,
"text": "<p>Check this out:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>TimeSpan ts = DateTime.Now.Subtract(Birthdate);\nage = (byte)(ts.TotalDays / 365.25);\n</code></pre>\n"
},
{
"answer_id": 31025282,
"author": "user1210708",
"author_id": 1210708,
"author_profile": "https://Stackoverflow.com/users/1210708",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a function that is serving me well. No calculations , very simple.</p>\n<pre><code> public static string ToAge(this DateTime dob, DateTime? toDate = null)\n {\n if (!toDate.HasValue)\n toDate = DateTime.Now;\n var now = toDate.Value;\n\n if (now.CompareTo(dob) < 0)\n return "Future date";\n\n int years = now.Year - dob.Year;\n int months = now.Month - dob.Month;\n int days = now.Day - dob.Day;\n\n if (days < 0)\n {\n months--;\n days = DateTime.DaysInMonth(dob.Year, dob.Month) - dob.Day + now.Day;\n }\n\n if (months < 0)\n {\n years--;\n months = 12 + months;\n }\n\n\n return string.Format("{0} year(s), {1} month(s), {2} days(s)",\n years,\n months,\n days);\n }\n</code></pre>\n<p>And here is a unit test:</p>\n<pre><code> [Test]\n public void ToAgeTests()\n {\n var date = new DateTime(2000, 1, 1);\n Assert.AreEqual("0 year(s), 0 month(s), 1 days(s)", new DateTime(1999, 12, 31).ToAge(date));\n Assert.AreEqual("0 year(s), 0 month(s), 0 days(s)", new DateTime(2000, 1, 1).ToAge(date));\n Assert.AreEqual("1 year(s), 0 month(s), 0 days(s)", new DateTime(1999, 1, 1).ToAge(date));\n Assert.AreEqual("0 year(s), 11 month(s), 0 days(s)", new DateTime(1999, 2, 1).ToAge(date));\n Assert.AreEqual("0 year(s), 10 month(s), 25 days(s)", new DateTime(1999, 2, 4).ToAge(date));\n Assert.AreEqual("0 year(s), 10 month(s), 1 days(s)", new DateTime(1999, 2, 28).ToAge(date));\n\n date = new DateTime(2000, 2, 15);\n Assert.AreEqual("0 year(s), 0 month(s), 28 days(s)", new DateTime(2000, 1, 18).ToAge(date));\n }\n</code></pre>\n"
},
{
"answer_id": 31077562,
"author": "Lukas",
"author_id": 593388,
"author_profile": "https://Stackoverflow.com/users/593388",
"pm_score": 3,
"selected": false,
"text": "<p>It can be this simple:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1;\n</code></pre>\n"
},
{
"answer_id": 31178328,
"author": "BrunoVT",
"author_id": 4090831,
"author_profile": "https://Stackoverflow.com/users/4090831",
"pm_score": 2,
"selected": false,
"text": "<p>I would simply do this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime birthDay = new DateTime(1990, 05, 23);\nDateTime age = DateTime.Now - birthDay;\n</code></pre>\n\n<p>This way you can calculate the exact age of a person, down to the millisecond if you want.</p>\n"
},
{
"answer_id": 32954095,
"author": "VhsPiceros",
"author_id": 581783,
"author_profile": "https://Stackoverflow.com/users/581783",
"pm_score": 2,
"selected": false,
"text": "<p>I have used the following for this issue. I know it's not very elegant, but it's working.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime zeroTime = new DateTime(1, 1, 1);\nvar date1 = new DateTime(1983, 03, 04);\nvar date2 = DateTime.Now;\nvar dif = date2 - date1;\nint years = (zeroTime + dif).Year - 1;\nLog.DebugFormat(\"Years -->{0}\", years);\n</code></pre>\n"
},
{
"answer_id": 33082044,
"author": "Ahmed Sabry",
"author_id": 4707576,
"author_profile": "https://Stackoverflow.com/users/4707576",
"pm_score": 2,
"selected": false,
"text": "<pre class=\"lang-cs prettyprint-override\"><code>public string GetAge(this DateTime birthdate, string ageStrinFormat = null)\n{\n var date = DateTime.Now.AddMonths(-birthdate.Month).AddDays(-birthdate.Day);\n return string.Format(ageStrinFormat ?? \"{0}/{1}/{2}\",\n (date.Year - birthdate.Year), date.Month, date.Day);\n}\n</code></pre>\n"
},
{
"answer_id": 36893577,
"author": "CathalMF",
"author_id": 1680271,
"author_profile": "https://Stackoverflow.com/users/1680271",
"pm_score": 3,
"selected": false,
"text": "<p>This is the easiest way to answer this in a single line.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime Dob = DateTime.Parse("1985-04-24");\n \nint Age = DateTime.MinValue.AddDays(DateTime.Now.Subtract(Dob).TotalHours/24 - 1).Year - 1;\n</code></pre>\n<p>This also works for leap years.</p>\n"
},
{
"answer_id": 37022367,
"author": "John Jang",
"author_id": 3634867,
"author_profile": "https://Stackoverflow.com/users/3634867",
"pm_score": 3,
"selected": false,
"text": "<p>=== <strong>Common Saying (from months to years old)</strong> ===</p>\n\n<p>If you just for common use, here is the code as your information:</p>\n\n<pre><code>DateTime today = DateTime.Today;\nDateTime bday = DateTime.Parse(\"2016-2-14\");\nint age = today.Year - bday.Year;\nvar unit = \"\";\n\nif (bday > today.AddYears(-age))\n{\n age--;\n}\nif (age == 0) // Under one year old\n{\n age = today.Month - bday.Month;\n\n age = age <= 0 ? (12 + age) : age; // The next year before birthday\n\n age = today.Day - bday.Day >= 0 ? age : --age; // Before the birthday.day\n\n unit = \"month\";\n}\nelse {\n unit = \"year\";\n}\n\nif (age > 1)\n{\n unit = unit + \"s\";\n}\n</code></pre>\n\n<p>The test result as below:</p>\n\n<pre><code>The birthday: 2016-2-14\n\n2016-2-15 => age=0, unit=month;\n2016-5-13 => age=2, unit=months;\n2016-5-14 => age=3, unit=months; \n2016-6-13 => age=3, unit=months; \n2016-6-15 => age=4, unit=months; \n2017-1-13 => age=10, unit=months; \n2017-1-14 => age=11, unit=months; \n2017-2-13 => age=11, unit=months; \n2017-2-14 => age=1, unit=year; \n2017-2-15 => age=1, unit=year; \n2017-3-13 => age=1, unit=year;\n2018-1-13 => age=1, unit=year; \n2018-1-14 => age=1, unit=year; \n2018-2-13 => age=1, unit=year; \n2018-2-14 => age=2, unit=years; \n</code></pre>\n"
},
{
"answer_id": 38121726,
"author": "xenedia",
"author_id": 836565,
"author_profile": "https://Stackoverflow.com/users/836565",
"pm_score": 3,
"selected": false,
"text": "<p>SQL version:</p>\n\n<pre><code>declare @dd smalldatetime = '1980-04-01'\ndeclare @age int = YEAR(GETDATE())-YEAR(@dd)\nif (@dd> DATEADD(YYYY, -@age, GETDATE())) set @age = @age -1\n\nprint @age \n</code></pre>\n"
},
{
"answer_id": 39779195,
"author": "André Sobreiro",
"author_id": 3177959,
"author_profile": "https://Stackoverflow.com/users/3177959",
"pm_score": 3,
"selected": false,
"text": "<p>Wow, I had to give my answer here... There are so many answers for such a simple question.</p>\n\n<pre><code>private int CalcularIdade(DateTime dtNascimento)\n {\n var nHoje = Convert.ToInt32(DateTime.Today.ToString(\"yyyyMMdd\"));\n var nAniversario = Convert.ToInt32(dtNascimento.ToString(\"yyyyMMdd\"));\n\n double diff = (nHoje - nAniversario) / 10000;\n\n var ret = Convert.ToInt32(Math.Truncate(diff));\n\n return ret;\n }\n</code></pre>\n"
},
{
"answer_id": 40196001,
"author": "K1laba",
"author_id": 1591350,
"author_profile": "https://Stackoverflow.com/users/1591350",
"pm_score": 3,
"selected": false,
"text": "<pre class=\"lang-cs prettyprint-override\"><code>private int GetYearDiff(DateTime start, DateTime end)\n{\n int diff = end.Year - start.Year;\n if (end.DayOfYear < start.DayOfYear) { diff -= 1; }\n return diff;\n}\n[Fact]\npublic void GetYearDiff_WhenCalls_ShouldReturnCorrectYearDiff()\n{\n //arrange\n var now = DateTime.Now;\n //act\n //assert\n Assert.Equal(24, GetYearDiff(new DateTime(1992, 7, 9), now)); // passed\n Assert.Equal(24, GetYearDiff(new DateTime(1992, now.Month, now.Day), now)); // passed\n Assert.Equal(23, GetYearDiff(new DateTime(1992, 12, 9), now)); // passed\n}\n</code></pre>\n"
},
{
"answer_id": 45127603,
"author": "Sean Kearon",
"author_id": 2608,
"author_profile": "https://Stackoverflow.com/users/2608",
"pm_score": 2,
"selected": false,
"text": "<p>I often count on my fingers. I need to look at a calendar to work out when things change. So that's what I'd do in my code:</p>\n\n<pre><code>int AgeNow(DateTime birthday)\n{\n return AgeAt(DateTime.Now, birthday);\n}\n\nint AgeAt(DateTime now, DateTime birthday)\n{\n return AgeAt(now, birthday, CultureInfo.CurrentCulture.Calendar);\n}\n\nint AgeAt(DateTime now, DateTime birthday, Calendar calendar)\n{\n // My age has increased on the morning of my\n // birthday even though I was born in the evening.\n now = now.Date;\n birthday = birthday.Date;\n\n var age = 0;\n if (now <= birthday) return age; // I am zero now if I am to be born tomorrow.\n\n while (calendar.AddYears(birthday, age + 1) <= now)\n {\n age++;\n }\n return age;\n}\n</code></pre>\n\n<p>Running this through in <a href=\"https://en.wikipedia.org/wiki/LINQPad\" rel=\"nofollow noreferrer\">LINQPad</a> gives this:</p>\n\n<pre><code>PASSED: someone born on 28 February 1964 is age 4 on 28 February 1968\nPASSED: someone born on 29 February 1964 is age 3 on 28 February 1968\nPASSED: someone born on 31 December 2016 is age 0 on 01 January 2017\n</code></pre>\n\n<p>Code in LINQPad is <a href=\"http://share.linqpad.net/3gx8ba.linq\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 46968983,
"author": "Sunny Jangid",
"author_id": 6803066,
"author_profile": "https://Stackoverflow.com/users/6803066",
"pm_score": 2,
"selected": false,
"text": "<p>Simple Code</p>\n\n<pre><code> var birthYear=1993;\n var age = DateTime.Now.AddYears(-birthYear).Year;\n</code></pre>\n"
},
{
"answer_id": 47035067,
"author": "Kaval Patel",
"author_id": 6629154,
"author_profile": "https://Stackoverflow.com/users/6629154",
"pm_score": 0,
"selected": false,
"text": "<p>To calculate how many years old a person is, </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime dateOfBirth;\n\nint ageInYears = DateTime.Now.Year - dateOfBirth.Year;\n\nif (dateOfBirth > today.AddYears(-ageInYears )) ageInYears --;\n</code></pre>\n"
},
{
"answer_id": 47837162,
"author": "Moises Conejo",
"author_id": 4155324,
"author_profile": "https://Stackoverflow.com/users/4155324",
"pm_score": 2,
"selected": false,
"text": "<p>Just use:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>(DateTime.Now - myDate).TotalHours / 8766.0\n</code></pre>\n\n<p>The current date - <code>myDate = TimeSpan</code>, get total hours and divide in the total hours per year and get exactly the age/months/days...</p>\n"
},
{
"answer_id": 48688691,
"author": "wild coder",
"author_id": 9106094,
"author_profile": "https://Stackoverflow.com/users/9106094",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the simplest way to calculate someone's age.<br>\nCalculating someone's age is pretty straightforward, and here's how! In order for the code to work, you need a DateTime object called BirthDate containing the birthday. </p>\n\n<pre><code> C#\n // get the difference in years\n int years = DateTime.Now.Year - BirthDate.Year; \n // subtract another year if we're before the\n // birth day in the current year\n if (DateTime.Now.Month < BirthDate.Month || \n (DateTime.Now.Month == BirthDate.Month && \n DateTime.Now.Day < BirthDate.Day)) \n years--;\n VB.NET\n ' get the difference in years\n Dim years As Integer = DateTime.Now.Year - BirthDate.Year\n ' subtract another year if we're before the\n ' birth day in the current year\n If DateTime.Now.Month < BirthDate.Month Or (DateTime.Now.Month = BirthDate.Month And DateTime.Now.Day < BirthDate.Day) Then \n years = years - 1\n End If\n</code></pre>\n"
},
{
"answer_id": 48805951,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre class=\"lang-cs prettyprint-override\"><code>var birthDate = ... // DOB\nvar resultDate = DateTime.Now - birthDate;\n</code></pre>\n\n<p>Using <code>resultDate</code> you can apply <code>TimeSpan</code> properties whatever you want to display it.</p>\n"
},
{
"answer_id": 60541141,
"author": "Alexander",
"author_id": 11841521,
"author_profile": "https://Stackoverflow.com/users/11841521",
"pm_score": 0,
"selected": false,
"text": "<p>Very simple answer</p>\n\n<pre><code> DateTime dob = new DateTime(1991, 3, 4); \n DateTime now = DateTime.Now; \n int dobDay = dob.Day, dobMonth = dob.Month; \n int add = -1; \n if (dobMonth < now.Month)\n {\n add = 0;\n }\n else if (dobMonth == now.Month)\n {\n if(dobDay <= now.Day)\n {\n add = 0;\n }\n else\n {\n add = -1;\n }\n }\n else\n {\n add = -1;\n } \n int age = now.Year - dob.Year + add;\n</code></pre>\n"
},
{
"answer_id": 64085367,
"author": "Alexander Díaz",
"author_id": 11120141,
"author_profile": "https://Stackoverflow.com/users/11120141",
"pm_score": 0,
"selected": false,
"text": "<pre><code>int Age = new DateTime((DateTime.Now - BirthDate).Ticks).Year -1;\nConsole.WriteLine("Age {0}", Age);\n</code></pre>\n"
},
{
"answer_id": 64135345,
"author": "Abrar Jahin",
"author_id": 2193439,
"author_profile": "https://Stackoverflow.com/users/2193439",
"pm_score": -1,
"selected": false,
"text": "<p>I think this problem can be solved with an easier way like this-</p>\n<p>The class can be like-</p>\n<pre><code>using System;\n\nnamespace TSA\n{\n class BirthDay\n {\n double ageDay;\n public BirthDay(int day, int month, int year)\n {\n DateTime birthDate = new DateTime(year, month, day);\n ageDay = (birthDate - DateTime.Now).TotalDays; //DateTime.UtcNow\n }\n\n internal int GetAgeYear()\n {\n return (int)Math.Truncate(ageDay / 365);\n }\n\n internal int GetAgeMonth()\n {\n return (int)Math.Truncate((ageDay % 365) / 30);\n }\n }\n}\n</code></pre>\n<p>And calls can be like-</p>\n<pre><code>BirthDay b = new BirthDay(1,12,1990);\nint year = b.GetAgeYear();\nint month = b.GetAgeMonth();\n</code></pre>\n"
},
{
"answer_id": 64220001,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I have no knowledge about <code>DateTime</code> but all I can do is this:</p>\n<pre><code>using System;\n \npublic class Program\n{\n public static int getAge(int month, int day, int year) {\n DateTime today = DateTime.Today;\n int currentDay = today.Day;\n int currentYear = today.Year;\n int currentMonth = today.Month;\n int age = 0;\n if (currentMonth < month) {\n age -= 1;\n } else if (currentMonth == month) {\n if (currentDay < day) {\n age -= 1;\n }\n }\n currentYear -= year;\n age += currentYear;\n return age;\n }\n public static void Main()\n {\n int ageInYears = getAge(8, 10, 2007);\n Console.WriteLine(ageInYears);\n }\n}\n</code></pre>\n<p>A little confusing, but looking at the code more carefully, it will all make sense.</p>\n"
},
{
"answer_id": 68783776,
"author": "Wylan Osorio",
"author_id": 2249897,
"author_profile": "https://Stackoverflow.com/users/2249897",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var startDate = new DateTime(2015, 04, 05);//your start date\nvar endDate = DateTime.Now;\nvar years = 0;\nwhile(startDate < endDate) \n{\n startDate = startDate.AddYears(1);\n if(startDate < endDate) \n {\n years++;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 69123059,
"author": "Rob",
"author_id": 3178666,
"author_profile": "https://Stackoverflow.com/users/3178666",
"pm_score": 0,
"selected": false,
"text": "<p>One could compute 'age' (i.e. the 'westerner' way) this way:</p>\n<pre><code>public static int AgeInYears(this System.DateTime source, System.DateTime target)\n => target.Year - source.Year is int age && age > 0 && source.AddYears(age) > target ? age - 1 : age < 0 && source.AddYears(age) < target ? age + 1 : age;\n</code></pre>\n<p>If the direction of time is 'negative', the age will be negative also.</p>\n<p>One can add a fraction, which represents the amount of age accumulated from target to the next birthday:</p>\n<pre><code>public static double AgeInTotalYears(this System.DateTime source, System.DateTime target)\n{\n var sign = (source <= target ? 1 : -1);\n\n var ageInYears = AgeInYears(source, target); // The method above.\n\n var last = source.AddYears(ageInYears);\n var next = source.AddYears(ageInYears + sign);\n\n var fractionalAge = (double)(target - last).Ticks / (double)(next - last).Ticks * sign;\n\n return ageInYears + fractionalAge;\n}\n</code></pre>\n<p>The fraction is the ratio of passed time (from the last birthday) over total time (to the next birthday).</p>\n<p>Both of the methods work the same way whether going forward or backward in time.</p>\n"
},
{
"answer_id": 69308492,
"author": "A.G.",
"author_id": 8261867,
"author_profile": "https://Stackoverflow.com/users/8261867",
"pm_score": 2,
"selected": false,
"text": "<p>I would strongly recommend using a NuGet package called <a href=\"https://www.nuget.org/packages/AgeCalculator/\" rel=\"nofollow noreferrer\">AgeCalculator</a> since there are many things to consider when calculating age (leap years, time component etc) and only two lines of code does not cut it. The library gives you more than just a year. It even takes into consideration the time component at the calculation so you get an accurate age with years, months, days and time components. It is more advanced giving an option to consider Feb 29 in a leap year as Feb 28 in a non-leap year.</p>\n"
},
{
"answer_id": 69981159,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This is a very simple approach:</p>\n<pre><code>int Age = DateTime.Today.Year - new DateTime(2000, 1, 1).Year;\n</code></pre>\n"
},
{
"answer_id": 70659202,
"author": "Wouter",
"author_id": 4491768,
"author_profile": "https://Stackoverflow.com/users/4491768",
"pm_score": 0,
"selected": false,
"text": "<p>A branchless solution:</p>\n<pre><code>public int GetAge(DateOnly birthDate, DateOnly today)\n{\n return today.Year - birthDate.Year + (((today.Month << 5) + today.Day - ((birthDate.Month << 5) + birthDate.Day)) >> 31);\n}\n</code></pre>\n"
},
{
"answer_id": 71185870,
"author": "subcoder",
"author_id": 8227155,
"author_profile": "https://Stackoverflow.com/users/8227155",
"pm_score": 1,
"selected": false,
"text": "<p>Simple and readable with complementary method</p>\n<pre><code>public static int getAge(DateTime birthDate)\n{\n var today = DateTime.Today;\n var age = today.Year - birthDate.Year;\n var monthDiff = today.Month - birthDate.Month;\n var dayDiff = today.Day - birthDate.Day;\n\n if (dayDiff < 0)\n {\n monthDiff--;\n }\n if (monthDiff < 0)\n {\n age--;\n }\n return age;\n}\n</code></pre>\n"
},
{
"answer_id": 73211429,
"author": "Ruchir Gupta",
"author_id": 3832403,
"author_profile": "https://Stackoverflow.com/users/3832403",
"pm_score": 0,
"selected": false,
"text": "<p>Don't know why nobody tried this:</p>\n<pre><code> ushort age = (ushort)DateAndTime.DateDiff(DateInterval.Year, DateTime.Now.Date, birthdate);\n</code></pre>\n<p>All it requires is <code>using Microsoft.VisualBasic;</code> and reference to this assembly in the project (if not already referred).</p>\n"
}
] | 2008/07/31 | [
"https://Stackoverflow.com/questions/9",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
] | Given a `DateTime` representing a person's birthday, how do I calculate their age in years? | An easy to understand and simple solution.
```cs
// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;
```
However, this assumes you are looking for the *western* idea of the age and not using [*East Asian reckoning*](https://en.wikipedia.org/wiki/East_Asian_age_reckoning). |
11 | <p>Given a specific <code>DateTime</code> value, how do I display relative time, like:</p>
<ul>
<li><code>2 hours ago</code></li>
<li><code>3 days ago</code></li>
<li><code>a month ago</code></li>
</ul>
| [
{
"answer_id": 12,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 8,
"selected": false,
"text": "<p>Here's how I do it</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);\ndouble delta = Math.Abs(ts.TotalSeconds);\n\nif (delta < 60)\n{\n return ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\";\n}\nif (delta < 60 * 2)\n{\n return \"a minute ago\";\n}\nif (delta < 45 * 60)\n{\n return ts.Minutes + \" minutes ago\";\n}\nif (delta < 90 * 60)\n{\n return \"an hour ago\";\n}\nif (delta < 24 * 60 * 60)\n{\n return ts.Hours + \" hours ago\";\n}\nif (delta < 48 * 60 * 60)\n{\n return \"yesterday\";\n}\nif (delta < 30 * 24 * 60 * 60)\n{\n return ts.Days + \" days ago\";\n}\nif (delta < 12 * 30 * 24 * 60 * 60)\n{\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n}\nint years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\nreturn years <= 1 ? \"one year ago\" : years + \" years ago\";\n</code></pre>\n\n<p>Suggestions? Comments? Ways to improve this algorithm?</p>\n"
},
{
"answer_id": 27,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 5,
"selected": false,
"text": "<p>@jeff</p>\n<p>IMHO yours seems a little long. However it does seem a little more robust with support for "yesterday" and "years". But in my experience when this is used, the person is most likely to view the content in the first 30 days. It is only the really hardcore people that come after that. So, I usually elect to keep this short and simple.</p>\n<p>This is the method I am currently using in one of my websites. This returns only a relative day, hour and time. And then the user has to slap on "ago" in the output.</p>\n<pre><code>public static string ToLongString(this TimeSpan time)\n{\n string output = String.Empty;\n\n if (time.Days > 0)\n output += time.Days + " days ";\n\n if ((time.Days == 0 || time.Days == 1) && time.Hours > 0)\n output += time.Hours + " hr ";\n\n if (time.Days == 0 && time.Minutes > 0)\n output += time.Minutes + " min ";\n\n if (output.Length == 0)\n output += time.Seconds + " sec";\n\n return output.Trim();\n}\n</code></pre>\n"
},
{
"answer_id": 1248,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 11,
"selected": true,
"text": "<p>Jeff, <a href=\"https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/12#12\">your code</a> is nice but could be clearer with constants (as suggested in Code Complete).</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>const int SECOND = 1;\nconst int MINUTE = 60 * SECOND;\nconst int HOUR = 60 * MINUTE;\nconst int DAY = 24 * HOUR;\nconst int MONTH = 30 * DAY;\n\nvar ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);\ndouble delta = Math.Abs(ts.TotalSeconds);\n\nif (delta < 1 * MINUTE)\n return ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\";\n\nif (delta < 2 * MINUTE)\n return \"a minute ago\";\n\nif (delta < 45 * MINUTE)\n return ts.Minutes + \" minutes ago\";\n\nif (delta < 90 * MINUTE)\n return \"an hour ago\";\n\nif (delta < 24 * HOUR)\n return ts.Hours + \" hours ago\";\n\nif (delta < 48 * HOUR)\n return \"yesterday\";\n\nif (delta < 30 * DAY)\n return ts.Days + \" days ago\";\n\nif (delta < 12 * MONTH)\n{\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n}\nelse\n{\n int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n return years <= 1 ? \"one year ago\" : years + \" years ago\";\n}\n</code></pre>\n"
},
{
"answer_id": 1752,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 4,
"selected": false,
"text": "<p>I thought I'd give this a shot using classes and polymorphism. I had a previous iteration which used sub-classing which ended up having way too much overhead. I've switched to a more flexible delegate / public property object model which is significantly better. My code is very slightly more accurate, I wish I could come up with a better way to generate \"months ago\" that didn't seem too over-engineered.</p>\n\n<p>I think I'd still stick with Jeff's if-then cascade because it's less code and it's simpler (it's definitely easier to ensure it'll work as expected).</p>\n\n<p>For the below code <em>PrintRelativeTime.GetRelativeTimeMessage(TimeSpan ago)</em> returns the relative time message (e.g. \"yesterday\").</p>\n\n<pre><code>public class RelativeTimeRange : IComparable\n{\n public TimeSpan UpperBound { get; set; }\n\n public delegate string RelativeTimeTextDelegate(TimeSpan timeDelta);\n\n public RelativeTimeTextDelegate MessageCreator { get; set; }\n\n public int CompareTo(object obj)\n {\n if (!(obj is RelativeTimeRange))\n {\n return 1;\n }\n // note that this sorts in reverse order to the way you'd expect, \n // this saves having to reverse a list later\n return (obj as RelativeTimeRange).UpperBound.CompareTo(UpperBound);\n }\n}\n\npublic class PrintRelativeTime\n{\n private static List<RelativeTimeRange> timeRanges;\n\n static PrintRelativeTime()\n {\n timeRanges = new List<RelativeTimeRange>{\n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromSeconds(1),\n MessageCreator = (delta) => \n { return \"one second ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromSeconds(60),\n MessageCreator = (delta) => \n { return delta.Seconds + \" seconds ago\"; }\n\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromMinutes(2),\n MessageCreator = (delta) => \n { return \"one minute ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromMinutes(60),\n MessageCreator = (delta) => \n { return delta.Minutes + \" minutes ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromHours(2),\n MessageCreator = (delta) => \n { return \"one hour ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromHours(24),\n MessageCreator = (delta) => \n { return delta.Hours + \" hours ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromDays(2),\n MessageCreator = (delta) => \n { return \"yesterday\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)),\n MessageCreator = (delta) => \n { return delta.Days + \" days ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-2)),\n MessageCreator = (delta) => \n { return \"one month ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-1)),\n MessageCreator = (delta) => \n { return (int)Math.Floor(delta.TotalDays / 30) + \" months ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-2)),\n MessageCreator = (delta) => \n { return \"one year ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.MaxValue,\n MessageCreator = (delta) => \n { return (int)Math.Floor(delta.TotalDays / 365.24D) + \" years ago\"; }\n }\n };\n\n timeRanges.Sort();\n }\n\n public static string GetRelativeTimeMessage(TimeSpan ago)\n {\n RelativeTimeRange postRelativeDateRange = timeRanges[0];\n\n foreach (var timeRange in timeRanges)\n {\n if (ago.CompareTo(timeRange.UpperBound) <= 0)\n {\n postRelativeDateRange = timeRange;\n }\n }\n\n return postRelativeDateRange.MessageCreator(ago);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10705,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 7,
"selected": false,
"text": "<pre class=\"lang-csharp prettyprint-override\"><code>public static string RelativeDate(DateTime theDate)\n{\n Dictionary<long, string> thresholds = new Dictionary<long, string>();\n int minute = 60;\n int hour = 60 * minute;\n int day = 24 * hour;\n thresholds.Add(60, \"{0} seconds ago\");\n thresholds.Add(minute * 2, \"a minute ago\");\n thresholds.Add(45 * minute, \"{0} minutes ago\");\n thresholds.Add(120 * minute, \"an hour ago\");\n thresholds.Add(day, \"{0} hours ago\");\n thresholds.Add(day * 2, \"yesterday\");\n thresholds.Add(day * 30, \"{0} days ago\");\n thresholds.Add(day * 365, \"{0} months ago\");\n thresholds.Add(long.MaxValue, \"{0} years ago\");\n long since = (DateTime.Now.Ticks - theDate.Ticks) / 10000000;\n foreach (long threshold in thresholds.Keys) \n {\n if (since < threshold) \n {\n TimeSpan t = new TimeSpan((DateTime.Now.Ticks - theDate.Ticks));\n return string.Format(thresholds[threshold], (t.Days > 365 ? t.Days / 365 : (t.Days > 0 ? t.Days : (t.Hours > 0 ? t.Hours : (t.Minutes > 0 ? t.Minutes : (t.Seconds > 0 ? t.Seconds : 0))))).ToString());\n }\n }\n return \"\";\n}\n</code></pre>\n\n<p>I prefer this version for its conciseness, and ability to add in new tick points.\nThis could be encapsulated with a <code>Latest()</code> extension to Timespan instead of that long 1 liner, but for the sake of brevity in posting, this will do.\n<strong>This fixes the an hour ago, 1 hours ago, by providing an hour until 2 hours have elapsed</strong></p>\n"
},
{
"answer_id": 12279,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 4,
"selected": false,
"text": "<p>@Jeff</p>\n\n<blockquote>\n<pre><code>var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);\n</code></pre>\n</blockquote>\n\n<p>Doing a subtraction on <code>DateTime</code> returns a <code>TimeSpan</code> anyway.</p>\n\n<p>So you can just do </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>(DateTime.UtcNow - dt).TotalSeconds\n</code></pre>\n\n<p>I'm also surprised to see the constants multiplied-out by hand and then comments added with the multiplications in. Was that some misguided optimisation?</p>\n"
},
{
"answer_id": 12852,
"author": "markpasc",
"author_id": 1472,
"author_profile": "https://Stackoverflow.com/users/1472",
"pm_score": 4,
"selected": false,
"text": "<p>When you know the viewer's time zone, it might be clearer to use calendar days at the day scale. I'm not familiar with the .NET libraries so I don't know how you'd do that in C#, unfortunately.</p>\n\n<p>On consumer sites, you could also be hand-wavier under a minute. \"Less than a minute ago\" or \"just now\" could be good enough.</p>\n"
},
{
"answer_id": 13690,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>You can reduce the server-side load by performing this logic client-side. View source on some Digg pages for reference. They have the server emit an epoch time value that gets processed by Javascript. This way you don't need to manage the end user's time zone. The new server-side code would be something like:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public string GetRelativeTime(DateTime timeStamp)\n{\n return string.Format(\"<script>printdate({0});</script>\", timeStamp.ToFileTimeUtc());\n}\n</code></pre>\n\n<p>You could even add a NOSCRIPT block there and just perform a ToString().</p>\n"
},
{
"answer_id": 18393,
"author": "icco",
"author_id": 1063,
"author_profile": "https://Stackoverflow.com/users/1063",
"pm_score": 4,
"selected": false,
"text": "<p>In PHP, I do it this way: </p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\nfunction timesince($original) {\n // array of time period chunks\n $chunks = array(\n array(60 * 60 * 24 * 365 , 'year'),\n array(60 * 60 * 24 * 30 , 'month'),\n array(60 * 60 * 24 * 7, 'week'),\n array(60 * 60 * 24 , 'day'),\n array(60 * 60 , 'hour'),\n array(60 , 'minute'),\n );\n\n $today = time(); /* Current unix time */\n $since = $today - $original;\n\n if($since > 604800) {\n $print = date(\"M jS\", $original);\n\n if($since > 31536000) {\n $print .= \", \" . date(\"Y\", $original);\n }\n\n return $print;\n}\n\n// $j saves performing the count function each time around the loop\nfor ($i = 0, $j = count($chunks); $i < $j; $i++) {\n\n $seconds = $chunks[$i][0];\n $name = $chunks[$i][1];\n\n // finding the biggest chunk (if the chunk fits, break)\n if (($count = floor($since / $seconds)) != 0) {\n break;\n }\n}\n\n$print = ($count == 1) ? '1 '.$name : \"$count {$name}s\";\n\nreturn $print . \" ago\";\n\n} ?>\n</code></pre>\n"
},
{
"answer_id": 25709,
"author": "Cebjyre",
"author_id": 1612,
"author_profile": "https://Stackoverflow.com/users/1612",
"pm_score": 2,
"selected": false,
"text": "<p>Surely an easy fix to get rid of the '1 hours ago' problem would be to increase the window that 'an hour ago' is valid for.\nChange</p>\n\n<pre><code>if (delta < 5400) // 90 * 60\n{\n return \"an hour ago\";\n}\n</code></pre>\n\n<p>into</p>\n\n<pre><code>if (delta < 7200) // 120 * 60\n{\n return \"an hour ago\";\n}\n</code></pre>\n\n<p>This means that something that occurred 110 minutes ago will read as 'an hour ago' - this may not be perfect, but I'd say it is better than the current situation of '1 hours ago'. </p>\n"
},
{
"answer_id": 79601,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<pre class=\"lang-csharp prettyprint-override\"><code>public static string ToRelativeDate(DateTime input)\n{\n TimeSpan oSpan = DateTime.Now.Subtract(input);\n double TotalMinutes = oSpan.TotalMinutes;\n string Suffix = \" ago\";\n\n if (TotalMinutes < 0.0)\n {\n TotalMinutes = Math.Abs(TotalMinutes);\n Suffix = \" from now\";\n }\n\n var aValue = new SortedList<double, Func<string>>();\n aValue.Add(0.75, () => \"less than a minute\");\n aValue.Add(1.5, () => \"about a minute\");\n aValue.Add(45, () => string.Format(\"{0} minutes\", Math.Round(TotalMinutes)));\n aValue.Add(90, () => \"about an hour\");\n aValue.Add(1440, () => string.Format(\"about {0} hours\", Math.Round(Math.Abs(oSpan.TotalHours)))); // 60 * 24\n aValue.Add(2880, () => \"a day\"); // 60 * 48\n aValue.Add(43200, () => string.Format(\"{0} days\", Math.Floor(Math.Abs(oSpan.TotalDays)))); // 60 * 24 * 30\n aValue.Add(86400, () => \"about a month\"); // 60 * 24 * 60\n aValue.Add(525600, () => string.Format(\"{0} months\", Math.Floor(Math.Abs(oSpan.TotalDays / 30)))); // 60 * 24 * 365 \n aValue.Add(1051200, () => \"about a year\"); // 60 * 24 * 365 * 2\n aValue.Add(double.MaxValue, () => string.Format(\"{0} years\", Math.Floor(Math.Abs(oSpan.TotalDays / 365))));\n\n return aValue.First(n => TotalMinutes < n.Key).Value.Invoke() + Suffix;\n}\n</code></pre>\n\n<p><a href=\"http://refactormycode.com/codes/493-twitter-esque-relative-dates\" rel=\"noreferrer\">http://refactormycode.com/codes/493-twitter-esque-relative-dates</a></p>\n\n<p>C# 6 version:</p>\n\n<pre><code>static readonly SortedList<double, Func<TimeSpan, string>> offsets = \n new SortedList<double, Func<TimeSpan, string>>\n{\n { 0.75, _ => \"less than a minute\"},\n { 1.5, _ => \"about a minute\"},\n { 45, x => $\"{x.TotalMinutes:F0} minutes\"},\n { 90, x => \"about an hour\"},\n { 1440, x => $\"about {x.TotalHours:F0} hours\"},\n { 2880, x => \"a day\"},\n { 43200, x => $\"{x.TotalDays:F0} days\"},\n { 86400, x => \"about a month\"},\n { 525600, x => $\"{x.TotalDays / 30:F0} months\"},\n { 1051200, x => \"about a year\"},\n { double.MaxValue, x => $\"{x.TotalDays / 365:F0} years\"}\n};\n\npublic static string ToRelativeDate(this DateTime input)\n{\n TimeSpan x = DateTime.Now - input;\n string Suffix = x.TotalMinutes > 0 ? \" ago\" : \" from now\";\n x = new TimeSpan(Math.Abs(x.Ticks));\n return offsets.First(n => x.TotalMinutes < n.Key).Value(x) + Suffix;\n}\n</code></pre>\n"
},
{
"answer_id": 111303,
"author": "Ryan McGeary",
"author_id": 8985,
"author_profile": "https://Stackoverflow.com/users/8985",
"pm_score": 9,
"selected": false,
"text": "<h2><a href=\"https://timeago.yarp.com/\" rel=\"noreferrer\">jquery.timeago plugin</a></h2>\n\n<p>Jeff, because Stack Overflow uses jQuery extensively, I recommend the <a href=\"https://timeago.yarp.com/\" rel=\"noreferrer\">jquery.timeago plugin</a>. </p>\n\n<p>Benefits:</p>\n\n<ul>\n<li>Avoid timestamps dated \"1 minute ago\" even though the page was opened 10 minutes ago; timeago refreshes automatically.</li>\n<li>You can take full advantage of page and/or fragment caching in your web applications, because the timestamps aren't calculated on the server.</li>\n<li>You get to use microformats like the cool kids.</li>\n</ul>\n\n<p>Just attach it to your timestamps on DOM ready:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>jQuery(document).ready(function() {\n jQuery('abbr.timeago').timeago();\n});\n</code></pre>\n\n<p>This will turn all <code>abbr</code> elements with a class of timeago and an <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"noreferrer\">ISO 8601</a> timestamp in the title:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><abbr class=\"timeago\" title=\"2008-07-17T09:24:17Z\">July 17, 2008</abbr>\n</code></pre>\n\n<p>into something like this:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><abbr class=\"timeago\" title=\"July 17, 2008\">4 months ago</abbr>\n</code></pre>\n\n<p>which yields: 4 months ago. As time passes, the timestamps will automatically update. </p>\n\n<p><em>Disclaimer: I wrote this plugin, so I'm biased.</em></p>\n"
},
{
"answer_id": 118569,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 3,
"selected": false,
"text": "<p>Here's the algorithm stackoverflow uses but rewritten more concisely in perlish pseudocode with a bug fix (no \"one hours ago\"). The function takes a (positive) number of seconds ago and returns a human-friendly string like \"3 hours ago\" or \"yesterday\".</p>\n\n<pre><code>agoify($delta)\n local($y, $mo, $d, $h, $m, $s);\n $s = floor($delta);\n if($s<=1) return \"a second ago\";\n if($s<60) return \"$s seconds ago\";\n $m = floor($s/60);\n if($m==1) return \"a minute ago\";\n if($m<45) return \"$m minutes ago\";\n $h = floor($m/60);\n if($h==1) return \"an hour ago\";\n if($h<24) return \"$h hours ago\";\n $d = floor($h/24);\n if($d<2) return \"yesterday\";\n if($d<30) return \"$d days ago\";\n $mo = floor($d/30);\n if($mo<=1) return \"a month ago\";\n $y = floor($mo/12);\n if($y<1) return \"$mo months ago\";\n if($y==1) return \"a year ago\";\n return \"$y years ago\";\n</code></pre>\n"
},
{
"answer_id": 229285,
"author": "Jauder Ho",
"author_id": 26366,
"author_profile": "https://Stackoverflow.com/users/26366",
"pm_score": 5,
"selected": false,
"text": "<p>I would recommend computing this on the client side too. Less work for the server. </p>\n\n<p>The following is the version that I use (from Zach Leatherman)</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>/*\n * Javascript Humane Dates\n * Copyright (c) 2008 Dean Landolt (deanlandolt.com)\n * Re-write by Zach Leatherman (zachleat.com)\n * \n * Adopted from the John Resig's pretty.js\n * at http://ejohn.org/blog/javascript-pretty-date\n * and henrah's proposed modification \n * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458\n * \n * Licensed under the MIT license.\n */\n\nfunction humane_date(date_str){\n var time_formats = [\n [60, 'just now'],\n [90, '1 minute'], // 60*1.5\n [3600, 'minutes', 60], // 60*60, 60\n [5400, '1 hour'], // 60*60*1.5\n [86400, 'hours', 3600], // 60*60*24, 60*60\n [129600, '1 day'], // 60*60*24*1.5\n [604800, 'days', 86400], // 60*60*24*7, 60*60*24\n [907200, '1 week'], // 60*60*24*7*1.5\n [2628000, 'weeks', 604800], // 60*60*24*(365/12), 60*60*24*7\n [3942000, '1 month'], // 60*60*24*(365/12)*1.5\n [31536000, 'months', 2628000], // 60*60*24*365, 60*60*24*(365/12)\n [47304000, '1 year'], // 60*60*24*365*1.5\n [3153600000, 'years', 31536000], // 60*60*24*365*100, 60*60*24*365\n [4730400000, '1 century'] // 60*60*24*365*100*1.5\n ];\n\n var time = ('' + date_str).replace(/-/g,\"/\").replace(/[TZ]/g,\" \"),\n dt = new Date,\n seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),\n token = ' ago',\n i = 0,\n format;\n\n if (seconds < 0) {\n seconds = Math.abs(seconds);\n token = '';\n }\n\n while (format = time_formats[i++]) {\n if (seconds < format[0]) {\n if (format.length == 2) {\n return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago\n } else {\n return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');\n }\n }\n }\n\n // overflow for centuries\n if(seconds > 4730400000)\n return Math.round(seconds / 4730400000) + ' centuries' + token;\n\n return date_str;\n};\n\nif(typeof jQuery != 'undefined') {\n jQuery.fn.humane_dates = function(){\n return this.each(function(){\n var date = humane_date(this.title);\n if(date && jQuery(this).text() != date) // don't modify the dom if we don't have to\n jQuery(this).text(date);\n });\n };\n}\n</code></pre>\n"
},
{
"answer_id": 501415,
"author": "Thomaschaaf",
"author_id": 19929,
"author_profile": "https://Stackoverflow.com/users/19929",
"pm_score": 6,
"selected": false,
"text": "<p>Here a rewrite from Jeffs Script for PHP:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>define(\"SECOND\", 1);\ndefine(\"MINUTE\", 60 * SECOND);\ndefine(\"HOUR\", 60 * MINUTE);\ndefine(\"DAY\", 24 * HOUR);\ndefine(\"MONTH\", 30 * DAY);\nfunction relativeTime($time)\n{ \n $delta = time() - $time;\n\n if ($delta < 1 * MINUTE)\n {\n return $delta == 1 ? \"one second ago\" : $delta . \" seconds ago\";\n }\n if ($delta < 2 * MINUTE)\n {\n return \"a minute ago\";\n }\n if ($delta < 45 * MINUTE)\n {\n return floor($delta / MINUTE) . \" minutes ago\";\n }\n if ($delta < 90 * MINUTE)\n {\n return \"an hour ago\";\n }\n if ($delta < 24 * HOUR)\n {\n return floor($delta / HOUR) . \" hours ago\";\n }\n if ($delta < 48 * HOUR)\n {\n return \"yesterday\";\n }\n if ($delta < 30 * DAY)\n {\n return floor($delta / DAY) . \" days ago\";\n }\n if ($delta < 12 * MONTH)\n {\n $months = floor($delta / DAY / 30);\n return $months <= 1 ? \"one month ago\" : $months . \" months ago\";\n }\n else\n {\n $years = floor($delta / DAY / 365);\n return $years <= 1 ? \"one year ago\" : $years . \" years ago\";\n }\n} \n</code></pre>\n"
},
{
"answer_id": 569913,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Is there an easy way to do this in Java? The <code>java.util.Date</code> class seems rather limited.</p>\n\n<p>Here is my quick and dirty Java solution:</p>\n\n<pre><code>import java.util.Date;\nimport javax.management.timer.Timer;\n\nString getRelativeDate(Date date) { \n long delta = new Date().getTime() - date.getTime();\n if (delta < 1L * Timer.ONE_MINUTE) {\n return toSeconds(delta) == 1 ? \"one second ago\" : toSeconds(delta) + \" seconds ago\";\n }\n if (delta < 2L * Timer.ONE_MINUTE) {\n return \"a minute ago\";\n }\n if (delta < 45L * Timer.ONE_MINUTE) {\n return toMinutes(delta) + \" minutes ago\";\n }\n if (delta < 90L * Timer.ONE_MINUTE) {\n return \"an hour ago\";\n }\n if (delta < 24L * Timer.ONE_HOUR) {\n return toHours(delta) + \" hours ago\";\n }\n if (delta < 48L * Timer.ONE_HOUR) {\n return \"yesterday\";\n }\n if (delta < 30L * Timer.ONE_DAY) {\n return toDays(delta) + \" days ago\";\n }\n if (delta < 12L * 4L * Timer.ONE_WEEK) { // a month\n long months = toMonths(delta); \n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n }\n else {\n long years = toYears(delta);\n return years <= 1 ? \"one year ago\" : years + \" years ago\";\n }\n}\n\nprivate long toSeconds(long date) {\n return date / 1000L;\n}\n\nprivate long toMinutes(long date) {\n return toSeconds(date) / 60L;\n}\n\nprivate long toHours(long date) {\n return toMinutes(date) / 60L;\n}\n\nprivate long toDays(long date) {\n return toHours(date) / 24L;\n}\n\nprivate long toMonths(long date) {\n return toDays(date) / 30L;\n}\n\nprivate long toYears(long date) {\n return toMonths(date) / 365L;\n}\n</code></pre>\n"
},
{
"answer_id": 628203,
"author": "neuracnu",
"author_id": 19277,
"author_profile": "https://Stackoverflow.com/users/19277",
"pm_score": 6,
"selected": false,
"text": "<p>Here's an implementation I added as an extension method to the DateTime class that handles both future and past dates and provides an approximation option that allows you to specify the level of detail you're looking for (\"3 hour ago\" vs \"3 hours, 23 minutes, 12 seconds ago\"):</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>using System.Text;\n\n/// <summary>\n/// Compares a supplied date to the current date and generates a friendly English \n/// comparison (\"5 days ago\", \"5 days from now\")\n/// </summary>\n/// <param name=\"date\">The date to convert</param>\n/// <param name=\"approximate\">When off, calculate timespan down to the second.\n/// When on, approximate to the largest round unit of time.</param>\n/// <returns></returns>\npublic static string ToRelativeDateString(this DateTime value, bool approximate)\n{\n StringBuilder sb = new StringBuilder();\n\n string suffix = (value > DateTime.Now) ? \" from now\" : \" ago\";\n\n TimeSpan timeSpan = new TimeSpan(Math.Abs(DateTime.Now.Subtract(value).Ticks));\n\n if (timeSpan.Days > 0)\n {\n sb.AppendFormat(\"{0} {1}\", timeSpan.Days,\n (timeSpan.Days > 1) ? \"days\" : \"day\");\n if (approximate) return sb.ToString() + suffix;\n }\n if (timeSpan.Hours > 0)\n {\n sb.AppendFormat(\"{0}{1} {2}\", (sb.Length > 0) ? \", \" : string.Empty,\n timeSpan.Hours, (timeSpan.Hours > 1) ? \"hours\" : \"hour\");\n if (approximate) return sb.ToString() + suffix;\n }\n if (timeSpan.Minutes > 0)\n {\n sb.AppendFormat(\"{0}{1} {2}\", (sb.Length > 0) ? \", \" : string.Empty, \n timeSpan.Minutes, (timeSpan.Minutes > 1) ? \"minutes\" : \"minute\");\n if (approximate) return sb.ToString() + suffix;\n }\n if (timeSpan.Seconds > 0)\n {\n sb.AppendFormat(\"{0}{1} {2}\", (sb.Length > 0) ? \", \" : string.Empty, \n timeSpan.Seconds, (timeSpan.Seconds > 1) ? \"seconds\" : \"second\");\n if (approximate) return sb.ToString() + suffix;\n }\n if (sb.Length == 0) return \"right now\";\n\n sb.Append(suffix);\n return sb.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 1141237,
"author": "Chris Charabaruk",
"author_id": 5697,
"author_profile": "https://Stackoverflow.com/users/5697",
"pm_score": 4,
"selected": false,
"text": "<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class RelativeDateHelper\n{\n private static Dictionary<double, Func<double, string>> sm_Dict = null;\n\n private static Dictionary<double, Func<double, string>> DictionarySetup()\n {\n var dict = new Dictionary<double, Func<double, string>>();\n dict.Add(0.75, (mins) => \"less than a minute\");\n dict.Add(1.5, (mins) => \"about a minute\");\n dict.Add(45, (mins) => string.Format(\"{0} minutes\", Math.Round(mins)));\n dict.Add(90, (mins) => \"about an hour\");\n dict.Add(1440, (mins) => string.Format(\"about {0} hours\", Math.Round(Math.Abs(mins / 60)))); // 60 * 24\n dict.Add(2880, (mins) => \"a day\"); // 60 * 48\n dict.Add(43200, (mins) => string.Format(\"{0} days\", Math.Floor(Math.Abs(mins / 1440)))); // 60 * 24 * 30\n dict.Add(86400, (mins) => \"about a month\"); // 60 * 24 * 60\n dict.Add(525600, (mins) => string.Format(\"{0} months\", Math.Floor(Math.Abs(mins / 43200)))); // 60 * 24 * 365 \n dict.Add(1051200, (mins) => \"about a year\"); // 60 * 24 * 365 * 2\n dict.Add(double.MaxValue, (mins) => string.Format(\"{0} years\", Math.Floor(Math.Abs(mins / 525600))));\n\n return dict;\n }\n\n public static string ToRelativeDate(this DateTime input)\n {\n TimeSpan oSpan = DateTime.Now.Subtract(input);\n double TotalMinutes = oSpan.TotalMinutes;\n string Suffix = \" ago\";\n\n if (TotalMinutes < 0.0)\n {\n TotalMinutes = Math.Abs(TotalMinutes);\n Suffix = \" from now\";\n }\n\n if (null == sm_Dict)\n sm_Dict = DictionarySetup();\n\n return sm_Dict.First(n => TotalMinutes < n.Key).Value.Invoke(TotalMinutes) + Suffix;\n }\n}\n</code></pre>\n\n<p>The same as <a href=\"https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/79601#79601\">another answer to this question</a> but as an extension method with a static dictionary.</p>\n"
},
{
"answer_id": 1379178,
"author": "Simon",
"author_id": 53158,
"author_profile": "https://Stackoverflow.com/users/53158",
"pm_score": 4,
"selected": false,
"text": "<p>using <a href=\"https://github.com/FluentDateTime\" rel=\"nofollow noreferrer\">Fluent DateTime</a></p>\n\n<pre><code>var dateTime1 = 2.Hours().Ago();\nvar dateTime2 = 3.Days().Ago();\nvar dateTime3 = 1.Months().Ago();\nvar dateTime4 = 5.Hours().FromNow();\nvar dateTime5 = 2.Weeks().FromNow();\nvar dateTime6 = 40.Seconds().FromNow();\n</code></pre>\n"
},
{
"answer_id": 1735172,
"author": "antony.trupe",
"author_id": 5849,
"author_profile": "https://Stackoverflow.com/users/5849",
"pm_score": 3,
"selected": false,
"text": "<p>Java for client-side gwt usage:</p>\n\n<pre><code>import java.util.Date;\n\npublic class RelativeDateFormat {\n\n private static final long ONE_MINUTE = 60000L;\n private static final long ONE_HOUR = 3600000L;\n private static final long ONE_DAY = 86400000L;\n private static final long ONE_WEEK = 604800000L;\n\n public static String format(Date date) {\n\n long delta = new Date().getTime() - date.getTime();\n if (delta < 1L * ONE_MINUTE) {\n return toSeconds(delta) == 1 ? \"one second ago\" : toSeconds(delta)\n + \" seconds ago\";\n }\n if (delta < 2L * ONE_MINUTE) {\n return \"one minute ago\";\n }\n if (delta < 45L * ONE_MINUTE) {\n return toMinutes(delta) + \" minutes ago\";\n }\n if (delta < 90L * ONE_MINUTE) {\n return \"one hour ago\";\n }\n if (delta < 24L * ONE_HOUR) {\n return toHours(delta) + \" hours ago\";\n }\n if (delta < 48L * ONE_HOUR) {\n return \"yesterday\";\n }\n if (delta < 30L * ONE_DAY) {\n return toDays(delta) + \" days ago\";\n }\n if (delta < 12L * 4L * ONE_WEEK) {\n long months = toMonths(delta);\n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n } else {\n long years = toYears(delta);\n return years <= 1 ? \"one year ago\" : years + \" years ago\";\n }\n }\n\n private static long toSeconds(long date) {\n return date / 1000L;\n }\n\n private static long toMinutes(long date) {\n return toSeconds(date) / 60L;\n }\n\n private static long toHours(long date) {\n return toMinutes(date) / 60L;\n }\n\n private static long toDays(long date) {\n return toHours(date) / 24L;\n }\n\n private static long toMonths(long date) {\n return toDays(date) / 30L;\n }\n\n private static long toYears(long date) {\n return toMonths(date) / 365L;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 2179589,
"author": "Buhake Sindi",
"author_id": 251173,
"author_profile": "https://Stackoverflow.com/users/251173",
"pm_score": 3,
"selected": false,
"text": "<p>I got this answer from one of Bill Gates' blogs. I need to find it on my browser history and I'll give you the link.</p>\n<p>The Javascript code to do the same thing (as requested):</p>\n<pre class=\"lang-js prettyprint-override\"><code>function posted(t) {\n var now = new Date();\n var diff = parseInt((now.getTime() - Date.parse(t)) / 1000);\n if (diff < 60) { return 'less than a minute ago'; }\n else if (diff < 120) { return 'about a minute ago'; }\n else if (diff < (2700)) { return (parseInt(diff / 60)).toString() + ' minutes ago'; }\n else if (diff < (5400)) { return 'about an hour ago'; }\n else if (diff < (86400)) { return 'about ' + (parseInt(diff / 3600)).toString() + ' hours ago'; }\n else if (diff < (172800)) { return '1 day ago'; } \n else {return (parseInt(diff / 86400)).toString() + ' days ago'; }\n}\n</code></pre>\n<p>Basically, you work in terms of seconds.</p>\n"
},
{
"answer_id": 2244324,
"author": "0llie",
"author_id": 229906,
"author_profile": "https://Stackoverflow.com/users/229906",
"pm_score": 4,
"selected": false,
"text": "<h2>iPhone Objective-C Version</h2>\n\n<pre><code>+ (NSString *)timeAgoString:(NSDate *)date {\n int delta = -(int)[date timeIntervalSinceNow];\n\n if (delta < 60)\n {\n return delta == 1 ? @\"one second ago\" : [NSString stringWithFormat:@\"%i seconds ago\", delta];\n }\n if (delta < 120)\n {\n return @\"a minute ago\";\n }\n if (delta < 2700)\n {\n return [NSString stringWithFormat:@\"%i minutes ago\", delta/60];\n }\n if (delta < 5400)\n {\n return @\"an hour ago\";\n }\n if (delta < 24 * 3600)\n {\n return [NSString stringWithFormat:@\"%i hours ago\", delta/3600];\n }\n if (delta < 48 * 3600)\n {\n return @\"yesterday\";\n }\n if (delta < 30 * 24 * 3600)\n {\n return [NSString stringWithFormat:@\"%i days ago\", delta/(24*3600)];\n }\n if (delta < 12 * 30 * 24 * 3600)\n {\n int months = delta/(30*24*3600);\n return months <= 1 ? @\"one month ago\" : [NSString stringWithFormat:@\"%i months ago\", months];\n }\n else\n {\n int years = delta/(12*30*24*3600);\n return years <= 1 ? @\"one year ago\" : [NSString stringWithFormat:@\"%i years ago\", years];\n }\n}\n</code></pre>\n"
},
{
"answer_id": 5427203,
"author": "Town",
"author_id": 54975,
"author_profile": "https://Stackoverflow.com/users/54975",
"pm_score": 5,
"selected": false,
"text": "<p>A couple of years late to the party, but I had a requirement to do this for both past and future dates, so I combined <a href=\"https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/12#12\">Jeff</a>'s and <a href=\"https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/1248#1248\">Vincent's</a> into this. It's a ternarytastic extravaganza! :)</p>\n\n<pre><code>public static class DateTimeHelper\n {\n private const int SECOND = 1;\n private const int MINUTE = 60 * SECOND;\n private const int HOUR = 60 * MINUTE;\n private const int DAY = 24 * HOUR;\n private const int MONTH = 30 * DAY;\n\n /// <summary>\n /// Returns a friendly version of the provided DateTime, relative to now. E.g.: \"2 days ago\", or \"in 6 months\".\n /// </summary>\n /// <param name=\"dateTime\">The DateTime to compare to Now</param>\n /// <returns>A friendly string</returns>\n public static string GetFriendlyRelativeTime(DateTime dateTime)\n {\n if (DateTime.UtcNow.Ticks == dateTime.Ticks)\n {\n return \"Right now!\";\n }\n\n bool isFuture = (DateTime.UtcNow.Ticks < dateTime.Ticks);\n var ts = DateTime.UtcNow.Ticks < dateTime.Ticks ? new TimeSpan(dateTime.Ticks - DateTime.UtcNow.Ticks) : new TimeSpan(DateTime.UtcNow.Ticks - dateTime.Ticks);\n\n double delta = ts.TotalSeconds;\n\n if (delta < 1 * MINUTE)\n {\n return isFuture ? \"in \" + (ts.Seconds == 1 ? \"one second\" : ts.Seconds + \" seconds\") : ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\";\n }\n if (delta < 2 * MINUTE)\n {\n return isFuture ? \"in a minute\" : \"a minute ago\";\n }\n if (delta < 45 * MINUTE)\n {\n return isFuture ? \"in \" + ts.Minutes + \" minutes\" : ts.Minutes + \" minutes ago\";\n }\n if (delta < 90 * MINUTE)\n {\n return isFuture ? \"in an hour\" : \"an hour ago\";\n }\n if (delta < 24 * HOUR)\n {\n return isFuture ? \"in \" + ts.Hours + \" hours\" : ts.Hours + \" hours ago\";\n }\n if (delta < 48 * HOUR)\n {\n return isFuture ? \"tomorrow\" : \"yesterday\";\n }\n if (delta < 30 * DAY)\n {\n return isFuture ? \"in \" + ts.Days + \" days\" : ts.Days + \" days ago\";\n }\n if (delta < 12 * MONTH)\n {\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return isFuture ? \"in \" + (months <= 1 ? \"one month\" : months + \" months\") : months <= 1 ? \"one month ago\" : months + \" months ago\";\n }\n else\n {\n int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n return isFuture ? \"in \" + (years <= 1 ? \"one year\" : years + \" years\") : years <= 1 ? \"one year ago\" : years + \" years ago\";\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 5835905,
"author": "Owen Blacker",
"author_id": 205245,
"author_profile": "https://Stackoverflow.com/users/205245",
"pm_score": 4,
"selected": false,
"text": "<p>\nGiven the world and her husband appear to be posting code samples, here is what I wrote a while ago, based on a couple of these answers.</p>\n\n<p>I had a specific need for this code to be localisable. So I have two classes — <code>Grammar</code>, which specifies the localisable terms, and <code>FuzzyDateExtensions</code>, which holds a bunch of extension methods. I had no need to deal with future datetimes, so no attempt is made to handle them with this code.</p>\n\n<p>I've left some of the XMLdoc in the source, but removed most (where they'd be obvious) for brevity's sake. I've also not included every class member here:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class Grammar\n{\n /// <summary> Gets or sets the term for \"just now\". </summary>\n public string JustNow { get; set; }\n /// <summary> Gets or sets the term for \"X minutes ago\". </summary>\n /// <remarks>\n /// This is a <see cref=\"String.Format\"/> pattern, where <c>{0}</c>\n /// is the number of minutes.\n /// </remarks>\n public string MinutesAgo { get; set; }\n public string OneHourAgo { get; set; }\n public string HoursAgo { get; set; }\n public string Yesterday { get; set; }\n public string DaysAgo { get; set; }\n public string LastMonth { get; set; }\n public string MonthsAgo { get; set; }\n public string LastYear { get; set; }\n public string YearsAgo { get; set; }\n /// <summary> Gets or sets the term for \"ages ago\". </summary>\n public string AgesAgo { get; set; }\n\n /// <summary>\n /// Gets or sets the threshold beyond which the fuzzy date should be\n /// considered \"ages ago\".\n /// </summary>\n public TimeSpan AgesAgoThreshold { get; set; }\n\n /// <summary>\n /// Initialises a new <see cref=\"Grammar\"/> instance with the\n /// specified properties.\n /// </summary>\n private void Initialise(string justNow, string minutesAgo,\n string oneHourAgo, string hoursAgo, string yesterday, string daysAgo,\n string lastMonth, string monthsAgo, string lastYear, string yearsAgo,\n string agesAgo, TimeSpan agesAgoThreshold)\n { ... }\n}\n</code></pre>\n\n<p>The <code>FuzzyDateString</code> class contains:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static class FuzzyDateExtensions\n{\n public static string ToFuzzyDateString(this TimeSpan timespan)\n {\n return timespan.ToFuzzyDateString(new Grammar());\n }\n\n public static string ToFuzzyDateString(this TimeSpan timespan,\n Grammar grammar)\n {\n return GetFuzzyDateString(timespan, grammar);\n }\n\n public static string ToFuzzyDateString(this DateTime datetime)\n {\n return (DateTime.Now - datetime).ToFuzzyDateString();\n }\n\n public static string ToFuzzyDateString(this DateTime datetime,\n Grammar grammar)\n {\n return (DateTime.Now - datetime).ToFuzzyDateString(grammar);\n }\n\n\n private static string GetFuzzyDateString(TimeSpan timespan,\n Grammar grammar)\n {\n timespan = timespan.Duration();\n\n if (timespan >= grammar.AgesAgoThreshold)\n {\n return grammar.AgesAgo;\n }\n\n if (timespan < new TimeSpan(0, 2, 0)) // 2 minutes\n {\n return grammar.JustNow;\n }\n\n if (timespan < new TimeSpan(1, 0, 0)) // 1 hour\n {\n return String.Format(grammar.MinutesAgo, timespan.Minutes);\n }\n\n if (timespan < new TimeSpan(1, 55, 0)) // 1 hour 55 minutes\n {\n return grammar.OneHourAgo;\n }\n\n if (timespan < new TimeSpan(12, 0, 0) // 12 hours\n && (DateTime.Now - timespan).IsToday())\n {\n return String.Format(grammar.HoursAgo, timespan.RoundedHours());\n }\n\n if ((DateTime.Now.AddDays(1) - timespan).IsToday())\n {\n return grammar.Yesterday;\n }\n\n if (timespan < new TimeSpan(32, 0, 0, 0) // 32 days\n && (DateTime.Now - timespan).IsThisMonth())\n {\n return String.Format(grammar.DaysAgo, timespan.RoundedDays());\n }\n\n if ((DateTime.Now.AddMonths(1) - timespan).IsThisMonth())\n {\n return grammar.LastMonth;\n }\n\n if (timespan < new TimeSpan(365, 0, 0, 0, 0) // 365 days\n && (DateTime.Now - timespan).IsThisYear())\n {\n return String.Format(grammar.MonthsAgo, timespan.RoundedMonths());\n }\n\n if ((DateTime.Now - timespan).AddYears(1).IsThisYear())\n {\n return grammar.LastYear;\n }\n\n return String.Format(grammar.YearsAgo, timespan.RoundedYears());\n }\n}\n</code></pre>\n\n<p>One of the key things I wanted to achieve, as well as localisation, was that \"today\" would only mean \"this calendar day\", so the <code>IsToday</code>, <code>IsThisMonth</code>, <code>IsThisYear</code> methods look like this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static bool IsToday(this DateTime date)\n{\n return date.DayOfYear == DateTime.Now.DayOfYear && date.IsThisYear();\n}\n</code></pre>\n\n<p>and the rounding methods are like this (I've included <code>RoundedMonths</code>, as that's a bit different):</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static int RoundedDays(this TimeSpan timespan)\n{\n return (timespan.Hours > 12) ? timespan.Days + 1 : timespan.Days;\n}\n\npublic static int RoundedMonths(this TimeSpan timespan)\n{\n DateTime then = DateTime.Now - timespan;\n\n // Number of partial months elapsed since 1 Jan, AD 1 (DateTime.MinValue)\n int nowMonthYears = DateTime.Now.Year * 12 + DateTime.Now.Month;\n int thenMonthYears = then.Year * 12 + then.Month; \n\n return nowMonthYears - thenMonthYears;\n}\n</code></pre>\n\n<p>I hope people find this useful and/or interesting :o)</p>\n"
},
{
"answer_id": 10775917,
"author": "JoeyFur62",
"author_id": 1420406,
"author_profile": "https://Stackoverflow.com/users/1420406",
"pm_score": 3,
"selected": false,
"text": "<pre class=\"lang-cs prettyprint-override\"><code>var ts = new TimeSpan(DateTime.Now.Ticks - dt.Ticks);\n</code></pre>\n"
},
{
"answer_id": 12406029,
"author": "tugberk",
"author_id": 463785,
"author_profile": "https://Stackoverflow.com/users/463785",
"pm_score": 3,
"selected": false,
"text": "<p>I would provide some handy extensions methods for this and make the code more readable. First, couple of extension methods for <code>Int32</code>.</p>\n\n<pre><code>public static class TimeSpanExtensions {\n\n public static TimeSpan Days(this int value) {\n\n return new TimeSpan(value, 0, 0, 0);\n }\n\n public static TimeSpan Hours(this int value) {\n\n return new TimeSpan(0, value, 0, 0);\n }\n\n public static TimeSpan Minutes(this int value) {\n\n return new TimeSpan(0, 0, value, 0);\n }\n\n public static TimeSpan Seconds(this int value) {\n\n return new TimeSpan(0, 0, 0, value);\n }\n\n public static TimeSpan Milliseconds(this int value) {\n\n return new TimeSpan(0, 0, 0, 0, value);\n }\n\n public static DateTime Ago(this TimeSpan value) {\n\n return DateTime.Now - value;\n }\n}\n</code></pre>\n\n<p>Then, one for <code>DateTime</code>.</p>\n\n<pre><code>public static class DateTimeExtensions {\n\n public static DateTime Ago(this DateTime dateTime, TimeSpan delta) {\n\n return dateTime - delta;\n }\n}\n</code></pre>\n\n<p>Now, you can do something like below:</p>\n\n<pre><code>var date = DateTime.Now;\ndate.Ago(2.Days()); // 2 days ago\ndate.Ago(7.Hours()); // 7 hours ago\ndate.Ago(567.Milliseconds()); // 567 milliseconds ago\n</code></pre>\n"
},
{
"answer_id": 15446338,
"author": "Prashant Gupta",
"author_id": 985335,
"author_profile": "https://Stackoverflow.com/users/985335",
"pm_score": 3,
"selected": false,
"text": "<p>I think there is already a number of answers related to this post, but one can use this which is easy to use just like plugin and also easily readable for programmers. \nSend your specific date, and get its value in string form:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public string RelativeDateTimeCount(DateTime inputDateTime)\n{\n string outputDateTime = string.Empty;\n TimeSpan ts = DateTime.Now - inputDateTime;\n\n if (ts.Days > 7)\n { outputDateTime = inputDateTime.ToString(\"MMMM d, yyyy\"); }\n\n else if (ts.Days > 0)\n {\n outputDateTime = ts.Days == 1 ? (\"about 1 Day ago\") : (\"about \" + ts.Days.ToString() + \" Days ago\");\n }\n else if (ts.Hours > 0)\n {\n outputDateTime = ts.Hours == 1 ? (\"an hour ago\") : (ts.Hours.ToString() + \" hours ago\");\n }\n else if (ts.Minutes > 0)\n {\n outputDateTime = ts.Minutes == 1 ? (\"1 minute ago\") : (ts.Minutes.ToString() + \" minutes ago\");\n }\n else outputDateTime = \"few seconds ago\";\n\n return outputDateTime;\n}\n</code></pre>\n"
},
{
"answer_id": 18074585,
"author": "string.Empty",
"author_id": 2027232,
"author_profile": "https://Stackoverflow.com/users/2027232",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public string getRelativeDateTime(DateTime date)\n{\n TimeSpan ts = DateTime.Now - date;\n if (ts.TotalMinutes < 1)//seconds ago\n return \"just now\";\n if (ts.TotalHours < 1)//min ago\n return (int)ts.TotalMinutes == 1 ? \"1 Minute ago\" : (int)ts.TotalMinutes + \" Minutes ago\";\n if (ts.TotalDays < 1)//hours ago\n return (int)ts.TotalHours == 1 ? \"1 Hour ago\" : (int)ts.TotalHours + \" Hours ago\";\n if (ts.TotalDays < 7)//days ago\n return (int)ts.TotalDays == 1 ? \"1 Day ago\" : (int)ts.TotalDays + \" Days ago\";\n if (ts.TotalDays < 30.4368)//weeks ago\n return (int)(ts.TotalDays / 7) == 1 ? \"1 Week ago\" : (int)(ts.TotalDays / 7) + \" Weeks ago\";\n if (ts.TotalDays < 365.242)//months ago\n return (int)(ts.TotalDays / 30.4368) == 1 ? \"1 Month ago\" : (int)(ts.TotalDays / 30.4368) + \" Months ago\";\n //years ago\n return (int)(ts.TotalDays / 365.242) == 1 ? \"1 Year ago\" : (int)(ts.TotalDays / 365.242) + \" Years ago\";\n}\n</code></pre>\n\n<p>Conversion values for days in a month and year were taken from Google.</p>\n"
},
{
"answer_id": 19377828,
"author": "Premdeep Mohanty",
"author_id": 2749766,
"author_profile": "https://Stackoverflow.com/users/2749766",
"pm_score": 4,
"selected": false,
"text": "<p>you can try this.I think it will work correctly.</p>\n\n<pre><code>long delta = new Date().getTime() - date.getTime();\nconst int SECOND = 1;\nconst int MINUTE = 60 * SECOND;\nconst int HOUR = 60 * MINUTE;\nconst int DAY = 24 * HOUR;\nconst int MONTH = 30 * DAY;\n\nif (delta < 0L)\n{\n return \"not yet\";\n}\nif (delta < 1L * MINUTE)\n{\n return ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\";\n}\nif (delta < 2L * MINUTE)\n{\n return \"a minute ago\";\n}\nif (delta < 45L * MINUTE)\n{\n return ts.Minutes + \" minutes ago\";\n}\nif (delta < 90L * MINUTE)\n{\n return \"an hour ago\";\n}\nif (delta < 24L * HOUR)\n{\n return ts.Hours + \" hours ago\";\n}\nif (delta < 48L * HOUR)\n{\n return \"yesterday\";\n}\nif (delta < 30L * DAY)\n{\n return ts.Days + \" days ago\";\n}\nif (delta < 12L * MONTH)\n{\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n}\nelse\n{\n int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n return years <= 1 ? \"one year ago\" : years + \" years ago\";\n}\n</code></pre>\n"
},
{
"answer_id": 22961626,
"author": "Karl-Henrik",
"author_id": 1770846,
"author_profile": "https://Stackoverflow.com/users/1770846",
"pm_score": 6,
"selected": false,
"text": "<p>There are also a package called <a href=\"https://github.com/Humanizr/Humanizer\" rel=\"noreferrer\">Humanizr</a> on Nuget, and it actually works really well, and is in the .NET Foundation.</p>\n\n<pre><code>DateTime.UtcNow.AddHours(-30).Humanize() => \"yesterday\"\nDateTime.UtcNow.AddHours(-2).Humanize() => \"2 hours ago\"\n\nDateTime.UtcNow.AddHours(30).Humanize() => \"tomorrow\"\nDateTime.UtcNow.AddHours(2).Humanize() => \"2 hours from now\"\n\nTimeSpan.FromMilliseconds(1299630020).Humanize() => \"2 weeks\"\nTimeSpan.FromMilliseconds(1299630020).Humanize(3) => \"2 weeks, 1 day, 1 hour\"\n</code></pre>\n\n<p>Scott Hanselman has a writeup on it on his <a href=\"http://www.hanselman.com/blog/NuGetPackageOfTheWeekHumanizerMakesNETDataTypesMoreHuman.aspx\" rel=\"noreferrer\">blog</a></p>\n"
},
{
"answer_id": 25677278,
"author": "Wai Ho Leung",
"author_id": 1418148,
"author_profile": "https://Stackoverflow.com/users/1418148",
"pm_score": 2,
"selected": false,
"text": "<pre class=\"lang-java prettyprint-override\"><code>/** \n * {@code date1} has to be earlier than {@code date2}.\n */\npublic static String relativize(Date date1, Date date2) {\n assert date2.getTime() >= date1.getTime();\n\n long duration = date2.getTime() - date1.getTime();\n long converted;\n\n if ((converted = TimeUnit.MILLISECONDS.toDays(duration)) > 0) {\n return String.format(\"%d %s ago\", converted, converted == 1 ? \"day\" : \"days\");\n } else if ((converted = TimeUnit.MILLISECONDS.toHours(duration)) > 0) {\n return String.format(\"%d %s ago\", converted, converted == 1 ? \"hour\" : \"hours\");\n } else if ((converted = TimeUnit.MILLISECONDS.toMinutes(duration)) > 0) {\n return String.format(\"%d %s ago\", converted, converted == 1 ? \"minute\" : \"minutes\");\n } else if ((converted = TimeUnit.MILLISECONDS.toSeconds(duration)) > 0) {\n return String.format(\"%d %s ago\", converted, converted == 1 ? \"second\" : \"seconds\");\n } else {\n return \"just now\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 32459883,
"author": "Bgl86",
"author_id": 5293002,
"author_profile": "https://Stackoverflow.com/users/5293002",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to have an output like <code>\"2 days, 4 hours and 12 minutes ago\"</code>, you need a timespan:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>TimeSpan timeDiff = DateTime.Now-CreatedDate;\n</code></pre>\n\n<p>Then you can access the values you like:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>timeDiff.Days\ntimeDiff.Hours\n</code></pre>\n\n<p>etc...</p>\n"
},
{
"answer_id": 32459892,
"author": "Piotr Stapp",
"author_id": 1749895,
"author_profile": "https://Stackoverflow.com/users/1749895",
"pm_score": 4,
"selected": false,
"text": "<p>You can use <a href=\"http://dotnetthoughts.net/time-ago-function-for-c/\" rel=\"noreferrer\">TimeAgo extension</a> as below:</p>\n<pre><code>public static string TimeAgo(this DateTime dateTime)\n{\n string result = string.Empty;\n var timeSpan = DateTime.Now.Subtract(dateTime);\n \n if (timeSpan <= TimeSpan.FromSeconds(60))\n {\n result = string.Format("{0} seconds ago", timeSpan.Seconds);\n }\n else if (timeSpan <= TimeSpan.FromMinutes(60))\n {\n result = timeSpan.Minutes > 1 ? \n String.Format("about {0} minutes ago", timeSpan.Minutes) :\n "about a minute ago";\n }\n else if (timeSpan <= TimeSpan.FromHours(24))\n {\n result = timeSpan.Hours > 1 ? \n String.Format("about {0} hours ago", timeSpan.Hours) : \n "about an hour ago";\n }\n else if (timeSpan <= TimeSpan.FromDays(30))\n {\n result = timeSpan.Days > 1 ? \n String.Format("about {0} days ago", timeSpan.Days) : \n "yesterday";\n }\n else if (timeSpan <= TimeSpan.FromDays(365))\n {\n result = timeSpan.Days > 30 ? \n String.Format("about {0} months ago", timeSpan.Days / 30) : \n "about a month ago";\n }\n else\n {\n result = timeSpan.Days > 365 ? \n String.Format("about {0} years ago", timeSpan.Days / 365) : \n "about a year ago";\n }\n \n return result;\n}\n</code></pre>\n<p>Or use <a href=\"http://ardalis.com/wiring-up-timeago-and-aspnet-mvc\" rel=\"noreferrer\">jQuery plugin</a> with Razor extension from Timeago.</p>\n"
},
{
"answer_id": 46029235,
"author": "VnDevil",
"author_id": 1326699,
"author_profile": "https://Stackoverflow.com/users/1326699",
"pm_score": 1,
"selected": false,
"text": "<p>This is my function, works like a charm :)</p>\n<pre><code>public static string RelativeDate(DateTime theDate)\n{\n var span = DateTime.Now - theDate;\n if (span.Days > 365)\n {\n var years = (span.Days / 365);\n if (span.Days % 365 != 0)\n years += 1;\n return $"about {years} {(years == 1 ? "year" : "years")} ago";\n }\n if (span.Days > 30)\n {\n var months = (span.Days / 30);\n if (span.Days % 31 != 0)\n months += 1;\n return $"about {months} {(months == 1 ? "month" : "months")} ago";\n }\n if (span.Days > 0)\n return $"about {span.Days} {(span.Days == 1 ? "day" : "days")} ago";\n if (span.Hours > 0)\n return $"about {span.Hours} {(span.Hours == 1 ? "hour" : "hours")} ago";\n if (span.Minutes > 0)\n return $"about {span.Minutes} {(span.Minutes == 1 ? "minute" : "minutes")} ago";\n if (span.Seconds > 5)\n return $"about {span.Seconds} seconds ago";\n\n return span.Seconds <= 5 ? "about 5 seconds ago" : string.Empty;\n}\n</code></pre>\n"
},
{
"answer_id": 49300196,
"author": "Beingnin",
"author_id": 7441056,
"author_profile": "https://Stackoverflow.com/users/7441056",
"pm_score": -1,
"selected": false,
"text": "<p>My way is much more simpler. You can tweak with the return strings as you want</p>\n\n<pre><code> public static string TimeLeft(DateTime utcDate)\n {\n TimeSpan timeLeft = DateTime.UtcNow - utcDate;\n string timeLeftString = \"\";\n if (timeLeft.Days > 0)\n {\n timeLeftString += timeLeft.Days == 1 ? timeLeft.Days + \" day\" : timeLeft.Days + \" days\";\n }\n else if (timeLeft.Hours > 0)\n {\n timeLeftString += timeLeft.Hours == 1 ? timeLeft.Hours + \" hour\" : timeLeft.Hours + \" hours\";\n }\n else\n {\n timeLeftString += timeLeft.Minutes == 1 ? timeLeft.Minutes+\" minute\" : timeLeft.Minutes + \" minutes\";\n }\n return timeLeftString;\n }\n</code></pre>\n"
},
{
"answer_id": 54018412,
"author": "boyukbas",
"author_id": 1051784,
"author_profile": "https://Stackoverflow.com/users/1051784",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Turkish</strong> localized version of Vincents answer.</p>\n\n<pre><code> const int SECOND = 1;\n const int MINUTE = 60 * SECOND;\n const int HOUR = 60 * MINUTE;\n const int DAY = 24 * HOUR;\n const int MONTH = 30 * DAY;\n\n var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);\n double delta = Math.Abs(ts.TotalSeconds);\n\n if (delta < 1 * MINUTE)\n return ts.Seconds + \" saniye önce\";\n\n if (delta < 45 * MINUTE)\n return ts.Minutes + \" dakika önce\";\n\n if (delta < 24 * HOUR)\n return ts.Hours + \" saat önce\";\n\n if (delta < 48 * HOUR)\n return \"dün\";\n\n if (delta < 30 * DAY)\n return ts.Days + \" gün önce\";\n\n if (delta < 12 * MONTH)\n {\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return months + \" ay önce\";\n }\n else\n {\n int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n return years + \" yıl önce\";\n }\n</code></pre>\n"
},
{
"answer_id": 56310196,
"author": "Ahmed Osama",
"author_id": 5514131,
"author_profile": "https://Stackoverflow.com/users/5514131",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// Calculate total days in current year\nint daysInYear;\n\nfor (var i = 1; i <= 12; i++)\n daysInYear += DateTime.DaysInMonth(DateTime.Now.Year, i);\n\n// Past date\nDateTime dateToCompare = DateTime.Now.Subtract(TimeSpan.FromMinutes(582));\n\n// Calculate difference between current date and past date\ndouble diff = (DateTime.Now - dateToCompare).TotalMilliseconds;\n\nTimeSpan ts = TimeSpan.FromMilliseconds(diff);\n\nvar years = ts.TotalDays / daysInYear; // Years\nvar months = ts.TotalDays / (daysInYear / (double)12); // Months\nvar weeks = ts.TotalDays / 7; // Weeks\nvar days = ts.TotalDays; // Days\nvar hours = ts.TotalHours; // Hours\nvar minutes = ts.TotalMinutes; // Minutes\nvar seconds = ts.TotalSeconds; // Seconds\n\nif (years >= 1)\n Console.WriteLine(Math.Round(years, 0) + \" year(s) ago\");\nelse if (months >= 1)\n Console.WriteLine(Math.Round(months, 0) + \" month(s) ago\");\nelse if (weeks >= 1)\n Console.WriteLine(Math.Round(weeks, 0) + \" week(s) ago\");\nelse if (days >= 1)\n Console.WriteLine(Math.Round(days, 0) + \" days(s) ago\");\nelse if (hours >= 1)\n Console.WriteLine(Math.Round(hours, 0) + \" hour(s) ago\");\nelse if (minutes >= 1)\n Console.WriteLine(Math.Round(minutes, 0) + \" minute(s) ago\");\nelse if (seconds >= 1)\n Console.WriteLine(Math.Round(seconds, 0) + \" second(s) ago\");\n\nConsole.ReadLine();\n</code></pre>\n"
},
{
"answer_id": 64329743,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In a way you do your <code>DateTime</code> function over calculating relative time by either seconds to years, try something like this:</p>\n<pre><code>using System;\n\npublic class Program {\n public static string getRelativeTime(DateTime past) {\n DateTime now = DateTime.Today;\n string rt = "";\n int time;\n string statement = "";\n if (past.Second >= now.Second) {\n if (past.Second - now.Second == 1) {\n rt = "second ago";\n }\n rt = "seconds ago";\n time = past.Second - now.Second;\n statement = "" + time;\n return (statement + rt);\n }\n if (past.Minute >= now.Minute) {\n if (past.Second - now.Second == 1) {\n rt = "second ago";\n } else {\n rt = "minutes ago";\n }\n time = past.Minute - now.Minute;\n statement = "" + time;\n return (statement + rt);\n }\n // This process will go on until years\n }\n public static void Main() {\n DateTime before = new DateTime(1995, 8, 24);\n string date = getRelativeTime(before);\n Console.WriteLine("Windows 95 was {0}.", date);\n }\n}\n</code></pre>\n<p>Not exactly working but if you modify and debug it a bit, it will likely do the job.</p>\n"
},
{
"answer_id": 65238004,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>A "one-liner" using deconstruction and Linq to get "n [biggest unit of time] ago" :</p>\n<pre><code>TimeSpan timeSpan = DateTime.Now - new DateTime(1234, 5, 6, 7, 8, 9);\n\n(string unit, int value) = new Dictionary<string, int>\n{\n {"year(s)", (int)(timeSpan.TotalDays / 365.25)}, //https://en.wikipedia.org/wiki/Year#Intercalation\n {"month(s)", (int)(timeSpan.TotalDays / 29.53)}, //https://en.wikipedia.org/wiki/Month\n {"day(s)", (int)timeSpan.TotalDays},\n {"hour(s)", (int)timeSpan.TotalHours},\n {"minute(s)", (int)timeSpan.TotalMinutes},\n {"second(s)", (int)timeSpan.TotalSeconds},\n {"millisecond(s)", (int)timeSpan.TotalMilliseconds}\n}.First(kvp => kvp.Value > 0);\n\nConsole.WriteLine($"{value} {unit} ago");\n</code></pre>\n<p>You get <code>786 year(s) ago</code></p>\n<p>With the current year and month, like</p>\n<pre><code>TimeSpan timeSpan = DateTime.Now - new DateTime(2020, 12, 6, 7, 8, 9);\n</code></pre>\n<p>you get <code>4 day(s) ago</code></p>\n<p>With the actual date, like</p>\n<pre><code>TimeSpan timeSpan = DateTime.Now - DateTime.Now.Date;\n</code></pre>\n<p>you get <code>9 hour(s) ago</code></p>\n"
},
{
"answer_id": 69020909,
"author": "Shujat Munawar",
"author_id": 7849868,
"author_profile": "https://Stackoverflow.com/users/7849868",
"pm_score": -1,
"selected": false,
"text": "<p>Simple and 100% working solution.</p>\n<p>Handling ago and future times as well.. just in case</p>\n<pre><code> public string GetTimeSince(DateTime postDate)\n {\n string message = "";\n DateTime currentDate = DateTime.Now;\n TimeSpan timegap = currentDate - postDate;\n\n \n if (timegap.Days > 365)\n {\n message = string.Format(L("Ago") + " {0} " + L("Years"), (((timegap.Days) / 30) / 12)); \n }\n else if (timegap.Days > 30)\n {\n message = string.Format(L("Ago") + " {0} " + L("Months"), timegap.Days/30); \n }\n else if (timegap.Days > 0)\n {\n message = string.Format(L("Ago") + " {0} " + L("Days"), timegap.Days);\n } \n else if (timegap.Hours > 0)\n {\n message = string.Format(L("Ago") + " {0} " + L("Hours"), timegap.Hours);\n } \n else if (timegap.Minutes > 0)\n {\n message = string.Format(L("Ago") + " {0} " + L("Minutes"), timegap.Minutes);\n }\n else if (timegap.Seconds > 0)\n {\n message = string.Format(L("Ago") + " {0} " + L("Seconds"), timegap.Seconds);\n }\n\n // let's handle future times..just in case \n else if (timegap.Days < -365)\n {\n message = string.Format(L("In") + " {0} " + L("Years"), (((Math.Abs(timegap.Days)) / 30) / 12)); \n }\n else if (timegap.Days < -30)\n {\n message = string.Format(L("In") + " {0} " + L("Months"), ((Math.Abs(timegap.Days)) / 30)); \n }\n else if (timegap.Days < 0)\n {\n message = string.Format(L("In") + " {0} " + L("Days"), Math.Abs(timegap.Days)); \n } \n \n else if (timegap.Hours < 0)\n {\n message = string.Format(L("In") + " {0} " + L("Hours"), Math.Abs(timegap.Hours)); \n }\n else if (timegap.Minutes < 0)\n {\n message = string.Format(L("In") + " {0} " + L("Minutes"), Math.Abs(timegap.Minutes)); \n }\n else if (timegap.Seconds < 0)\n {\n message = string.Format(L("In") + " {0} " + L("Seconds"), Math.Abs(timegap.Seconds)); \n }\n\n\n else\n {\n message = "a bit";\n }\n\n return message;\n }\n</code></pre>\n"
},
{
"answer_id": 73608368,
"author": "StudioLE",
"author_id": 247218,
"author_profile": "https://Stackoverflow.com/users/247218",
"pm_score": 0,
"selected": false,
"text": "<p>The accepted answer by Vincent makes quite a few arbitrary decisions.\nWhy is 45 minutes rounded up to an hour while 45 seconds is not rounded up to a minute?\nIt has an increased level of cyclomatic complexity within the years and month calculations that makes it more complex to follow the logic.\nIt makes the assumption that the TimeSpan is relative to the past (2 days ago) when it could very well be in the future (2 days until).\nIt defines unnecessary constants instead of using <code>TimeSpan.TicksPerSecond</code> etc.</p>\n<p>This implementation resolves the above and updates the syntax to use <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression\" rel=\"nofollow noreferrer\">switch expressions</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns#relational-patterns\" rel=\"nofollow noreferrer\">relational patterns</a></p>\n<pre class=\"lang-cs prettyprint-override\"><code>/// <summary>\n/// Convert a <see cref="TimeSpan"/> to a natural language representation.\n/// </summary>\n/// <example>\n/// <code>\n/// TimeSpan.FromSeconds(10).ToNaturalLanguage();\n/// // 10 seconds\n/// </code>\n/// </example>\npublic static string ToNaturalLanguage(this TimeSpan @this)\n{\n const int daysInWeek = 7;\n const int daysInMonth = 30;\n const int daysInYear = 365;\n const long threshold = 100 * TimeSpan.TicksPerMillisecond;\n @this = @this.TotalSeconds < 0\n ? TimeSpan.FromSeconds(@this.TotalSeconds * -1)\n : @this;\n return (@this.Ticks + threshold) switch\n {\n < 2 * TimeSpan.TicksPerSecond => "a second",\n < 1 * TimeSpan.TicksPerMinute => @this.Seconds + " seconds",\n < 2 * TimeSpan.TicksPerMinute => "a minute",\n < 1 * TimeSpan.TicksPerHour => @this.Minutes + " minutes",\n < 2 * TimeSpan.TicksPerHour => "an hour",\n < 1 * TimeSpan.TicksPerDay => @this.Hours + " hours",\n < 2 * TimeSpan.TicksPerDay => "a day",\n < 1 * daysInWeek * TimeSpan.TicksPerDay => @this.Days + " days",\n < 2 * daysInWeek * TimeSpan.TicksPerDay => "a week",\n < 1 * daysInMonth * TimeSpan.TicksPerDay => (@this.Days / daysInWeek).ToString("F0") + " weeks",\n < 2 * daysInMonth * TimeSpan.TicksPerDay => "a month",\n < 1 * daysInYear * TimeSpan.TicksPerDay => (@this.Days / daysInMonth).ToString("F0") + " months",\n < 2 * daysInYear * TimeSpan.TicksPerDay => "a year",\n _ => (@this.Days / daysInYear).ToString("F0") + " years"\n };\n}\n\n/// <summary>\n/// Convert a <see cref="DateTime"/> to a natural language representation.\n/// </summary>\n/// <example>\n/// <code>\n/// (DateTime.Now - TimeSpan.FromSeconds(10)).ToNaturalLanguage()\n/// // 10 seconds ago\n/// </code>\n/// </example>\npublic static string ToNaturalLanguage(this DateTime @this)\n{\n TimeSpan timeSpan = @this - DateTime.Now;\n return timeSpan.TotalSeconds switch\n {\n >= 1 => timeSpan.ToNaturalLanguage() + " until",\n <= -1 => timeSpan.ToNaturalLanguage() + " ago",\n _ => "now",\n };\n}\n</code></pre>\n<p>You can test it with NUnit as follows:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>[TestCase("a second", 0)]\n[TestCase("a second", 1)]\n[TestCase("2 seconds", 2)]\n[TestCase("a minute", 0, 1)]\n[TestCase("5 minutes", 0, 5)]\n[TestCase("an hour", 0, 0, 1)]\n[TestCase("2 hours", 0, 0, 2)]\n[TestCase("a day", 0, 0, 24)]\n[TestCase("a day", 0, 0, 0, 1)]\n[TestCase("6 days", 0, 0, 0, 6)]\n[TestCase("a week", 0, 0, 0, 7)]\n[TestCase("4 weeks", 0, 0, 0, 29)]\n[TestCase("a month", 0, 0, 0, 30)]\n[TestCase("6 months", 0, 0, 0, 6 * 30)]\n[TestCase("a year", 0, 0, 0, 365)]\n[TestCase("68 years", int.MaxValue)]\npublic void NaturalLanguageHelpers_TimeSpan(\n string expected,\n int seconds,\n int minutes = 0,\n int hours = 0,\n int days = 0\n)\n{\n // Arrange\n TimeSpan timeSpan = new(days, hours, minutes, seconds);\n\n // Act\n string result = timeSpan.ToNaturalLanguage();\n\n // Assert\n Assert.That(result, Is.EqualTo(expected));\n}\n\n[TestCase("now", 0)]\n[TestCase("10 minutes ago", 0, -10)]\n[TestCase("10 minutes until", 10, 10)]\n[TestCase("68 years until", int.MaxValue)]\n[TestCase("68 years ago", int.MinValue)]\npublic void NaturalLanguageHelpers_DateTime(\n string expected,\n int seconds,\n int minutes = 0,\n int hours = 0,\n int days = 0\n)\n{\n // Arrange\n TimeSpan timeSpan = new(days, hours, minutes, seconds);\n DateTime now = DateTime.Now;\n DateTime dateTime = now + timeSpan;\n\n // Act\n string result = dateTime.ToNaturalLanguage();\n\n // Assert\n Assert.That(result, Is.EqualTo(expected));\n}\n</code></pre>\n<p>Or as a gist: <a href=\"https://gist.github.com/StudioLE/2dd394e3f792e79adc927ede274df56e\" rel=\"nofollow noreferrer\">https://gist.github.com/StudioLE/2dd394e3f792e79adc927ede274df56e</a></p>\n"
}
] | 2008/07/31 | [
"https://Stackoverflow.com/questions/11",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
] | Given a specific `DateTime` value, how do I display relative time, like:
* `2 hours ago`
* `3 days ago`
* `a month ago` | Jeff, [your code](https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/12#12) is nice but could be clearer with constants (as suggested in Code Complete).
```csharp
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 1 * MINUTE)
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
if (delta < 2 * MINUTE)
return "a minute ago";
if (delta < 45 * MINUTE)
return ts.Minutes + " minutes ago";
if (delta < 90 * MINUTE)
return "an hour ago";
if (delta < 24 * HOUR)
return ts.Hours + " hours ago";
if (delta < 48 * HOUR)
return "yesterday";
if (delta < 30 * DAY)
return ts.Days + " days ago";
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
}
``` |
16 | <p>How do you expose a LINQ query as an ASMX web service?
<br>
Usually, from the business tier, I can return a typed <code>DataSet</code> or a <code>DataTable</code> which can be serialized for transport over ASMX.</p>
<p>How can I do the same for a LINQ query? <br>
Is there a way to populate a typed <code>DataSet</code> or a <code>DataTable</code> via a LINQ query?</p>
<pre><code>public static MyDataTable CallMySproc()
{
string conn = "...";
MyDatabaseDataContext db = new MyDatabaseDataContext(conn);
MyDataTable dt = new MyDataTable();
// execute a sproc via LINQ
var query = from dr
in db.MySproc().AsEnumerable
select dr;
// copy LINQ query resultset into a DataTable -this does not work !
dt = query.CopyToDataTable();
return dt;
}
</code></pre>
<p>How could I put the result set of a LINQ query into a <code>DataSet</code> or a <code>DataTable</code>?
<br>
Alternatively, can the LINQ query be serializable so that I can expose it as an ASMX web service?</p>
| [
{
"answer_id": 84,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 4,
"selected": false,
"text": "<p>If you use a return type of <code>IEnumerable</code>, you can return your <strong>query</strong> variable directly.</p>\n"
},
{
"answer_id": 5830,
"author": "Brian Childress",
"author_id": 721,
"author_profile": "https://Stackoverflow.com/users/721",
"pm_score": 4,
"selected": false,
"text": "<p>Create a class object and return a <code>list(T)</code> of the query.</p>\n"
},
{
"answer_id": 12446,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 8,
"selected": true,
"text": "<p>As mentioned in the question, <code>IEnumerable</code> has a <code>CopyToDataTable</code> method:</p>\n\n<pre><code>IEnumerable<DataRow> query =\n from order in orders.AsEnumerable()\n where order.Field<DateTime>(\"OrderDate\") > new DateTime(2001, 8, 1)\n select order;\n\n// Create a table from the query.\nDataTable boundTable = query.CopyToDataTable<DataRow>();\n</code></pre>\n\n<p>Why won't that work for you?</p>\n"
},
{
"answer_id": 12460,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 5,
"selected": false,
"text": "<p>Make a set of Data Transfer Objects, a couple of mappers, and return that via the .asmx.<br>\nYou should <em>never</em> expose the database objects directly, as a change in the procedure schema will propagate to the web service consumer without you noticing it.</p>\n"
},
{
"answer_id": 544169,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>To perform this query against a <code>DataContext</code> class, you'll need to do the following:</p>\n\n<pre><code>MyDataContext db = new MyDataContext();\nIEnumerable<DataRow> query = \n (from order in db.Orders.AsEnumerable()\n select new\n {\n order.Property,\n order.Property2\n })\n as IEnumerable<DataRow>;\nreturn query.CopyToDataTable<DataRow>();\n</code></pre>\n\n<p>Without the <code>as IEnumerable<DataRow>;</code> you will see the following compilation error:</p>\n\n<blockquote>\n <p>Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)</p>\n</blockquote>\n"
},
{
"answer_id": 49774484,
"author": "Vijay S",
"author_id": 7204125,
"author_profile": "https://Stackoverflow.com/users/7204125",
"pm_score": 3,
"selected": false,
"text": "<p>If you use <code>IEnumerable</code> as the return type, it will return your query variable directly.</p>\n<pre><code>MyDataContext db = new MyDataContext();\nIEnumerable<DataRow> query = \n (from order in db.Orders.AsEnumerable()\n select new\n {\n order.Property,\n order.Property2\n })\n as IEnumerable<DataRow>;\nreturn query.CopyToDataTable<DataRow>();\n</code></pre>\n"
},
{
"answer_id": 56693278,
"author": "Gabriel Magana",
"author_id": 99455,
"author_profile": "https://Stackoverflow.com/users/99455",
"pm_score": 2,
"selected": false,
"text": "<p>For the sake of completeness, these solutions do not work for EF Core (at least not for EF Core 2.2). Casting to <code>IEnumerable<DataRow></code>, as suggested in the other answers here, fails. Implementing this class and extension methods worked for me <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/implement-copytodatatable-where-type-not-a-datarow\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/implement-copytodatatable-where-type-not-a-datarow</a>.</p>\n\n<p>Why it's not built into EF Core, I have not idea.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/16",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2/"
] | How do you expose a LINQ query as an ASMX web service?
Usually, from the business tier, I can return a typed `DataSet` or a `DataTable` which can be serialized for transport over ASMX.
How can I do the same for a LINQ query?
Is there a way to populate a typed `DataSet` or a `DataTable` via a LINQ query?
```
public static MyDataTable CallMySproc()
{
string conn = "...";
MyDatabaseDataContext db = new MyDatabaseDataContext(conn);
MyDataTable dt = new MyDataTable();
// execute a sproc via LINQ
var query = from dr
in db.MySproc().AsEnumerable
select dr;
// copy LINQ query resultset into a DataTable -this does not work !
dt = query.CopyToDataTable();
return dt;
}
```
How could I put the result set of a LINQ query into a `DataSet` or a `DataTable`?
Alternatively, can the LINQ query be serializable so that I can expose it as an ASMX web service? | As mentioned in the question, `IEnumerable` has a `CopyToDataTable` method:
```
IEnumerable<DataRow> query =
from order in orders.AsEnumerable()
where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
select order;
// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();
```
Why won't that work for you? |
19 | <p>I'm looking for the fastest way to obtain the value of π, as a personal challenge. More specifically, I'm using ways that don't involve using <code>#define</code> constants like <code>M_PI</code>, or hard-coding the number in.</p>
<p>The program below tests the various ways I know of. The inline assembly version is, in theory, the fastest option, though clearly not portable. I've included it as a baseline to compare against the other versions. In my tests, with built-ins, the <code>4 * atan(1)</code> version is fastest on GCC 4.2, because it auto-folds the <code>atan(1)</code> into a constant. With <code>-fno-builtin</code> specified, the <code>atan2(0, -1)</code> version is fastest.</p>
<p>Here's the main testing program (<code>pitimes.c</code>):</p>
<pre class="lang-c prettyprint-override"><code>#include <math.h>
#include <stdio.h>
#include <time.h>
#define ITERS 10000000
#define TESTWITH(x) { \
diff = 0.0; \
time1 = clock(); \
for (i = 0; i < ITERS; ++i) \
diff += (x) - M_PI; \
time2 = clock(); \
printf("%s\t=> %e, time => %f\n", #x, diff, diffclock(time2, time1)); \
}
static inline double
diffclock(clock_t time1, clock_t time0)
{
return (double) (time1 - time0) / CLOCKS_PER_SEC;
}
int
main()
{
int i;
clock_t time1, time2;
double diff;
/* Warmup. The atan2 case catches GCC's atan folding (which would
* optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin
* is not used. */
TESTWITH(4 * atan(1))
TESTWITH(4 * atan2(1, 1))
#if defined(__GNUC__) && (defined(__i386__) || defined(__amd64__))
extern double fldpi();
TESTWITH(fldpi())
#endif
/* Actual tests start here. */
TESTWITH(atan2(0, -1))
TESTWITH(acos(-1))
TESTWITH(2 * asin(1))
TESTWITH(4 * atan2(1, 1))
TESTWITH(4 * atan(1))
return 0;
}
</code></pre>
<p>And the inline assembly stuff (<code>fldpi.c</code>) that will only work for x86 and x64 systems:</p>
<pre class="lang-c prettyprint-override"><code>double
fldpi()
{
double pi;
asm("fldpi" : "=t" (pi));
return pi;
}
</code></pre>
<p>And a build script that builds all the configurations I'm testing (<code>build.sh</code>):</p>
<pre><code>#!/bin/sh
gcc -O3 -Wall -c -m32 -o fldpi-32.o fldpi.c
gcc -O3 -Wall -c -m64 -o fldpi-64.o fldpi.c
gcc -O3 -Wall -ffast-math -m32 -o pitimes1-32 pitimes.c fldpi-32.o
gcc -O3 -Wall -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -ffast-math -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm
</code></pre>
<p>Apart from testing between various compiler flags (I've compared 32-bit against 64-bit too because the optimizations are different), I've also tried switching the order of the tests around. But still, the <code>atan2(0, -1)</code> version still comes out on top every time.</p>
| [
{
"answer_id": 71,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 6,
"selected": false,
"text": "<p>Here's a general description of a technique for calculating pi that I learnt in high school.</p>\n\n<p>I only share this because I think it is simple enough that anyone can remember it, indefinitely, plus it teaches you the concept of \"Monte-Carlo\" methods -- which are statistical methods of arriving at answers that don't immediately appear to be deducible through random processes.</p>\n\n<p>Draw a square, and inscribe a quadrant (one quarter of a semi-circle) inside that square (a quadrant with radius equal to the side of the square, so it fills as much of the square as possible)</p>\n\n<p>Now throw a dart at the square, and record where it lands -- that is, choose a random point anywhere inside the square. Of course, it landed inside the square, but is it inside the semi-circle? Record this fact.</p>\n\n<p>Repeat this process many times -- and you will find there is a ratio of the number of points inside the semi-circle versus the total number thrown, call this ratio x.</p>\n\n<p>Since the area of the square is r times r, you can deduce that the area of the semi circle is x times r times r (that is, x times r squared). Hence x times 4 will give you pi. </p>\n\n<p>This is not a quick method to use. But it's a nice example of a Monte Carlo method. And if you look around, you may find that many problems otherwise outside your computational skills can be solved by such methods.</p>\n"
},
{
"answer_id": 531,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 9,
"selected": true,
"text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Monte_Carlo_method\" rel=\"noreferrer\">Monte Carlo method</a>, as mentioned, applies some great concepts but it is, clearly, not the fastest, not by a long shot, not by any reasonable measure. Also, it all depends on what kind of accuracy you are looking for. The fastest π I know of is the one with the digits hard coded. Looking at <a href=\"http://functions.wolfram.com/Constants/Pi/\" rel=\"noreferrer\" title=\"pi\">Pi</a> and <a href=\"http://functions.wolfram.com/PDF/Pi.pdf\" rel=\"noreferrer\" title=\"pi formulas\">Pi[PDF]</a>, there are a lot of formulae.</p>\n\n<p>Here is a method that converges quickly — about 14 digits per iteration. <a href=\"http://numbers.computation.free.fr/Constants/PiProgram/pifast.html\" rel=\"noreferrer\" title=\"PiFast\">PiFast</a>, the current fastest application, uses this formula with the FFT. I'll just write the formula, since the code is straightforward. This formula was almost found by <a href=\"http://numbers.computation.free.fr/Constants/Pi/piramanujan.html\" rel=\"noreferrer\">Ramanujan and discovered by Chudnovsky</a>. It is actually how he calculated several billion digits of the number — so it isn't a method to disregard. The formula will overflow quickly and, since we are dividing factorials, it would be advantageous then to delay such calculations to remove terms.</p>\n\n<p><img src=\"https://i.stack.imgur.com/aQMkk.gif\" alt=\"enter image description here\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/2y2l9.gif\" alt=\"enter image description here\"></p>\n\n<p>where,</p>\n\n<p><img src=\"https://i.stack.imgur.com/QqVnB.gif\" alt=\"enter image description here\"></p>\n\n<p>Below is the <a href=\"http://mathworld.wolfram.com/Brent-SalaminFormula.html\" rel=\"noreferrer\" title=\"Brent Salamin Formula\">Brent–Salamin algorithm</a>. Wikipedia mentions that when <strong>a</strong> and <strong>b</strong> are \"close enough\" then <strong>(a + b)² / 4t</strong> will be an approximation of π. I'm not sure what \"close enough\" means, but from my tests, one iteration got 2 digits, two got 7, and three had 15, of course this is with doubles, so it might have an error based on its representation and the <em>true</em> calculation could be more accurate.</p>\n\n<pre><code>let pi_2 iters =\n let rec loop_ a b t p i =\n if i = 0 then a,b,t,p\n else\n let a_n = (a +. b) /. 2.0 \n and b_n = sqrt (a*.b)\n and p_n = 2.0 *. p in\n let t_n = t -. (p *. (a -. a_n) *. (a -. a_n)) in\n loop_ a_n b_n t_n p_n (i - 1)\n in \n let a,b,t,p = loop_ (1.0) (1.0 /. (sqrt 2.0)) (1.0/.4.0) (1.0) iters in\n (a +. b) *. (a +. b) /. (4.0 *. t)\n</code></pre>\n\n<p>Lastly, how about some pi golf (800 digits)? 160 characters!</p>\n\n<pre><code>int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5;for(;d=0,g=c*2;c-=14,printf(\"%.4d\",e+d/a),e=d%a)for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);}\n</code></pre>\n"
},
{
"answer_id": 4089,
"author": "Michiel de Mare",
"author_id": 136,
"author_profile": "https://Stackoverflow.com/users/136",
"pm_score": 4,
"selected": false,
"text": "<p>If by fastest you mean fastest to type in the code, here's the <a href=\"http://www.golfscript.com/golfscript/examples.html\" rel=\"noreferrer\">golfscript</a> solution:</p>\n\n<pre><code>;''6666,-2%{2+.2/@*\\/10.3??2*+}*`1000<~\\;\n</code></pre>\n"
},
{
"answer_id": 25197,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 5,
"selected": false,
"text": "<p>There's actually a whole book dedicated (amongst other things) to <em>fast</em> methods for the computation of \\pi: 'Pi and the AGM', by Jonathan and Peter Borwein (<a href=\"https://rads.stackoverflow.com/amzn/click/com/047131515X\" rel=\"noreferrer\" rel=\"nofollow noreferrer\" title=\"available on Amazon\">available on Amazon</a>).</p>\n\n<p>I studied the AGM and related algorithms quite a bit: it's quite interesting (though sometimes non-trivial).</p>\n\n<p>Note that to implement most modern algorithms to compute \\pi, you will need a multiprecision arithmetic library (<a href=\"http://gmplib.org/\" rel=\"noreferrer\">GMP</a> is quite a good choice, though it's been a while since I last used it).</p>\n\n<p>The time-complexity of the best algorithms is in O(M(n)log(n)), where M(n) is the time-complexity for the multiplication of two n-bit integers (M(n)=O(n log(n) log(log(n))) using FFT-based algorithms, which are usually needed when computing digits of \\pi, and such an algorithm is implemented in GMP).</p>\n\n<p>Note that even though the mathematics behind the algorithms might not be trivial, the algorithms themselves are usually a few lines of pseudo-code, and their implementation is usually very straightforward (if you chose not to write your own multiprecision arithmetic :-) ). </p>\n"
},
{
"answer_id": 34239,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Bailey-Borwein-Plouffe_formula\" rel=\"noreferrer\">BBP formula</a> allows you to compute the nth digit - in base 2 (or 16) - without having to even bother with the previous n-1 digits first :)</p>\n"
},
{
"answer_id": 39512,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 7,
"selected": false,
"text": "<p>I really like this program, because it approximates π by looking at its own area.</p>\n\n<p>IOCCC 1988 : <a href=\"http://www0.us.ioccc.org/1988/westley.c\" rel=\"noreferrer\">westley.c</a> </p>\n\n<blockquote>\n<pre><code>#define _ -F<00||--F-OO--;\nint F=00,OO=00;main(){F_OO();printf(\"%1.3f\\n\",4.*-F/OO/OO);}F_OO()\n{\n _-_-_-_\n _-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_\n _-_-_-_\n}\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 85798,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 4,
"selected": false,
"text": "<h2>Calculate PI at compile-time with D.</h2>\n\n<p>( Copied from <a href=\"http://www.dsource.org/projects/ddl/browser/trunk/meta/demo/calcpi.d\" rel=\"noreferrer\">DSource.org</a> )</p>\n\n<pre class=\"lang-d prettyprint-override\"><code>/** Calculate pi at compile time\n *\n * Compile with dmd -c pi.d\n */\nmodule calcpi;\n\nimport meta.math;\nimport meta.conv;\n\n/** real evaluateSeries!(real x, real metafunction!(real y, int n) term)\n *\n * Evaluate a power series at compile time.\n *\n * Given a metafunction of the form\n * real term!(real y, int n),\n * which gives the nth term of a convergent series at the point y\n * (where the first term is n==1), and a real number x,\n * this metafunction calculates the infinite sum at the point x\n * by adding terms until the sum doesn't change any more.\n */\ntemplate evaluateSeries(real x, alias term, int n=1, real sumsofar=0.0)\n{\n static if (n>1 && sumsofar == sumsofar + term!(x, n+1)) {\n const real evaluateSeries = sumsofar;\n } else {\n const real evaluateSeries = evaluateSeries!(x, term, n+1, sumsofar + term!(x, n));\n }\n}\n\n/*** Calculate atan(x) at compile time.\n *\n * Uses the Maclaurin formula\n * atan(z) = z - z^3/3 + Z^5/5 - Z^7/7 + ...\n */\ntemplate atan(real z)\n{\n const real atan = evaluateSeries!(z, atanTerm);\n}\n\ntemplate atanTerm(real x, int n)\n{\n const real atanTerm = (n & 1 ? 1 : -1) * pow!(x, 2*n-1)/(2*n-1);\n}\n\n/// Machin's formula for pi\n/// pi/4 = 4 atan(1/5) - atan(1/239).\npragma(msg, \"PI = \" ~ fcvt!(4.0 * (4*atan!(1/5.0) - atan!(1/239.0))) );\n</code></pre>\n"
},
{
"answer_id": 164687,
"author": "Andrea Ambu",
"author_id": 21384,
"author_profile": "https://Stackoverflow.com/users/21384",
"pm_score": 5,
"selected": false,
"text": "<p>This is a \"classic\" method, very easy to implement.\nThis implementation in python (not the fastest language) does it:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>from math import pi\nfrom time import time\n\n\nprecision = 10**6 # higher value -> higher precision\n # lower value -> higher speed\n\nt = time()\n\ncalc = 0\nfor k in xrange(0, precision):\n calc += ((-1)**k) / (2*k+1.)\ncalc *= 4. # this is just a little optimization\n\nt = time()-t\n\nprint \"Calculated: %.40f\" % calc\nprint \"Constant pi: %.40f\" % pi\nprint \"Difference: %.40f\" % abs(calc-pi)\nprint \"Time elapsed: %s\" % repr(t)\n</code></pre>\n\n<p>You can find more information <a href=\"http://functions.wolfram.com/Constants/Pi/02/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Anyway, the fastest way to get a precise as-much-as-you-want value of pi in python is:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>from gmpy import pi\nprint pi(3000) # the rule is the same as \n # the precision on the previous code\n</code></pre>\n\n<p>Here is the piece of source for the gmpy pi method, I don't think the code is as useful as the comment in this case:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>static char doc_pi[]=\"\\\npi(n): returns pi with n bits of precision in an mpf object\\n\\\n\";\n\n/* This function was originally from netlib, package bmp, by\n * Richard P. Brent. Paulo Cesar Pereira de Andrade converted\n * it to C and used it in his LISP interpreter.\n *\n * Original comments:\n * \n * sets mp pi = 3.14159... to the available precision.\n * uses the gauss-legendre algorithm.\n * this method requires time o(ln(t)m(t)), so it is slower\n * than mppi if m(t) = o(t**2), but would be faster for\n * large t if a faster multiplication algorithm were used\n * (see comments in mpmul).\n * for a description of the method, see - multiple-precision\n * zero-finding and the complexity of elementary function\n * evaluation (by r. p. brent), in analytic computational\n * complexity (edited by j. f. traub), academic press, 1976, 151-176.\n * rounding options not implemented, no guard digits used.\n*/\nstatic PyObject *\nPygmpy_pi(PyObject *self, PyObject *args)\n{\n PympfObject *pi;\n int precision;\n mpf_t r_i2, r_i3, r_i4;\n mpf_t ix;\n\n ONE_ARG(\"pi\", \"i\", &precision);\n if(!(pi = Pympf_new(precision))) {\n return NULL;\n }\n\n mpf_set_si(pi->f, 1);\n\n mpf_init(ix);\n mpf_set_ui(ix, 1);\n\n mpf_init2(r_i2, precision);\n\n mpf_init2(r_i3, precision);\n mpf_set_d(r_i3, 0.25);\n\n mpf_init2(r_i4, precision);\n mpf_set_d(r_i4, 0.5);\n mpf_sqrt(r_i4, r_i4);\n\n for (;;) {\n mpf_set(r_i2, pi->f);\n mpf_add(pi->f, pi->f, r_i4);\n mpf_div_ui(pi->f, pi->f, 2);\n mpf_mul(r_i4, r_i2, r_i4);\n mpf_sub(r_i2, pi->f, r_i2);\n mpf_mul(r_i2, r_i2, r_i2);\n mpf_mul(r_i2, r_i2, ix);\n mpf_sub(r_i3, r_i3, r_i2);\n mpf_sqrt(r_i4, r_i4);\n mpf_mul_ui(ix, ix, 2);\n /* Check for convergence */\n if (!(mpf_cmp_si(r_i2, 0) && \n mpf_get_prec(r_i2) >= (unsigned)precision)) {\n mpf_mul(pi->f, pi->f, r_i4);\n mpf_div(pi->f, pi->f, r_i3);\n break;\n }\n }\n\n mpf_clear(ix);\n mpf_clear(r_i2);\n mpf_clear(r_i3);\n mpf_clear(r_i4);\n\n return (PyObject*)pi;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT:</strong> I had some problems with cut and paste and indentation, you can find the source <a href=\"http://code.google.com/p/gmpy/source/browse/branches/aleax-sandbox/src/gmpy.c\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 436447,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 4,
"selected": false,
"text": "<p>This version (in Delphi) is nothing special, but it is at least faster than <a href=\"http://blogs.codegear.com/nickhodges/2009/01/09/39174\" rel=\"nofollow noreferrer\">the version Nick Hodge posted on his blog</a> :). On my machine, it takes about 16 seconds to do a billion iterations, giving a value of <strong>3.14159265</strong>25879 (the accurate part is in bold).</p>\n\n<pre class=\"lang-pascal prettyprint-override\"><code>program calcpi;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils;\n\nvar\n start, finish: TDateTime;\n\nfunction CalculatePi(iterations: integer): double;\nvar\n numerator, denominator, i: integer;\n sum: double;\nbegin\n {\n PI may be approximated with this formula:\n 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 .......)\n //}\n numerator := 1;\n denominator := 1;\n sum := 0;\n for i := 1 to iterations do begin\n sum := sum + (numerator/denominator);\n denominator := denominator + 2;\n numerator := -numerator;\n end;\n Result := 4 * sum;\nend;\n\nbegin\n try\n start := Now;\n WriteLn(FloatToStr(CalculatePi(StrToInt(ParamStr(1)))));\n finish := Now;\n WriteLn('Seconds:' + FormatDateTime('hh:mm:ss.zz',finish-start));\n except\n on E:Exception do\n Writeln(E.Classname, ': ', E.Message);\n end;\nend.\n</code></pre>\n"
},
{
"answer_id": 571276,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 4,
"selected": false,
"text": "<p>Back in the old days, with small word sizes and slow or non-existent floating-point operations, we used to do stuff like this:</p>\n\n<pre><code>/* Return approximation of n * PI; n is integer */\n#define pi_times(n) (((n) * 22) / 7)\n</code></pre>\n\n<p>For applications that don't require a lot of precision (video games, for example), this is very fast and is accurate enough.</p>\n"
},
{
"answer_id": 592025,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Pi is exactly 3! [Prof. Frink (Simpsons)]</p>\n\n<p>Joke, but here's one in C# (.NET-Framework required).</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Text;\n\nclass Program {\n static void Main(string[] args) {\n int Digits = 100;\n\n BigNumber x = new BigNumber(Digits);\n BigNumber y = new BigNumber(Digits);\n x.ArcTan(16, 5);\n y.ArcTan(4, 239);\n x.Subtract(y);\n string pi = x.ToString();\n Console.WriteLine(pi);\n }\n}\n\npublic class BigNumber {\n private UInt32[] number;\n private int size;\n private int maxDigits;\n\n public BigNumber(int maxDigits) {\n this.maxDigits = maxDigits;\n this.size = (int)Math.Ceiling((float)maxDigits * 0.104) + 2;\n number = new UInt32[size];\n }\n public BigNumber(int maxDigits, UInt32 intPart)\n : this(maxDigits) {\n number[0] = intPart;\n for (int i = 1; i < size; i++) {\n number[i] = 0;\n }\n }\n private void VerifySameSize(BigNumber value) {\n if (Object.ReferenceEquals(this, value))\n throw new Exception(\"BigNumbers cannot operate on themselves\");\n if (value.size != this.size)\n throw new Exception(\"BigNumbers must have the same size\");\n }\n\n public void Add(BigNumber value) {\n VerifySameSize(value);\n\n int index = size - 1;\n while (index >= 0 && value.number[index] == 0)\n index--;\n\n UInt32 carry = 0;\n while (index >= 0) {\n UInt64 result = (UInt64)number[index] +\n value.number[index] + carry;\n number[index] = (UInt32)result;\n if (result >= 0x100000000U)\n carry = 1;\n else\n carry = 0;\n index--;\n }\n }\n public void Subtract(BigNumber value) {\n VerifySameSize(value);\n\n int index = size - 1;\n while (index >= 0 && value.number[index] == 0)\n index--;\n\n UInt32 borrow = 0;\n while (index >= 0) {\n UInt64 result = 0x100000000U + (UInt64)number[index] -\n value.number[index] - borrow;\n number[index] = (UInt32)result;\n if (result >= 0x100000000U)\n borrow = 0;\n else\n borrow = 1;\n index--;\n }\n }\n public void Multiply(UInt32 value) {\n int index = size - 1;\n while (index >= 0 && number[index] == 0)\n index--;\n\n UInt32 carry = 0;\n while (index >= 0) {\n UInt64 result = (UInt64)number[index] * value + carry;\n number[index] = (UInt32)result;\n carry = (UInt32)(result >> 32);\n index--;\n }\n }\n public void Divide(UInt32 value) {\n int index = 0;\n while (index < size && number[index] == 0)\n index++;\n\n UInt32 carry = 0;\n while (index < size) {\n UInt64 result = number[index] + ((UInt64)carry << 32);\n number[index] = (UInt32)(result / (UInt64)value);\n carry = (UInt32)(result % (UInt64)value);\n index++;\n }\n }\n public void Assign(BigNumber value) {\n VerifySameSize(value);\n for (int i = 0; i < size; i++) {\n number[i] = value.number[i];\n }\n }\n\n public override string ToString() {\n BigNumber temp = new BigNumber(maxDigits);\n temp.Assign(this);\n\n StringBuilder sb = new StringBuilder();\n sb.Append(temp.number[0]);\n sb.Append(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator);\n\n int digitCount = 0;\n while (digitCount < maxDigits) {\n temp.number[0] = 0;\n temp.Multiply(100000);\n sb.AppendFormat(\"{0:D5}\", temp.number[0]);\n digitCount += 5;\n }\n\n return sb.ToString();\n }\n public bool IsZero() {\n foreach (UInt32 item in number) {\n if (item != 0)\n return false;\n }\n return true;\n }\n\n public void ArcTan(UInt32 multiplicand, UInt32 reciprocal) {\n BigNumber X = new BigNumber(maxDigits, multiplicand);\n X.Divide(reciprocal);\n reciprocal *= reciprocal;\n\n this.Assign(X);\n\n BigNumber term = new BigNumber(maxDigits);\n UInt32 divisor = 1;\n bool subtractTerm = true;\n while (true) {\n X.Divide(reciprocal);\n term.Assign(X);\n divisor += 2;\n term.Divide(divisor);\n if (term.IsZero())\n break;\n\n if (subtractTerm)\n this.Subtract(term);\n else\n this.Add(term);\n subtractTerm = !subtractTerm;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 622950,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Instead of defining pi as a constant, I always use <code>acos(-1)</code>.</p>\n"
},
{
"answer_id": 1439914,
"author": "Daniel C. Sobral",
"author_id": 53013,
"author_profile": "https://Stackoverflow.com/users/53013",
"pm_score": 4,
"selected": false,
"text": "<p>If you are willing to use an approximation, <code>355 / 113</code> is good for 6 decimal digits, and has the added advantage of being usable with integer expressions. That's not as important these days, as \"floating point math co-processor\" ceased to have any meaning, but it was quite important once.</p>\n"
},
{
"answer_id": 1947163,
"author": "jon-hanson",
"author_id": 84538,
"author_profile": "https://Stackoverflow.com/users/84538",
"pm_score": 6,
"selected": false,
"text": "<p>In the interests of completeness, a C++ template version, which, for an optimised build, will compute an approximation of PI at compile time, and will inline to a single value.</p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>#include <iostream>\n\ntemplate<int I>\nstruct sign\n{\n enum {value = (I % 2) == 0 ? 1 : -1};\n};\n\ntemplate<int I, int J>\nstruct pi_calc\n{\n inline static double value ()\n {\n return (pi_calc<I-1, J>::value () + pi_calc<I-1, J+1>::value ()) / 2.0;\n }\n};\n\ntemplate<int J>\nstruct pi_calc<0, J>\n{\n inline static double value ()\n {\n return (sign<J>::value * 4.0) / (2.0 * J + 1.0) + pi_calc<0, J-1>::value ();\n }\n};\n\n\ntemplate<>\nstruct pi_calc<0, 0>\n{\n inline static double value ()\n {\n return 4.0;\n }\n};\n\ntemplate<int I>\nstruct pi\n{\n inline static double value ()\n {\n return pi_calc<I, I>::value ();\n }\n};\n\nint main ()\n{\n std::cout.precision (12);\n\n const double pi_value = pi<10>::value ();\n\n std::cout << \"pi ~ \" << pi_value << std::endl;\n\n return 0;\n}\n</code></pre>\n\n<p>Note for I > 10, optimised builds can be slow, likewise for non-optimised runs. For 12 iterations I believe there are around 80k calls to value() (in the absence of memoisation).</p>\n"
},
{
"answer_id": 1949194,
"author": "Seth",
"author_id": 65295,
"author_profile": "https://Stackoverflow.com/users/65295",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to <em>compute</em> an approximation of the value of π (for some reason), you should try a binary extraction algorithm. <a href=\"http://en.wikipedia.org/wiki/Bellard%27s_formula\" rel=\"noreferrer\">Bellard's</a> improvement of <a href=\"http://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula\" rel=\"noreferrer\">BBP</a> gives does PI in O(N^2). </p>\n\n<hr>\n\n<p>If you want to <em>obtain</em> an approximation of the value of π to do calculations, then: </p>\n\n<pre><code>PI = 3.141592654\n</code></pre>\n\n<p>Granted, that's only an approximation, and not entirely accurate. It's off by a little more than 0.00000000004102. (four ten-trillionths, about <sup>4</sup>/<sub>10,000,000,000</sub>).</p>\n\n<hr>\n\n<p>If you want to do <em>math</em> with π, then get yourself a pencil and paper or a computer algebra package, and use π's exact value, π. </p>\n\n<p>If you really want a formula, this one is fun: </p>\n\n<h2>π = -<em>i</em> ln(-1)</h2>\n"
},
{
"answer_id": 2350024,
"author": "qwerty01",
"author_id": 282776,
"author_profile": "https://Stackoverflow.com/users/282776",
"pm_score": 4,
"selected": false,
"text": "<p>With doubles:</p>\n\n<pre><code>4.0 * (4.0 * Math.Atan(0.2) - Math.Atan(1.0 / 239.0))\n</code></pre>\n\n<p>This will be accurate up to 14 decimal places, enough to fill a double (the inaccuracy is probably because the rest of the decimals in the arc tangents are truncated).</p>\n\n<p>Also Seth, it's 3.14159265358979323846<b>3</b>, not 64.</p>\n"
},
{
"answer_id": 4905303,
"author": "NihilistDandy",
"author_id": 604108,
"author_profile": "https://Stackoverflow.com/users/604108",
"pm_score": 4,
"selected": false,
"text": "<p>Use the Machin-like formula </p>\n\n<pre><code>176 * arctan (1/57) + 28 * arctan (1/239) - 48 * arctan (1/682) + 96 * arctan(1/12943) \n\n[; \\left( 176 \\arctan \\frac{1}{57} + 28 \\arctan \\frac{1}{239} - 48 \\arctan \\frac{1}{682} + 96 \\arctan \\frac{1}{12943}\\right) ;], for you TeX the World people.\n</code></pre>\n\n<p>Implemented in Scheme, for instance: </p>\n\n<p><code>(+ (- (+ (* 176 (atan (/ 1 57))) (* 28 (atan (/ 1 239)))) (* 48 (atan (/ 1 682)))) (* 96 (atan (/ 1 12943))))</code></p>\n"
},
{
"answer_id": 7924123,
"author": "Tilo",
"author_id": 677684,
"author_profile": "https://Stackoverflow.com/users/677684",
"pm_score": 5,
"selected": false,
"text": "<p>The following answers <strong>precisely how to do this in the fastest possible way -- with the least computing effort</strong>. Even if you don't like the answer, you have to admit that it is indeed the fastest way to get the value of PI.</p>\n<p>The <strong>FASTEST</strong> way to get the value of Pi is:</p>\n<ol>\n<li>chose your favourite programming language</li>\n<li>load its Math library</li>\n<li>and find that Pi is already defined there -- ready for use!</li>\n</ol>\n<p>In case you don't have a Math library at hand..</p>\n<p>The <strong>SECOND FASTEST</strong> way (more universal solution) is:</p>\n<p>look up Pi on the Internet, e.g. here:</p>\n<p><a href=\"http://www.eveandersson.com/pi/digits/1000000\" rel=\"nofollow noreferrer\">http://www.eveandersson.com/pi/digits/1000000</a> (1 million digits .. what's your floating point precision? )</p>\n<p>or here:</p>\n<p><a href=\"http://3.141592653589793238462643383279502884197169399375105820974944592.com/\" rel=\"nofollow noreferrer\">http://3.141592653589793238462643383279502884197169399375105820974944592.com/</a></p>\n<p>or here:</p>\n<p><a href=\"http://en.wikipedia.org/wiki/Pi\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Pi</a></p>\n<p>It's really fast to find the digits you need for whatever precision arithmetic you would like to use, and by defining a constant, you can make sure that you don't waste precious CPU time.</p>\n<p>Not only is this a partly humorous answer, but in reality, if anybody would go ahead and compute the value of Pi in a real application .. that would be a pretty big waste of CPU time, wouldn't it? At least I don't see a real application for trying to re-compute this.</p>\n<p><strong>Also consider</strong> that NASA only uses 15 digits of Pi for calculating interplanetary travel:</p>\n<ul>\n<li>TL;DR: <a href=\"https://twitter.com/Rainmaker1973/status/1463477499434835968\" rel=\"nofollow noreferrer\">https://twitter.com/Rainmaker1973/status/1463477499434835968</a></li>\n<li>JPL Explanation: <a href=\"https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/\" rel=\"nofollow noreferrer\">https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/</a></li>\n</ul>\n<p>Dear Moderator: please note that the OP asked: "Fastest Way to get the value of PI"</p>\n"
},
{
"answer_id": 44346598,
"author": "Agnius Vasiliauskas",
"author_id": 380331,
"author_profile": "https://Stackoverflow.com/users/380331",
"pm_score": 1,
"selected": false,
"text": "<p>Calculating π from circle area :-)</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><input id=\"range\" type=\"range\" min=\"10\" max=\"960\" value=\"10\" step=\"50\" oninput=\"calcPi()\">\r\n<br>\r\n<div id=\"cont\"></div>\r\n\r\n<script>\r\nfunction generateCircle(width) {\r\n var c = width/2;\r\n var delta = 1.0;\r\n var str = \"\";\r\n var xCount = 0;\r\n for (var x=0; x <= width; x++) {\r\n for (var y = 0; y <= width; y++) {\r\n var d = Math.sqrt((x-c)*(x-c) + (y-c)*(y-c));\r\n if (d > (width-1)/2) {\r\n str += '.';\r\n }\r\n else {\r\n xCount++;\r\n str += 'o';\r\n }\r\n str += \"&nbsp;\" \r\n }\r\n str += \"\\n\";\r\n }\r\n var pi = (xCount * 4) / (width * width);\r\n return [str, pi];\r\n}\r\n\r\nfunction calcPi() {\r\n var e = document.getElementById(\"cont\");\r\n var width = document.getElementById(\"range\").value;\r\n e.innerHTML = \"<h4>Generating circle...</h4>\";\r\n setTimeout(function() {\r\n var circ = generateCircle(width);\r\n e.innerHTML = \"<pre>\" + \"π = \" + circ[1].toFixed(2) + \"\\n\" + circ[0] +\"</pre>\";\r\n }, 200);\r\n}\r\ncalcPi();\r\n</script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 50907044,
"author": "Anand Tripathi",
"author_id": 5230702,
"author_profile": "https://Stackoverflow.com/users/5230702",
"pm_score": 0,
"selected": false,
"text": "<h2>Better Approach</h2>\n\n<p>To get the output of standard constants like <strong>pi</strong> or the standard concepts, we should first go with the builtins methods available in the language that you are using. It will return a value in the fastest and best way. I am using python to run the fastest way to get the value of pi.</p>\n\n<ul>\n<li><strong>pi variable of the math library</strong>. The math library stores the variable pi as a constant.</li>\n</ul>\n\n<p>math_pi.py</p>\n\n<pre><code>import math\nprint math.pi\n</code></pre>\n\n<p>Run the script with time utility of linux <code>/usr/bin/time -v python math_pi.py</code></p>\n\n<p>Output:</p>\n\n<pre><code>Command being timed: \"python math_pi.py\"\nUser time (seconds): 0.01\nSystem time (seconds): 0.01\nPercent of CPU this job got: 91%\nElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.03\n</code></pre>\n\n<ul>\n<li><strong>Use arc cos method of math</strong></li>\n</ul>\n\n<p>acos_pi.py</p>\n\n<pre><code>import math\nprint math.acos(-1)\n</code></pre>\n\n<p>Run the script with time utility of linux <code>/usr/bin/time -v python acos_pi.py</code></p>\n\n<p>Output:</p>\n\n<pre><code>Command being timed: \"python acos_pi.py\"\nUser time (seconds): 0.02\nSystem time (seconds): 0.01\nPercent of CPU this job got: 94%\nElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.03\n</code></pre>\n\n<ul>\n<li><strong>use <a href=\"https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula\" rel=\"nofollow noreferrer\">BBP formula</a></strong></li>\n</ul>\n\n<p>bbp_pi.py</p>\n\n<pre><code>from decimal import Decimal, getcontext\ngetcontext().prec=100\nprint sum(1/Decimal(16)**k * \n (Decimal(4)/(8*k+1) - \n Decimal(2)/(8*k+4) - \n Decimal(1)/(8*k+5) -\n Decimal(1)/(8*k+6)) for k in range(100))\n</code></pre>\n\n<p>Run the script with time utility of linux <code>/usr/bin/time -v python bbp_pi.py</code></p>\n\n<p>Output:</p>\n\n<pre><code>Command being timed: \"python c.py\"\nUser time (seconds): 0.05\nSystem time (seconds): 0.01\nPercent of CPU this job got: 98%\nElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.06\n</code></pre>\n\n<p><strong>So the best way is to use builtin methods provided by the language because they are the fastest and best to get the output. In python use math.pi</strong></p>\n"
},
{
"answer_id": 61670212,
"author": "paperclip optimizer",
"author_id": 11147804,
"author_profile": "https://Stackoverflow.com/users/11147804",
"pm_score": 1,
"selected": false,
"text": "<p>The Chudnovsky algorithm is pretty fast if you don't mind performing a square root and a couple inverses. It converges to double precision in just 2 iterations.</p>\n\n<pre><code>/*\n Chudnovsky algorithm for computing PI\n*/\n\n#include <iostream>\n#include <cmath>\nusing namespace std;\n\ndouble calc_PI(int K=2) {\n\n static const int A = 545140134;\n static const int B = 13591409;\n static const int D = 640320;\n\n const double ID3 = 1./ (double(D)*double(D)*double(D));\n\n double sum = 0.;\n double b = sqrt(ID3);\n long long int p = 1;\n long long int a = B;\n\n sum += double(p) * double(a)* b;\n\n // 2 iterations enough for double convergence\n for (int k=1; k<K; ++k) {\n // A*k + B\n a += A;\n // update denominator\n b *= ID3;\n // p = (-1)^k 6k! / 3k! k!^3\n p *= (6*k)*(6*k-1)*(6*k-2)*(6*k-3)*(6*k-4)*(6*k-5);\n p /= (3*k)*(3*k-1)*(3*k-2) * k*k*k;\n p = -p;\n\n sum += double(p) * double(a)* b;\n }\n\n return 1./(12*sum);\n}\n\nint main() {\n\n cout.precision(16);\n cout.setf(ios::fixed);\n\n for (int k=1; k<=5; ++k) cout << \"k = \" << k << \" PI = \" << calc_PI(k) << endl;\n\n return 0;\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>k = 1 PI = 3.1415926535897341\nk = 2 PI = 3.1415926535897931\nk = 3 PI = 3.1415926535897931\nk = 4 PI = 3.1415926535897931\nk = 5 PI = 3.1415926535897931\n</code></pre>\n"
},
{
"answer_id": 64410809,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Basically the C version of paperclip optimizer's answer, and much more simpilified:</p>\n<pre><code>#include <stdio.h>\n#include <math.h>\n\ndouble calc_PI(int K) {\n static const int A = 545140134;\n static const int B = 13591409;\n static const int D = 640320;\n const double ID3 = 1.0 / ((double) D * (double) D * (double) D);\n double sum = 0.0;\n double b = sqrt(ID3);\n long long int p = 1;\n long long int a = B;\n sum += (double) p * (double) a * b;\n for (int k = 1; k < K; ++k) {\n a += A;\n b *= ID3;\n p *= (6 * k) * (6 * k - 1) * (6 * k - 2) * (6 * k - 3) * (6 * k - 4) * (6 * k - 5);\n p /= (3 * k) * (3 * k - 1) * (3 * k - 2) * k * k * k;\n p = -p;\n sum += (double) p * (double) a * b;\n }\n return 1.0 / (12 * sum);\n}\n\nint main() {\n for (int k = 1; k <= 5; ++k) {\n printf("k = %i, PI = %.16f\\n", k, calc_PI(k));\n }\n}\n</code></pre>\n<p>But for more simplification, this algorithm takes Chudnovsky's formula, which I can fully simplify if you don't really understand the code.</p>\n<p>Summary: We will get a number from 1 to 5 and add it in to a function we will use to get PI. Then 3 numbers are given to you: 545140134 (A), 13591409 (B), 640320 (D). Then we will use D as a <code>double</code> multiplying itself 3 times into another <code>double</code> (ID3). We will then take the square root of ID3 into another <code>double</code> (b) and assign 2 numbers: 1 (p), the value of B (a). <strong>Take note that C is case-insensitive.</strong> Then a <code>double</code> (sum) will be created by multiplying the value's of p, a and b, all in <code>double</code>s. Then a loop up until the number given for the function will start and add up A's value to a, b's value gets multiplied by ID3, p's value will be multiplied by multiple values that I hope you can understand and also gets divided by multiple values as well. The sum will add up by p, a and b once again and the loop will repeat until the value of the loop's number is greater or equal to 5. Later, the sum is multiplied by 12 and returned by the function giving us the result of PI.</p>\n<p>Okay, that was long, but I guess you will understand it...</p>\n"
},
{
"answer_id": 69610755,
"author": "Rajanand",
"author_id": 16425812,
"author_profile": "https://Stackoverflow.com/users/16425812",
"pm_score": 1,
"selected": false,
"text": "<p>I think the value of pi is the ratio between the circumference and radius of the circle.</p>\n<p>It can be simply achieved by a regular math calculation</p>\n"
},
{
"answer_id": 73777598,
"author": "Andy Richter",
"author_id": 6262481,
"author_profile": "https://Stackoverflow.com/users/6262481",
"pm_score": 0,
"selected": false,
"text": "<h2>Faster than GMPY2 and MPmath Built-ins: A Billion in 45 minutes:</h2>\n<hr />\n<p>I tried several ways; Manchin, AGM and Chudnovsky Bros. Chudnovsky with Binary Split was the fastest:<br />\nMy github : <a href=\"https://github.com/Overboard-code/Pi-Pourri\" rel=\"nofollow noreferrer\">https://github.com/Overboard-code/Pi-Pourri</a></p>\n<p>My Binary Split Chudnovsky is about <strong>twice</strong> the speed of the builtin gmpy2.const_pi(). MPmath.mp.pi() took 50 minutes for a billion, so it was almost as fast as the Chudnovsky.</p>\n<p>I would greatly appreciate performance tips as well. I am not sure my code is perfect. It is 100% accurate (all formula agree to 100 million) but maybe could be faster?</p>\n<p>I tried gmpy2.const_pi() to 100 million digits and it took 300 seconds vs. 150 seconds for the Chudnovsky on the same machine. pi.txt and pi2.txt were the same.</p>\n<p>I got to a billion digits on my old i7 16GB laptop in less than an hour.</p>\n<p>Here is a snippet of the fastest of the 12 methods I tried:</p>\n<pre><code>class PiChudnovsky:\n """Version of Chudnovsky Bros using Binary Splitting \n So far this is the winner for fastest time to a million digits on my older intel i7\n """\n A = mpz(13591409)\n B = mpz(545140134)\n C = mpz(640320)\n D = mpz(426880)\n E = mpz(10005)\n C3_24 = pow(C, mpz(3)) // mpz(24)\n #DIGITS_PER_TERM = math.log(53360 ** 3) / math.log(10) #=> 14.181647462725476\n DIGITS_PER_TERM = 14.181647462725476\n MMILL = mpz(1000000)\n\n def __init__(self,ndigits):\n """ Initialization\n :param int ndigits: digits of PI computation\n """\n self.ndigits = ndigits\n self.n = mpz(self.ndigits // self.DIGITS_PER_TERM + 1)\n self.prec = mpz((self.ndigits + 1) * LOG2_10)\n self.one_sq = pow(mpz(10),mpz(2 * ndigits))\n self.sqrt_c = isqrt(self.E * self.one_sq)\n self.iters = mpz(0)\n self.start_time = 0\n\n def compute(self):\n """ Computation """\n try:\n self.start_time = time.time()\n logging.debug("Starting {} formula to {:,} decimal places"\n .format(name,ndigits) )\n __, q, t = self.__bs(mpz(0), self.n) # p is just for recursion\n pi = (q * self.D * self.sqrt_c) // t\n logging.debug('{} calulation Done! {:,} iterations and {:.2f} seconds.'\n .format( name, int(self.iters),time.time() - self.start_time))\n get_context().precision= int((self.ndigits+10) * LOG2_10)\n pi_s = pi.digits() # digits() gmpy2 creates a string \n pi_o = pi_s[:1] + "." + pi_s[1:]\n return pi_o,int(self.iters),time.time() - self.start_time\n except Exception as e:\n print (e.message, e.args)\n raise\n\n def __bs(self, a, b):\n """ PQT computation by BSA(= Binary Splitting Algorithm)\n :param int a: positive integer\n :param int b: positive integer\n :return list [int p_ab, int q_ab, int t_ab]\n """\n try:\n self.iters += mpz(1)\n if self.iters % self.MMILL == mpz(0):\n logging.debug('Chudnovsky ... {:,} iterations and {:.2f} seconds.'\n .format( int(self.iters),time.time() - self.start_time))\n if a + mpz(1) == b:\n if a == mpz(0):\n p_ab = q_ab = mpz(1)\n else:\n p_ab = mpz((mpz(6) * a - mpz(5)) * (mpz(2) * a - mpz(1)) * (mpz(6) * a - mpz(1)))\n q_ab = pow(a,mpz(3)) * self.C3_24\n t_ab = p_ab * (self.A + self.B * a)\n if a & 1:\n t_ab *= mpz(-1)\n else:\n m = (a + b) // mpz(2)\n p_am, q_am, t_am = self.__bs(a, m)\n p_mb, q_mb, t_mb = self.__bs(m, b)\n p_ab = p_am * p_mb\n q_ab = q_am * q_mb\n t_ab = q_mb * t_am + p_am * t_mb\n return [p_ab, q_ab, t_ab]\n except Exception as e:\n print (e.message, e.args)\n raise\n</code></pre>\n<p>Here is the output of 1,000,000,000 digits less than 45 minutes:</p>\n<pre><code>python pi-pourri.py -v -d 1,000,000,000 -a 10 \n\n[INFO] 2022-10-03 09:22:51,860 <module>: MainProcess Computing π to 1,000,000,000 digits.\n[DEBUG] 2022-10-03 09:25:00,543 compute: MainProcess Starting Chudnovsky brothers 1988 \n π = (Q(0, N) / 12T(0, N) + 12AQ(0, N))**(C**(3/2))\n formula to 1,000,000,000 decimal places\n[DEBUG] 2022-10-03 09:25:04,995 __bs: MainProcess Chudnovsky ... 1,000,000 iterations and 4.45 seconds.\n[DEBUG] 2022-10-03 09:25:10,836 __bs: MainProcess Chudnovsky ... 2,000,000 iterations and 10.29 seconds.\n[DEBUG] 2022-10-03 09:25:18,227 __bs: MainProcess Chudnovsky ... 3,000,000 iterations and 17.68 seconds.\n[DEBUG] 2022-10-03 09:25:24,512 __bs: MainProcess Chudnovsky ... 4,000,000 iterations and 23.97 seconds.\n[DEBUG] 2022-10-03 09:25:35,670 __bs: MainProcess Chudnovsky ... 5,000,000 iterations and 35.13 seconds.\n[DEBUG] 2022-10-03 09:25:41,376 __bs: MainProcess Chudnovsky ... 6,000,000 iterations and 40.83 seconds.\n[DEBUG] 2022-10-03 09:25:49,238 __bs: MainProcess Chudnovsky ... 7,000,000 iterations and 48.69 seconds.\n[DEBUG] 2022-10-03 09:25:55,646 __bs: MainProcess Chudnovsky ... 8,000,000 iterations and 55.10 seconds.\n[DEBUG] 2022-10-03 09:26:15,043 __bs: MainProcess Chudnovsky ... 9,000,000 iterations and 74.50 seconds.\n[DEBUG] 2022-10-03 09:26:21,437 __bs: MainProcess Chudnovsky ... 10,000,000 iterations and 80.89 seconds.\n[DEBUG] 2022-10-03 09:26:26,587 __bs: MainProcess Chudnovsky ... 11,000,000 iterations and 86.04 seconds.\n[DEBUG] 2022-10-03 09:26:34,777 __bs: MainProcess Chudnovsky ... 12,000,000 iterations and 94.23 seconds.\n[DEBUG] 2022-10-03 09:26:41,231 __bs: MainProcess Chudnovsky ... 13,000,000 iterations and 100.69 seconds.\n[DEBUG] 2022-10-03 09:26:52,972 __bs: MainProcess Chudnovsky ... 14,000,000 iterations and 112.43 seconds.\n[DEBUG] 2022-10-03 09:26:59,517 __bs: MainProcess Chudnovsky ... 15,000,000 iterations and 118.97 seconds.\n[DEBUG] 2022-10-03 09:27:07,932 __bs: MainProcess Chudnovsky ... 16,000,000 iterations and 127.39 seconds.\n[DEBUG] 2022-10-03 09:27:14,036 __bs: MainProcess Chudnovsky ... 17,000,000 iterations and 133.49 seconds.\n[DEBUG] 2022-10-03 09:27:51,629 __bs: MainProcess Chudnovsky ... 18,000,000 iterations and 171.09 seconds.\n[DEBUG] 2022-10-03 09:27:58,176 __bs: MainProcess Chudnovsky ... 19,000,000 iterations and 177.63 seconds.\n[DEBUG] 2022-10-03 09:28:06,704 __bs: MainProcess Chudnovsky ... 20,000,000 iterations and 186.16 seconds.\n[DEBUG] 2022-10-03 09:28:13,376 __bs: MainProcess Chudnovsky ... 21,000,000 iterations and 192.83 seconds.\n[DEBUG] 2022-10-03 09:28:18,737 __bs: MainProcess Chudnovsky ... 22,000,000 iterations and 198.19 seconds.\n[DEBUG] 2022-10-03 09:28:31,095 __bs: MainProcess Chudnovsky ... 23,000,000 iterations and 210.55 seconds.\n[DEBUG] 2022-10-03 09:28:37,789 __bs: MainProcess Chudnovsky ... 24,000,000 iterations and 217.25 seconds.\n[DEBUG] 2022-10-03 09:28:46,171 __bs: MainProcess Chudnovsky ... 25,000,000 iterations and 225.63 seconds.\n[DEBUG] 2022-10-03 09:28:52,933 __bs: MainProcess Chudnovsky ... 26,000,000 iterations and 232.39 seconds.\n[DEBUG] 2022-10-03 09:29:13,524 __bs: MainProcess Chudnovsky ... 27,000,000 iterations and 252.98 seconds.\n[DEBUG] 2022-10-03 09:29:19,676 __bs: MainProcess Chudnovsky ... 28,000,000 iterations and 259.13 seconds.\n[DEBUG] 2022-10-03 09:29:28,196 __bs: MainProcess Chudnovsky ... 29,000,000 iterations and 267.65 seconds.\n[DEBUG] 2022-10-03 09:29:34,720 __bs: MainProcess Chudnovsky ... 30,000,000 iterations and 274.18 seconds.\n[DEBUG] 2022-10-03 09:29:47,075 __bs: MainProcess Chudnovsky ... 31,000,000 iterations and 286.53 seconds.\n[DEBUG] 2022-10-03 09:29:53,746 __bs: MainProcess Chudnovsky ... 32,000,000 iterations and 293.20 seconds.\n[DEBUG] 2022-10-03 09:29:59,099 __bs: MainProcess Chudnovsky ... 33,000,000 iterations and 298.56 seconds.\n[DEBUG] 2022-10-03 09:30:07,511 __bs: MainProcess Chudnovsky ... 34,000,000 iterations and 306.97 seconds.\n[DEBUG] 2022-10-03 09:30:14,279 __bs: MainProcess Chudnovsky ... 35,000,000 iterations and 313.74 seconds.\n[DEBUG] 2022-10-03 09:31:31,710 __bs: MainProcess Chudnovsky ... 36,000,000 iterations and 391.17 seconds.\n[DEBUG] 2022-10-03 09:31:38,454 __bs: MainProcess Chudnovsky ... 37,000,000 iterations and 397.91 seconds.\n[DEBUG] 2022-10-03 09:31:46,437 __bs: MainProcess Chudnovsky ... 38,000,000 iterations and 405.89 seconds.\n[DEBUG] 2022-10-03 09:31:53,285 __bs: MainProcess Chudnovsky ... 39,000,000 iterations and 412.74 seconds.\n[DEBUG] 2022-10-03 09:32:05,602 __bs: MainProcess Chudnovsky ... 40,000,000 iterations and 425.06 seconds.\n[DEBUG] 2022-10-03 09:32:12,220 __bs: MainProcess Chudnovsky ... 41,000,000 iterations and 431.68 seconds.\n[DEBUG] 2022-10-03 09:32:20,708 __bs: MainProcess Chudnovsky ... 42,000,000 iterations and 440.17 seconds.\n[DEBUG] 2022-10-03 09:32:27,552 __bs: MainProcess Chudnovsky ... 43,000,000 iterations and 447.01 seconds.\n[DEBUG] 2022-10-03 09:32:32,986 __bs: MainProcess Chudnovsky ... 44,000,000 iterations and 452.44 seconds.\n[DEBUG] 2022-10-03 09:32:53,904 __bs: MainProcess Chudnovsky ... 45,000,000 iterations and 473.36 seconds.\n[DEBUG] 2022-10-03 09:33:00,832 __bs: MainProcess Chudnovsky ... 46,000,000 iterations and 480.29 seconds.\n[DEBUG] 2022-10-03 09:33:09,198 __bs: MainProcess Chudnovsky ... 47,000,000 iterations and 488.66 seconds.\n[DEBUG] 2022-10-03 09:33:16,000 __bs: MainProcess Chudnovsky ... 48,000,000 iterations and 495.46 seconds.\n[DEBUG] 2022-10-03 09:33:27,921 __bs: MainProcess Chudnovsky ... 49,000,000 iterations and 507.38 seconds.\n[DEBUG] 2022-10-03 09:33:34,778 __bs: MainProcess Chudnovsky ... 50,000,000 iterations and 514.24 seconds.\n[DEBUG] 2022-10-03 09:33:43,298 __bs: MainProcess Chudnovsky ... 51,000,000 iterations and 522.76 seconds.\n[DEBUG] 2022-10-03 09:33:49,959 __bs: MainProcess Chudnovsky ... 52,000,000 iterations and 529.42 seconds.\n[DEBUG] 2022-10-03 09:34:29,294 __bs: MainProcess Chudnovsky ... 53,000,000 iterations and 568.75 seconds.\n[DEBUG] 2022-10-03 09:34:36,176 __bs: MainProcess Chudnovsky ... 54,000,000 iterations and 575.63 seconds.\n[DEBUG] 2022-10-03 09:34:41,576 __bs: MainProcess Chudnovsky ... 55,000,000 iterations and 581.03 seconds.\n[DEBUG] 2022-10-03 09:34:50,161 __bs: MainProcess Chudnovsky ... 56,000,000 iterations and 589.62 seconds.\n[DEBUG] 2022-10-03 09:34:56,811 __bs: MainProcess Chudnovsky ... 57,000,000 iterations and 596.27 seconds.\n[DEBUG] 2022-10-03 09:35:09,382 __bs: MainProcess Chudnovsky ... 58,000,000 iterations and 608.84 seconds.\n[DEBUG] 2022-10-03 09:35:16,206 __bs: MainProcess Chudnovsky ... 59,000,000 iterations and 615.66 seconds.\n[DEBUG] 2022-10-03 09:35:24,295 __bs: MainProcess Chudnovsky ... 60,000,000 iterations and 623.75 seconds.\n[DEBUG] 2022-10-03 09:35:31,095 __bs: MainProcess Chudnovsky ... 61,000,000 iterations and 630.55 seconds.\n[DEBUG] 2022-10-03 09:35:52,139 __bs: MainProcess Chudnovsky ... 62,000,000 iterations and 651.60 seconds.\n[DEBUG] 2022-10-03 09:35:58,781 __bs: MainProcess Chudnovsky ... 63,000,000 iterations and 658.24 seconds.\n[DEBUG] 2022-10-03 09:36:07,399 __bs: MainProcess Chudnovsky ... 64,000,000 iterations and 666.86 seconds.\n[DEBUG] 2022-10-03 09:36:12,847 __bs: MainProcess Chudnovsky ... 65,000,000 iterations and 672.30 seconds.\n[DEBUG] 2022-10-03 09:36:19,763 __bs: MainProcess Chudnovsky ... 66,000,000 iterations and 679.22 seconds.\n[DEBUG] 2022-10-03 09:36:32,351 __bs: MainProcess Chudnovsky ... 67,000,000 iterations and 691.81 seconds.\n[DEBUG] 2022-10-03 09:36:39,078 __bs: MainProcess Chudnovsky ... 68,000,000 iterations and 698.53 seconds.\n[DEBUG] 2022-10-03 09:36:47,830 __bs: MainProcess Chudnovsky ... 69,000,000 iterations and 707.29 seconds.\n[DEBUG] 2022-10-03 09:36:54,701 __bs: MainProcess Chudnovsky ... 70,000,000 iterations and 714.16 seconds.\n[DEBUG] 2022-10-03 09:39:39,357 __bs: MainProcess Chudnovsky ... 71,000,000 iterations and 878.81 seconds.\n[DEBUG] 2022-10-03 09:39:46,199 __bs: MainProcess Chudnovsky ... 72,000,000 iterations and 885.66 seconds.\n[DEBUG] 2022-10-03 09:39:54,956 __bs: MainProcess Chudnovsky ... 73,000,000 iterations and 894.41 seconds.\n[DEBUG] 2022-10-03 09:40:01,639 __bs: MainProcess Chudnovsky ... 74,000,000 iterations and 901.10 seconds.\n[DEBUG] 2022-10-03 09:40:14,219 __bs: MainProcess Chudnovsky ... 75,000,000 iterations and 913.68 seconds.\n[DEBUG] 2022-10-03 09:40:19,680 __bs: MainProcess Chudnovsky ... 76,000,000 iterations and 919.14 seconds.\n[DEBUG] 2022-10-03 09:40:26,625 __bs: MainProcess Chudnovsky ... 77,000,000 iterations and 926.08 seconds.\n[DEBUG] 2022-10-03 09:40:35,212 __bs: MainProcess Chudnovsky ... 78,000,000 iterations and 934.67 seconds.\n[DEBUG] 2022-10-03 09:40:41,914 __bs: MainProcess Chudnovsky ... 79,000,000 iterations and 941.37 seconds.\n[DEBUG] 2022-10-03 09:41:03,218 __bs: MainProcess Chudnovsky ... 80,000,000 iterations and 962.68 seconds.\n[DEBUG] 2022-10-03 09:41:10,213 __bs: MainProcess Chudnovsky ... 81,000,000 iterations and 969.67 seconds.\n[DEBUG] 2022-10-03 09:41:18,344 __bs: MainProcess Chudnovsky ... 82,000,000 iterations and 977.80 seconds.\n[DEBUG] 2022-10-03 09:41:25,261 __bs: MainProcess Chudnovsky ... 83,000,000 iterations and 984.72 seconds.\n[DEBUG] 2022-10-03 09:41:37,663 __bs: MainProcess Chudnovsky ... 84,000,000 iterations and 997.12 seconds.\n[DEBUG] 2022-10-03 09:41:44,680 __bs: MainProcess Chudnovsky ... 85,000,000 iterations and 1004.14 seconds.\n[DEBUG] 2022-10-03 09:41:53,411 __bs: MainProcess Chudnovsky ... 86,000,000 iterations and 1012.87 seconds.\n[DEBUG] 2022-10-03 09:41:58,926 __bs: MainProcess Chudnovsky ... 87,000,000 iterations and 1018.38 seconds.\n[DEBUG] 2022-10-03 09:42:05,858 __bs: MainProcess Chudnovsky ... 88,000,000 iterations and 1025.32 seconds.\n[DEBUG] 2022-10-03 09:42:46,163 __bs: MainProcess Chudnovsky ... 89,000,000 iterations and 1065.62 seconds.\n[DEBUG] 2022-10-03 09:42:53,054 __bs: MainProcess Chudnovsky ... 90,000,000 iterations and 1072.51 seconds.\n[DEBUG] 2022-10-03 09:43:02,030 __bs: MainProcess Chudnovsky ... 91,000,000 iterations and 1081.49 seconds.\n[DEBUG] 2022-10-03 09:43:09,192 __bs: MainProcess Chudnovsky ... 92,000,000 iterations and 1088.65 seconds.\n[DEBUG] 2022-10-03 09:43:21,533 __bs: MainProcess Chudnovsky ... 93,000,000 iterations and 1100.99 seconds.\n[DEBUG] 2022-10-03 09:43:28,643 __bs: MainProcess Chudnovsky ... 94,000,000 iterations and 1108.10 seconds.\n[DEBUG] 2022-10-03 09:43:37,372 __bs: MainProcess Chudnovsky ... 95,000,000 iterations and 1116.83 seconds.\n[DEBUG] 2022-10-03 09:43:44,558 __bs: MainProcess Chudnovsky ... 96,000,000 iterations and 1124.02 seconds.\n[DEBUG] 2022-10-03 09:44:06,555 __bs: MainProcess Chudnovsky ... 97,000,000 iterations and 1146.01 seconds.\n[DEBUG] 2022-10-03 09:44:12,220 __bs: MainProcess Chudnovsky ... 98,000,000 iterations and 1151.68 seconds.\n[DEBUG] 2022-10-03 09:44:19,278 __bs: MainProcess Chudnovsky ... 99,000,000 iterations and 1158.74 seconds.\n[DEBUG] 2022-10-03 09:44:28,323 __bs: MainProcess Chudnovsky ... 100,000,000 iterations and 1167.78 seconds.\n[DEBUG] 2022-10-03 09:44:35,211 __bs: MainProcess Chudnovsky ... 101,000,000 iterations and 1174.67 seconds.\n[DEBUG] 2022-10-03 09:44:48,331 __bs: MainProcess Chudnovsky ... 102,000,000 iterations and 1187.79 seconds.\n[DEBUG] 2022-10-03 09:44:54,835 __bs: MainProcess Chudnovsky ... 103,000,000 iterations and 1194.29 seconds.\n[DEBUG] 2022-10-03 09:45:03,869 __bs: MainProcess Chudnovsky ... 104,000,000 iterations and 1203.33 seconds.\n[DEBUG] 2022-10-03 09:45:10,967 __bs: MainProcess Chudnovsky ... 105,000,000 iterations and 1210.42 seconds.\n[DEBUG] 2022-10-03 09:46:32,760 __bs: MainProcess Chudnovsky ... 106,000,000 iterations and 1292.22 seconds.\n[DEBUG] 2022-10-03 09:46:39,872 __bs: MainProcess Chudnovsky ... 107,000,000 iterations and 1299.33 seconds.\n[DEBUG] 2022-10-03 09:46:48,948 __bs: MainProcess Chudnovsky ... 108,000,000 iterations and 1308.41 seconds.\n[DEBUG] 2022-10-03 09:46:54,611 __bs: MainProcess Chudnovsky ... 109,000,000 iterations and 1314.07 seconds.\n[DEBUG] 2022-10-03 09:47:01,727 __bs: MainProcess Chudnovsky ... 110,000,000 iterations and 1321.18 seconds.\n[DEBUG] 2022-10-03 09:47:14,525 __bs: MainProcess Chudnovsky ... 111,000,000 iterations and 1333.98 seconds.\n[DEBUG] 2022-10-03 09:47:21,682 __bs: MainProcess Chudnovsky ... 112,000,000 iterations and 1341.14 seconds.\n[DEBUG] 2022-10-03 09:47:30,610 __bs: MainProcess Chudnovsky ... 113,000,000 iterations and 1350.07 seconds.\n[DEBUG] 2022-10-03 09:47:37,176 __bs: MainProcess Chudnovsky ... 114,000,000 iterations and 1356.63 seconds.\n[DEBUG] 2022-10-03 09:47:59,642 __bs: MainProcess Chudnovsky ... 115,000,000 iterations and 1379.10 seconds.\n[DEBUG] 2022-10-03 09:48:06,702 __bs: MainProcess Chudnovsky ... 116,000,000 iterations and 1386.16 seconds.\n[DEBUG] 2022-10-03 09:48:15,483 __bs: MainProcess Chudnovsky ... 117,000,000 iterations and 1394.94 seconds.\n[DEBUG] 2022-10-03 09:48:22,537 __bs: MainProcess Chudnovsky ... 118,000,000 iterations and 1401.99 seconds.\n[DEBUG] 2022-10-03 09:48:35,714 __bs: MainProcess Chudnovsky ... 119,000,000 iterations and 1415.17 seconds.\n[DEBUG] 2022-10-03 09:48:41,321 __bs: MainProcess Chudnovsky ... 120,000,000 iterations and 1420.78 seconds.\n[DEBUG] 2022-10-03 09:48:48,408 __bs: MainProcess Chudnovsky ... 121,000,000 iterations and 1427.87 seconds.\n[DEBUG] 2022-10-03 09:48:57,138 __bs: MainProcess Chudnovsky ... 122,000,000 iterations and 1436.60 seconds.\n[DEBUG] 2022-10-03 09:49:04,328 __bs: MainProcess Chudnovsky ... 123,000,000 iterations and 1443.79 seconds.\n[DEBUG] 2022-10-03 09:49:46,274 __bs: MainProcess Chudnovsky ... 124,000,000 iterations and 1485.73 seconds.\n[DEBUG] 2022-10-03 09:49:52,833 __bs: MainProcess Chudnovsky ... 125,000,000 iterations and 1492.29 seconds.\n[DEBUG] 2022-10-03 09:50:01,786 __bs: MainProcess Chudnovsky ... 126,000,000 iterations and 1501.24 seconds.\n[DEBUG] 2022-10-03 09:50:08,975 __bs: MainProcess Chudnovsky ... 127,000,000 iterations and 1508.43 seconds.\n[DEBUG] 2022-10-03 09:50:21,850 __bs: MainProcess Chudnovsky ... 128,000,000 iterations and 1521.31 seconds.\n[DEBUG] 2022-10-03 09:50:28,962 __bs: MainProcess Chudnovsky ... 129,000,000 iterations and 1528.42 seconds.\n[DEBUG] 2022-10-03 09:50:34,594 __bs: MainProcess Chudnovsky ... 130,000,000 iterations and 1534.05 seconds.\n[DEBUG] 2022-10-03 09:50:43,647 __bs: MainProcess Chudnovsky ... 131,000,000 iterations and 1543.10 seconds.\n[DEBUG] 2022-10-03 09:50:50,724 __bs: MainProcess Chudnovsky ... 132,000,000 iterations and 1550.18 seconds.\n[DEBUG] 2022-10-03 09:51:12,742 __bs: MainProcess Chudnovsky ... 133,000,000 iterations and 1572.20 seconds.\n[DEBUG] 2022-10-03 09:51:19,799 __bs: MainProcess Chudnovsky ... 134,000,000 iterations and 1579.26 seconds.\n[DEBUG] 2022-10-03 09:51:28,824 __bs: MainProcess Chudnovsky ... 135,000,000 iterations and 1588.28 seconds.\n[DEBUG] 2022-10-03 09:51:35,324 __bs: MainProcess Chudnovsky ... 136,000,000 iterations and 1594.78 seconds.\n[DEBUG] 2022-10-03 09:51:48,419 __bs: MainProcess Chudnovsky ... 137,000,000 iterations and 1607.88 seconds.\n[DEBUG] 2022-10-03 09:51:55,634 __bs: MainProcess Chudnovsky ... 138,000,000 iterations and 1615.09 seconds.\n[DEBUG] 2022-10-03 09:52:04,435 __bs: MainProcess Chudnovsky ... 139,000,000 iterations and 1623.89 seconds.\n[DEBUG] 2022-10-03 09:52:11,583 __bs: MainProcess Chudnovsky ... 140,000,000 iterations and 1631.04 seconds.\n[DEBUG] 2022-10-03 09:52:17,222 __bs: MainProcess Chudnovsky ... 141,000,000 iterations and 1636.68 seconds.\n[DEBUG] 2022-10-03 10:02:43,939 compute: MainProcess Chudnovsky brothers 1988 \n π = (Q(0, N) / 12T(0, N) + 12AQ(0, N))**(C**(3/2))\n calulation Done! 141,027,339 iterations and 2263.39 seconds.\n[INFO] 2022-10-03 10:09:07,119 <module>: MainProcess Last 5 digits of π were 45519 as expected at offset 999,999,995\n[INFO] 2022-10-03 10:09:07,119 <module>: MainProcess Calculated π to 1,000,000,000 digits using a formula of:\n 10 Chudnovsky brothers 1988 \n π = (Q(0, N) / 12T(0, N) + 12AQ(0, N))**(C**(3/2))\n \n[INFO] 2022-10-03 10:09:07,120 <module>: MainProcess Calculation took 141,027,339 iterations and 0:44:06.398345.\n</code></pre>\n<p><strong>math_pi.pi(b = 1000000)</strong>\nis faster to a million. About 40 times faster. But it cannot go to a Billion. 1 Million is the most digits.</p>\n<p>The GMPY Builtin looks like:</p>\n<pre><code>python pi-pourri.py -v -d 1,000,000,000 -a 11\n[INFO] 2022-10-03 14:33:34,729 <module>: MainProcess Computing π to 1,000,000,000 digits.\n[DEBUG] 2022-10-03 14:33:34,729 compute: MainProcess Starting const_pi() function from the gmpy2 library formula to 1,000,000,000 decimal places\n[DEBUG] 2022-10-03 15:46:46,575 compute: MainProcess const_pi() function from the gmpy2 library calulation Done! 1 iterations and 4391.85 seconds.\n[INFO] 2022-10-03 15:46:46,575 <module>: MainProcess Last 5 digits of π were 45519 as expected at offset 999,999,995\n[INFO] 2022-10-03 15:46:46,575 <module>: MainProcess Calculated π to 1,000,000,000 digits using a formula of:\n 11 const_pi() function from the gmpy2 library \n[INFO] 2022-10-03 15:46:46,575 <module>: MainProcess Calculation took 1 iterations and 1:13:11.845652.\n</code></pre>\n<p>The MPmath Builtin is almost as fast. About 12% (6 minutes) slower:</p>\n<pre><code>python pi-pourri.py -v -a 12 -d 1,000,000,000 \n[INFO] 2022-10-04 09:10:37,085 <module>: MainProcess Computing π to 1,000,000,000 digits.\n[DEBUG] 2022-10-04 09:10:37,085 compute: MainProcess Starting mp.pi() function from the mpmath library formula to 1,000,000,000 decimal places\n[DEBUG] 2022-10-04 10:01:25,321 compute: MainProcess mp.pi() function from the mpmath library calulation Done! 1 iterations and 3048.22 seconds.\n[INFO] 2022-10-04 10:01:25,338 <module>: MainProcess Last 5 digits of π were 45519 as expected at offset 999,999,995\n[INFO] 2022-10-04 10:01:25,340 <module>: MainProcess Calculated π to 1,000,000,000 digits using a formula of:\n 12 mp.pi() function from the mpmath library \n[INFO] 2022-10-04 10:01:25,343 <module>: MainProcess Calculation took 1 iterations and 0:50:48.250337.\n</code></pre>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/19",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13/"
] | I'm looking for the fastest way to obtain the value of π, as a personal challenge. More specifically, I'm using ways that don't involve using `#define` constants like `M_PI`, or hard-coding the number in.
The program below tests the various ways I know of. The inline assembly version is, in theory, the fastest option, though clearly not portable. I've included it as a baseline to compare against the other versions. In my tests, with built-ins, the `4 * atan(1)` version is fastest on GCC 4.2, because it auto-folds the `atan(1)` into a constant. With `-fno-builtin` specified, the `atan2(0, -1)` version is fastest.
Here's the main testing program (`pitimes.c`):
```c
#include <math.h>
#include <stdio.h>
#include <time.h>
#define ITERS 10000000
#define TESTWITH(x) { \
diff = 0.0; \
time1 = clock(); \
for (i = 0; i < ITERS; ++i) \
diff += (x) - M_PI; \
time2 = clock(); \
printf("%s\t=> %e, time => %f\n", #x, diff, diffclock(time2, time1)); \
}
static inline double
diffclock(clock_t time1, clock_t time0)
{
return (double) (time1 - time0) / CLOCKS_PER_SEC;
}
int
main()
{
int i;
clock_t time1, time2;
double diff;
/* Warmup. The atan2 case catches GCC's atan folding (which would
* optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin
* is not used. */
TESTWITH(4 * atan(1))
TESTWITH(4 * atan2(1, 1))
#if defined(__GNUC__) && (defined(__i386__) || defined(__amd64__))
extern double fldpi();
TESTWITH(fldpi())
#endif
/* Actual tests start here. */
TESTWITH(atan2(0, -1))
TESTWITH(acos(-1))
TESTWITH(2 * asin(1))
TESTWITH(4 * atan2(1, 1))
TESTWITH(4 * atan(1))
return 0;
}
```
And the inline assembly stuff (`fldpi.c`) that will only work for x86 and x64 systems:
```c
double
fldpi()
{
double pi;
asm("fldpi" : "=t" (pi));
return pi;
}
```
And a build script that builds all the configurations I'm testing (`build.sh`):
```
#!/bin/sh
gcc -O3 -Wall -c -m32 -o fldpi-32.o fldpi.c
gcc -O3 -Wall -c -m64 -o fldpi-64.o fldpi.c
gcc -O3 -Wall -ffast-math -m32 -o pitimes1-32 pitimes.c fldpi-32.o
gcc -O3 -Wall -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm
gcc -O3 -Wall -ffast-math -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm
gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm
```
Apart from testing between various compiler flags (I've compared 32-bit against 64-bit too because the optimizations are different), I've also tried switching the order of the tests around. But still, the `atan2(0, -1)` version still comes out on top every time. | The [Monte Carlo method](http://en.wikipedia.org/wiki/Monte_Carlo_method), as mentioned, applies some great concepts but it is, clearly, not the fastest, not by a long shot, not by any reasonable measure. Also, it all depends on what kind of accuracy you are looking for. The fastest π I know of is the one with the digits hard coded. Looking at [Pi](http://functions.wolfram.com/Constants/Pi/ "pi") and [Pi[PDF]](http://functions.wolfram.com/PDF/Pi.pdf "pi formulas"), there are a lot of formulae.
Here is a method that converges quickly — about 14 digits per iteration. [PiFast](http://numbers.computation.free.fr/Constants/PiProgram/pifast.html "PiFast"), the current fastest application, uses this formula with the FFT. I'll just write the formula, since the code is straightforward. This formula was almost found by [Ramanujan and discovered by Chudnovsky](http://numbers.computation.free.fr/Constants/Pi/piramanujan.html). It is actually how he calculated several billion digits of the number — so it isn't a method to disregard. The formula will overflow quickly and, since we are dividing factorials, it would be advantageous then to delay such calculations to remove terms.
![enter image description here](https://i.stack.imgur.com/aQMkk.gif)
![enter image description here](https://i.stack.imgur.com/2y2l9.gif)
where,
![enter image description here](https://i.stack.imgur.com/QqVnB.gif)
Below is the [Brent–Salamin algorithm](http://mathworld.wolfram.com/Brent-SalaminFormula.html "Brent Salamin Formula"). Wikipedia mentions that when **a** and **b** are "close enough" then **(a + b)² / 4t** will be an approximation of π. I'm not sure what "close enough" means, but from my tests, one iteration got 2 digits, two got 7, and three had 15, of course this is with doubles, so it might have an error based on its representation and the *true* calculation could be more accurate.
```
let pi_2 iters =
let rec loop_ a b t p i =
if i = 0 then a,b,t,p
else
let a_n = (a +. b) /. 2.0
and b_n = sqrt (a*.b)
and p_n = 2.0 *. p in
let t_n = t -. (p *. (a -. a_n) *. (a -. a_n)) in
loop_ a_n b_n t_n p_n (i - 1)
in
let a,b,t,p = loop_ (1.0) (1.0 /. (sqrt 2.0)) (1.0/.4.0) (1.0) iters in
(a +. b) *. (a +. b) /. (4.0 *. t)
```
Lastly, how about some pi golf (800 digits)? 160 characters!
```
int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5;for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);}
``` |
25 | <p>I'm having issues getting the C sockets API to work properly in C++ on z/OS.</p>
<p>Although I am including <code>sys/socket.h</code>, I still get compile time errors telling me that <code>AF_INET</code> is not defined.</p>
<p>Am I missing something obvious, or is this related to the fact that being on z/OS makes my problems much more complicated?</p>
<p>I discovered that there is an <code>#ifdef</code> that I'm hitting. Apparently z/OS isn't happy unless I define which "type" of sockets I'm using with:</p>
<pre><code>#define _OE_SOCKETS
</code></pre>
<p>Now, I personally have no idea what this <code>_OE_SOCKETS</code> is actually for, so if any z/OS sockets programmers are out there (all 3 of you), perhaps you could give me a rundown of how this all works?</p>
<p>Test App</p>
<pre><code>#include <sys/socket.h>
int main()
{
return AF_INET;
}
</code></pre>
<p>Compile/Link Output:</p>
<pre><code>cxx -Wc,xplink -Wl,xplink -o inet_test inet.C
"./inet.C", line 5.16: CCN5274 (S) The name lookup for "AF_INET" did not find a declaration.
CCN0797(I) Compilation failed for file ./inet.C. Object file not created.
</code></pre>
<p>A check of sys/sockets.h does include the definition I need, and as far as I can tell, it is not being blocked by any <code>#ifdef</code> statements.</p>
<p>I have however noticed it contains the following:</p>
<pre><code>#ifdef __cplusplus
extern "C" {
#endif
</code></pre>
<p>which encapsulates basically the whole file? Not sure if it matters.</p>
| [
{
"answer_id": 30,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": false,
"text": "<p>I've had no trouble using the BSD sockets API in C++, in GNU/Linux. Here's the sample program I used:</p>\n\n<pre><code>#include <sys/socket.h>\n\nint\nmain()\n{\n return AF_INET;\n}\n</code></pre>\n\n<p>So my take on this is that z/OS is probably the complicating factor here, however, because I've never used z/OS before, much less programmed in it, I can't say this definitively. :-P</p>\n"
},
{
"answer_id": 73,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": false,
"text": "<p>@Jax: The <code>extern \"C\"</code> thing matters, very very much. If a header file doesn't have one, then (unless it's a C++-only header file), you would have to enclose your <code>#include</code> with it:</p>\n\n<pre><code>extern \"C\" {\n#include <sys/socket.h>\n// include other similarly non-compliant header files\n}\n</code></pre>\n\n<p>Basically, anytime where a C++ program wants to link to C-based facilities, the <code>extern \"C\"</code> is vital. In practical terms, it means that the names used in external references will not be mangled, like normal C++ names would. <a href=\"http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html\" rel=\"noreferrer\">Reference.</a></p>\n"
},
{
"answer_id": 35029,
"author": "David Bryson",
"author_id": 3663,
"author_profile": "https://Stackoverflow.com/users/3663",
"pm_score": 4,
"selected": false,
"text": "<p>DISCLAIMER: I am not a C++ programmer, however I know C really well. I\nadapated these calls from some C code I have.</p>\n\n<p>Also markdown put these strange _ as my underscores.</p>\n\n<p>You should just be able to write an abstraction class around the C sockets with something like this:</p>\n\n<pre><code>class my_sock {\n private int sock;\n private int socket_type;\n private socklen_t sock_len;\n private struct sockaddr_in server_addr;\n public char *server_ip;\n public unsigned short server_port;\n};\n</code></pre>\n\n<p>Then have methods for opening, closing, and sending packets down the socket.</p>\n\n<p>For example, the open call might look something like this:</p>\n\n<pre><code>int my_socket_connect()\n{\n int return_code = 0;\n\n if ( this->socket_type != CLIENT_SOCK ) {\n cout << \"This is a not a client socket!\\n\";\n return -1;\n }\n\n return_code = connect( this->local_sock, (struct sockaddr *) &this->server_addr, sizeof(this->server_addr));\n\n if( return_code < 0 ) {\n cout << \"Connect() failure! %s\\n\", strerror(errno);\n return return_code;\n }\n\n return return_code;\n}\n</code></pre>\n"
},
{
"answer_id": 48248,
"author": "Federico",
"author_id": 4981,
"author_profile": "https://Stackoverflow.com/users/4981",
"pm_score": 5,
"selected": false,
"text": "<p>You may want to take a look to <a href=\"http://sourceforge.net/projects/cpp-sockets/\" rel=\"noreferrer\">cpp-sockets</a>, a C++ wrapper for the sockets system calls. It works with many operating systems (Win32, POSIX, Linux, *BSD). I don't think it will work with z/OS but you can take a look at the include files it uses and you'll have many examples of tested code that works well on other OSs.</p>\n"
},
{
"answer_id": 110917,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 5,
"selected": false,
"text": "<p>So try</p>\n\n<pre><code>#define _OE_SOCKETS\n</code></pre>\n\n<p>before you include sys/socket.h</p>\n"
},
{
"answer_id": 193478,
"author": "Fabio Ceconello",
"author_id": 8999,
"author_profile": "https://Stackoverflow.com/users/8999",
"pm_score": 5,
"selected": false,
"text": "<p>The _OE_SOCKETS appears to be simply to enable/disable the definition of socket-related symbols. It is not uncommon in some libraries to have a bunch of macros to do that, to assure that you're not compiling/linking parts not needed. The macro is not standard in other sockets implementations, it appears to be something specific to z/OS.</p>\n\n<p>Take a look at this page:<br>\n<a href=\"http://publib.boulder.ibm.com/infocenter/zvm/v5r3/index.jsp?topic=/com.ibm.zvm.v53.kiml0/sktnew.htm\" rel=\"noreferrer\">Compiling and Linking a z/VM C Sockets Program</a></p>\n"
},
{
"answer_id": 867088,
"author": "Robert Groves",
"author_id": 3534,
"author_profile": "https://Stackoverflow.com/users/3534",
"pm_score": 5,
"selected": false,
"text": "<p>See the <em>Using z/OS UNIX System Services sockets</em> section in the z/OS XL C/C++ Programming Guide. Make sure you're including the necessary header files and using the appropriate #defines.</p>\n\n<p>The link to the doc has changed over the years, but you should be able to get to it easily enough by finding the current location of the <a href=\"http://ibm.com/support/entry/portal/documentation\" rel=\"noreferrer\">Support & Downloads section</a> on <a href=\"http://www.ibm.com/\" rel=\"noreferrer\">ibm.com</a> and searching the documentation by title.</p>\n"
},
{
"answer_id": 1443907,
"author": "Anthony Giorgio",
"author_id": 9816,
"author_profile": "https://Stackoverflow.com/users/9816",
"pm_score": 8,
"selected": true,
"text": "<p>Keep a copy of the IBM manuals handy:</p>\n\n<ul>\n<li><a href=\"http://publibz.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/CBCPG1A0/CCONTENTS?DT=20090606065305\" rel=\"noreferrer\"> z/OS V1R11.0 XL C/C++ Programming Guide</a> </li>\n<li><a href=\"http://publibz.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/EDCLB1A0/CCONTENTS?DT=20090607203246\" rel=\"noreferrer\"> z/OS V1R11.0 XL C/C++ Run-Time Library Reference</a> </li>\n</ul>\n\n<p>The IBM publications are generally very good, but you need to get used to their format, as well as knowing where to look for an answer. You'll find quite often that a feature that you want to use is guarded by a \"feature test macro\"</p>\n\n<p>You should ask your friendly system programmer to install the <a href=\"http://www-03.ibm.com/servers/eserver/zseries/zos/le/manpgs.html\" rel=\"noreferrer\">XL C/C++ Run-Time Library Reference: Man Pages\n</a> on your system. Then you can do things like \"man connect\" to pull up the man page for the socket connect() API. When I do that, this is what I see:</p>\n\n<p>FORMAT</p>\n\n<p>X/Open</p>\n\n<pre><code>#define _XOPEN_SOURCE_EXTENDED 1\n#include <sys/socket.h>\n\nint connect(int socket, const struct sockaddr *address, socklen_t address_len);\n</code></pre>\n\n<p>Berkeley Sockets</p>\n\n<pre><code>#define _OE_SOCKETS\n#include <sys/types.h>\n#include <sys/socket.h>\n\nint connect(int socket, struct sockaddr *address, int address_len);\n</code></pre>\n"
},
{
"answer_id": 5626132,
"author": "Hope T. Helps",
"author_id": 702754,
"author_profile": "https://Stackoverflow.com/users/702754",
"pm_score": 4,
"selected": false,
"text": "<p>Use the following c89 flag:</p>\n<pre><code> -D_OE_SOCKETS\n</code></pre>\n<p>Example:</p>\n<pre><code> bash-2.03$ c89 -D_OE_SOCKETS [filename].c\n</code></pre>\n<p>For more information look for c89 Options in the z/OS XLC/C++ User's Guide.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/25",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23/"
] | I'm having issues getting the C sockets API to work properly in C++ on z/OS.
Although I am including `sys/socket.h`, I still get compile time errors telling me that `AF_INET` is not defined.
Am I missing something obvious, or is this related to the fact that being on z/OS makes my problems much more complicated?
I discovered that there is an `#ifdef` that I'm hitting. Apparently z/OS isn't happy unless I define which "type" of sockets I'm using with:
```
#define _OE_SOCKETS
```
Now, I personally have no idea what this `_OE_SOCKETS` is actually for, so if any z/OS sockets programmers are out there (all 3 of you), perhaps you could give me a rundown of how this all works?
Test App
```
#include <sys/socket.h>
int main()
{
return AF_INET;
}
```
Compile/Link Output:
```
cxx -Wc,xplink -Wl,xplink -o inet_test inet.C
"./inet.C", line 5.16: CCN5274 (S) The name lookup for "AF_INET" did not find a declaration.
CCN0797(I) Compilation failed for file ./inet.C. Object file not created.
```
A check of sys/sockets.h does include the definition I need, and as far as I can tell, it is not being blocked by any `#ifdef` statements.
I have however noticed it contains the following:
```
#ifdef __cplusplus
extern "C" {
#endif
```
which encapsulates basically the whole file? Not sure if it matters. | Keep a copy of the IBM manuals handy:
* [z/OS V1R11.0 XL C/C++ Programming Guide](http://publibz.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/CBCPG1A0/CCONTENTS?DT=20090606065305)
* [z/OS V1R11.0 XL C/C++ Run-Time Library Reference](http://publibz.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/EDCLB1A0/CCONTENTS?DT=20090607203246)
The IBM publications are generally very good, but you need to get used to their format, as well as knowing where to look for an answer. You'll find quite often that a feature that you want to use is guarded by a "feature test macro"
You should ask your friendly system programmer to install the [XL C/C++ Run-Time Library Reference: Man Pages](http://www-03.ibm.com/servers/eserver/zseries/zos/le/manpgs.html) on your system. Then you can do things like "man connect" to pull up the man page for the socket connect() API. When I do that, this is what I see:
FORMAT
X/Open
```
#define _XOPEN_SOURCE_EXTENDED 1
#include <sys/socket.h>
int connect(int socket, const struct sockaddr *address, socklen_t address_len);
```
Berkeley Sockets
```
#define _OE_SOCKETS
#include <sys/types.h>
#include <sys/socket.h>
int connect(int socket, struct sockaddr *address, int address_len);
``` |
34 | <p>How do I forcefully unload a <code>ByteArray</code> from memory using ActionScript 3?</p>
<p>I have tried the following:</p>
<pre><code>// First non-working solution
byteArray.length = 0;
byteArray = new ByteArray();
// Second non-working solution
for ( var i:int=0; i < byteArray.length; i++ ) {
byteArray[i] = null;
}
</code></pre>
| [
{
"answer_id": 52,
"author": "Jax",
"author_id": 23,
"author_profile": "https://Stackoverflow.com/users/23",
"pm_score": 4,
"selected": false,
"text": "<p>Have a look at this article</p>\n\n<p><a href=\"http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html\" rel=\"noreferrer\">http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html</a></p>\n\n<p>IANA actionscript programmer, however the feeling I'm getting is that, because the garbage collector might not run when you want it to.</p>\n\n<p>Hence\n<a href=\"http://www.craftymind.com/2008/04/09/kick-starting-the-garbage-collector-in-actionscript-3-with-air/\" rel=\"noreferrer\">http://www.craftymind.com/2008/04/09/kick-starting-the-garbage-collector-in-actionscript-3-with-air/</a></p>\n\n<p>So I'd recommend trying out their collection code and see if it helps</p>\n\n<pre><code>private var gcCount:int;\nprivate function startGCCycle():void{\n gcCount = 0;\n addEventListener(Event.ENTER_FRAME, doGC);\n}\nprivate function doGC(evt:Event):void{\n flash.system.System.gc();\n if(++gcCount > 1){\n removeEventListener(Event.ENTER_FRAME, doGC);\n setTimeout(lastGC, 40);\n }\n}\nprivate function lastGC():void{\n flash.system.System.gc();\n}\n</code></pre>\n"
},
{
"answer_id": 53,
"author": "Karl Seguin",
"author_id": 34,
"author_profile": "https://Stackoverflow.com/users/34",
"pm_score": 5,
"selected": false,
"text": "<p>(I'm not positive about this, but...)</p>\n<p>AS3 uses a non-deterministic garbage collection which means that dereferenced memory will be freed up whenever the runtime feels like it (typically not unless there's a reason to run, since it's an expensive operation to execute). This is the same approach used by most modern garbage collecting languages (like C# and Java as well).</p>\n<p>Assuming there are no other references to the memory pointed to by <code>byteArray</code> or the items within the array itself, the memory will be freed at some point after you exit the scope where <code>byteArray</code> is declared.</p>\n<p>You can force a garbage collection, though you really shouldn't. If you do, do it only for testing. If you do it in production, you'll hurt performance much more than help it.</p>\n<p>To force a GC, try (yes, twice):</p>\n<pre><code>flash.system.System.gc();\nflash.system.System.gc();\n</code></pre>\n<p><a href=\"http://www.craftymind.com/2008/04/09/kick-starting-the-garbage-collector-in-actionscript-3-with-air/\" rel=\"nofollow noreferrer\">You can read more here</a>.</p>\n"
},
{
"answer_id": 60,
"author": "Redbaron",
"author_id": 41,
"author_profile": "https://Stackoverflow.com/users/41",
"pm_score": 4,
"selected": false,
"text": "<p>Unfortunately when it comes to memory management in <em>Flash/actionscript</em> there isn't a whole lot you can do. ActionScript was designed to be easy to use (so they didn't want people to have to worry about memory management)</p>\n\n<p>The following is a workaround, instead of creating a <code>ByteArray</code> variable try this.</p>\n\n<pre><code>var byteObject:Object = new Object();\n\nbyteObject.byteArray = new ByteArray();\n\n...\n\n//Then when you are finished delete the variable from byteObject\ndelete byteObject.byteArray;\n</code></pre>\n\n<p>Where <code>byteArray</code> is a dynamic property of <code>byteObject</code>, you can free the memory that was allocated for it.</p>\n"
},
{
"answer_id": 81,
"author": "Redbaron",
"author_id": 41,
"author_profile": "https://Stackoverflow.com/users/41",
"pm_score": 4,
"selected": false,
"text": "<p>I believe you have answered your own question.</p>\n<p><code>System.totalMemory</code> gives you the total amount of memory being "used", not allocated. It is accurate that your application may only be using 20 MB, but it has 5 MB that is free for future allocations.</p>\n<p>I'm not sure whether the Adobe docs would shed light on the way that it manages memory.</p>\n"
},
{
"answer_id": 11340,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 5,
"selected": false,
"text": "<p>I don't think you have anything to worry about. If <code>System.totalMemory</code> goes down you can relax. It may very well be the OS that doesn't reclaim the newly freed memory (in anticipation of the next time Flash Player will ask for more memory).</p>\n\n<p>Try doing something else that is very memory intensive and I'm sure that you'll notice that the memory allocated to Flash Player will decrease and be used for the other process instead.</p>\n\n<p>As I've understood it, memory management in modern OS's isn't intuitive from the perspective of looking at the amounts allocated to each process, or even the total amount allocated.</p>\n\n<p>When I've used my Mac for 5 minutes 95% of my 3 GB RAM is used, and it will stay that way, it never goes down. That's just the way the OS handles memory.</p>\n\n<p>As long as it's not needed elsewhere even processes that have quit still have memory assigned to them (this can make them launch quicker the next time, for example).</p>\n"
},
{
"answer_id": 81683,
"author": "Pedro",
"author_id": 15524,
"author_profile": "https://Stackoverflow.com/users/15524",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n<p>So, if I load say 20MB from MySQL, in the Task Manager the RAM for the application goes up by about 25MB. Then when I close the connection and try to dispose the ByteArray, the RAM never frees up. However, if I use System.totalMemory, flash player shows that the memory is being released, which is not the case.</p>\n<p>Is the flash player doing something like Java and reserving heap space and not releasing it until the app quits?</p>\n</blockquote>\n<p>Well yes and no, as you might have read from countless blog posts that the GC in AVM2 is optimistic and will work its own mysterious ways. So it does work a bit like Java and tries to reserve heap space. However if you let it long enough and start doing other operations that are consuming some significant memory, it will free that previous space. You can see this using the profiler overnight with some tests running on top of your app.</p>\n"
},
{
"answer_id": 175520,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>So, if I load say 20MB from MySQL, in the Task Manager the RAM for the application goes up by about 25MB. Then when I close the connection and try to dispose the ByteArray, the RAM never frees up. However, if I use System.totalMemory, flash player shows that the memory is being released, which is not the case.</p>\n</blockquote>\n\n<p>The player is \"releasing\" the memory. If you minimize the window and restore it you should see that the memeory is now much closer to what System.totalMemory shows.</p>\n\n<p>You might also be interested in using FlexBuilder's profiling tools which can show you if you really have memory leaks.</p>\n"
},
{
"answer_id": 74515081,
"author": "Manish",
"author_id": 3958207,
"author_profile": "https://Stackoverflow.com/users/3958207",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>bytearray.clear()</code></p>\n<p>As per the <a href=\"https://airsdk.dev/reference/actionscript/3.0/\" rel=\"nofollow noreferrer\">Language Reference</a></p>\n<p>this</p>\n<blockquote>\n<p>Clears the contents of the byte array and resets the length and position properties to 0. Calling this method explicitly frees up the memory used by the ByteArray instance.</p>\n</blockquote>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/34",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How do I forcefully unload a `ByteArray` from memory using ActionScript 3?
I have tried the following:
```
// First non-working solution
byteArray.length = 0;
byteArray = new ByteArray();
// Second non-working solution
for ( var i:int=0; i < byteArray.length; i++ ) {
byteArray[i] = null;
}
``` | (I'm not positive about this, but...)
AS3 uses a non-deterministic garbage collection which means that dereferenced memory will be freed up whenever the runtime feels like it (typically not unless there's a reason to run, since it's an expensive operation to execute). This is the same approach used by most modern garbage collecting languages (like C# and Java as well).
Assuming there are no other references to the memory pointed to by `byteArray` or the items within the array itself, the memory will be freed at some point after you exit the scope where `byteArray` is declared.
You can force a garbage collection, though you really shouldn't. If you do, do it only for testing. If you do it in production, you'll hurt performance much more than help it.
To force a GC, try (yes, twice):
```
flash.system.System.gc();
flash.system.System.gc();
```
[You can read more here](http://www.craftymind.com/2008/04/09/kick-starting-the-garbage-collector-in-actionscript-3-with-air/). |
36 | <p>How can I monitor an SQL Server database for changes to a table without using triggers or modifying the structure of the database in any way? My preferred programming environment is <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> and C#.</p>
<p>I'd like to be able to support any <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#Genesis" rel="noreferrer">SQL Server 2000</a> SP4 or newer. My application is a bolt-on data visualization for another company's product. Our customer base is in the thousands, so I don't want to have to put in requirements that we modify the third-party vendor's table at every installation.</p>
<p>By <em>"changes to a table"</em> I mean changes to table data, not changes to table structure.</p>
<p>Ultimately, I would like the change to trigger an event in my application, instead of having to check for changes at an interval.</p>
<hr>
<p>The best course of action given my requirements (no triggers or schema modification, SQL Server 2000 and 2005) seems to be to use the <code>BINARY_CHECKSUM</code> function in <a href="http://en.wikipedia.org/wiki/Transact-SQL" rel="noreferrer">T-SQL</a>. The way I plan to implement is this:</p>
<p>Every X seconds run the following query:</p>
<pre><code>SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*))
FROM sample_table
WITH (NOLOCK);
</code></pre>
<p>And compare that against the stored value. If the value has changed, go through the table row by row using the query:</p>
<pre><code>SELECT row_id, BINARY_CHECKSUM(*)
FROM sample_table
WITH (NOLOCK);
</code></pre>
<p>And compare the returned checksums against stored values.</p>
| [
{
"answer_id": 51,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 5,
"selected": false,
"text": "<p>Why don't you want to use triggers? They are a good thing if you use them correctly. If you use them as a way to enforce referential integrity that is when they go from good to bad. But if you use them for monitoring, they are not really considered taboo.</p>\n"
},
{
"answer_id": 82,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 4,
"selected": false,
"text": "<p>Have a DTS job (or a job that is started by a windows service) that runs at a given interval. Each time it is run, it gets information about the given table by using the system <a href=\"http://msdn.microsoft.com/en-us/library/ms186778.aspx\" rel=\"noreferrer\">INFORMATION_SCHEMA</a> tables, and records this data in the data repository. Compare the data returned regarding the structure of the table with the data returned the previous time. If it is different, then you know that the structure has changed.</p>\n\n<p>Example query to return information regarding all of the columns in table ABC (ideally listing out just the columns from the INFORMATION_SCHEMA table that you want, instead of using *select ** like I do here):</p>\n\n<pre><code>select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'ABC'\n</code></pre>\n\n<p>You would monitor different columns and INFORMATION_SCHEMA views depending on how exactly you define \"changes to a table\".</p>\n"
},
{
"answer_id": 352,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 8,
"selected": true,
"text": "<p>Take a look at the CHECKSUM command:</p>\n\n<pre><code>SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK);\n</code></pre>\n\n<p>That will return the same number each time it's run as long as the table contents haven't changed. See my post on this for more information:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa258245(SQL.80).aspx\" rel=\"noreferrer\">CHECKSUM</a></p>\n\n<p>Here's how I used it to rebuild cache dependencies when tables changed:<br>\n<a href=\"http://weblogs.asp.net/jgalloway/archive/2005/05/07/406056.aspx\" rel=\"noreferrer\">ASP.NET 1.1 database cache dependency (without triggers)</a></p>\n"
},
{
"answer_id": 695,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 4,
"selected": false,
"text": "<p>How often do you need to check for changes and how large (in terms of row size) are the tables in the database? If you use the <code>CHECKSUM_AGG(BINARY_CHECKSUM(*))</code> method suggested by John, it will scan every row of the specified table. The <code>NOLOCK</code> hint helps, but on a large database, you are still hitting every row. You will also need to store the checksum for every row so that you tell one has changed.</p>\n\n<p>Have you considered going at this from a different angle? If you do not want to modify the schema to add triggers, (which makes a sense, it's not your database), have you considered working with the application vendor that does make the database? </p>\n\n<p>They could implement an API that provides a mechanism for notifying accessory apps that data has changed. It could be as simple as writing to a notification table that lists what table and which row were modified. That could be implemented through triggers or application code. From your side, ti wouldn't matter, your only concern would be scanning the notification table on a periodic basis. The performance hit on the database would be far less than scanning every row for changes.</p>\n\n<p>The hard part would be convincing the application vendor to implement this feature. Since this can be handles entirely through SQL via triggers, you could do the bulk of the work for them by writing and testing the triggers and then bringing the code to the application vendor. By having the vendor support the triggers, it prevent the situation where your adding a trigger inadvertently replaces a trigger supplied by the vendor.</p>\n"
},
{
"answer_id": 1778,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": false,
"text": "<p>Wild guess here: If you don't want to modify the third party's tables, Can you create a view and then put a trigger on that view?</p>\n"
},
{
"answer_id": 3009,
"author": "caryden",
"author_id": 313,
"author_profile": "https://Stackoverflow.com/users/313",
"pm_score": 4,
"selected": false,
"text": "<p>Unfortunately, I do not think that there is a clean way to do this in SQL2000. If you narrow your requirements to SQL Server 2005 (and later), then you are in business. You can use the <code>SQLDependency</code> class in <code>System.Data.SqlClient</code>. See <a href=\"http://msdn.microsoft.com/en-us/library/t9x04ed2.aspx\" rel=\"noreferrer\">Query Notifications in SQL Server (ADO.NET)</a>.</p>\n"
},
{
"answer_id": 5486054,
"author": "BitLauncher",
"author_id": 519971,
"author_profile": "https://Stackoverflow.com/users/519971",
"pm_score": 5,
"selected": false,
"text": "<p><b>Unfortunately CHECKSUM does not always work properly to detect changes</b>.</p>\n\n<p>It is only a primitive checksum and no cyclic redundancy check (CRC) calculation.</p>\n\n<p>Therefore you can't use it to detect all changes, e. g. symmetrical changes result in the same CHECKSUM!</p>\n\n<p>E. g. the solution with <code>CHECKSUM_AGG(BINARY_CHECKSUM(*))</code> will always deliver 0 for all 3 tables with different content:</p>\n\n<p><pre><code>\nSELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM \n(\n SELECT 1 as numA, 1 as numB\n UNION ALL\n SELECT 1 as numA, 1 as numB\n) q\n-- delivers 0!</p>\n\n<p>SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM \n(\n SELECT 1 as numA, 2 as numB\n UNION ALL\n SELECT 1 as numA, 2 as numB\n) q\n-- delivers 0!</p>\n\n<p>SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM \n(\n SELECT 0 as numA, 0 as numB\n UNION ALL\n SELECT 0 as numA, 0 as numB\n) q\n-- delivers 0!\n</pre></code></p>\n"
},
{
"answer_id": 24925434,
"author": "ECE",
"author_id": 1877309,
"author_profile": "https://Stackoverflow.com/users/1877309",
"pm_score": 3,
"selected": false,
"text": "<p>Check the last commit date. Every database has a history of when each commit is made. I believe its a standard of ACID compliance.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/36",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32/"
] | How can I monitor an SQL Server database for changes to a table without using triggers or modifying the structure of the database in any way? My preferred programming environment is [.NET](http://en.wikipedia.org/wiki/.NET_Framework) and C#.
I'd like to be able to support any [SQL Server 2000](http://en.wikipedia.org/wiki/Microsoft_SQL_Server#Genesis) SP4 or newer. My application is a bolt-on data visualization for another company's product. Our customer base is in the thousands, so I don't want to have to put in requirements that we modify the third-party vendor's table at every installation.
By *"changes to a table"* I mean changes to table data, not changes to table structure.
Ultimately, I would like the change to trigger an event in my application, instead of having to check for changes at an interval.
---
The best course of action given my requirements (no triggers or schema modification, SQL Server 2000 and 2005) seems to be to use the `BINARY_CHECKSUM` function in [T-SQL](http://en.wikipedia.org/wiki/Transact-SQL). The way I plan to implement is this:
Every X seconds run the following query:
```
SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*))
FROM sample_table
WITH (NOLOCK);
```
And compare that against the stored value. If the value has changed, go through the table row by row using the query:
```
SELECT row_id, BINARY_CHECKSUM(*)
FROM sample_table
WITH (NOLOCK);
```
And compare the returned checksums against stored values. | Take a look at the CHECKSUM command:
```
SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK);
```
That will return the same number each time it's run as long as the table contents haven't changed. See my post on this for more information:
[CHECKSUM](http://msdn.microsoft.com/en-us/library/aa258245(SQL.80).aspx)
Here's how I used it to rebuild cache dependencies when tables changed:
[ASP.NET 1.1 database cache dependency (without triggers)](http://weblogs.asp.net/jgalloway/archive/2005/05/07/406056.aspx) |
42 | <p>I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface. </p>
<p>How does one go about writing 'hooks' into their code so that plugins can attach to specific events?</p>
| [
{
"answer_id": 76,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 4,
"selected": false,
"text": "<p>I believe the easiest way would be to follow Jeff's own advice and have a look around the existing code. Try looking at WordPress, Drupal, Joomla, and other well-known PHP-based CMS to see how their API hooks look and feel. This way you can even get ideas you may have not thought of previously to make things a little more robust.</p>\n<p>A more direct answer would be to write general files that they would "include_once" into their file that would provide the usability they would need. This would be broken up into categories and NOT provided in one MASSIVE "hooks.php" file. Be careful though, because what ends up happening is that files that they include end up having more and more dependencies and functionality improves. Try to keep API dependencies low. I.E fewer files for them to include.</p>\n"
},
{
"answer_id": 77,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 8,
"selected": true,
"text": "<p>You could use an Observer pattern. A simple functional way to accomplish this:</p>\n\n<pre><code><?php\n\n/** Plugin system **/\n\n$listeners = array();\n\n/* Create an entry point for plugins */\nfunction hook() {\n global $listeners;\n\n $num_args = func_num_args();\n $args = func_get_args();\n\n if($num_args < 2)\n trigger_error(\"Insufficient arguments\", E_USER_ERROR);\n\n // Hook name should always be first argument\n $hook_name = array_shift($args);\n\n if(!isset($listeners[$hook_name]))\n return; // No plugins have registered this hook\n\n foreach($listeners[$hook_name] as $func) {\n $args = $func($args); \n }\n return $args;\n}\n\n/* Attach a function to a hook */\nfunction add_listener($hook, $function_name) {\n global $listeners;\n $listeners[$hook][] = $function_name;\n}\n\n/////////////////////////\n\n/** Sample Plugin **/\nadd_listener('a_b', 'my_plugin_func1');\nadd_listener('str', 'my_plugin_func2');\n\nfunction my_plugin_func1($args) {\n return array(4, 5);\n}\n\nfunction my_plugin_func2($args) {\n return str_replace('sample', 'CRAZY', $args[0]);\n}\n\n/////////////////////////\n\n/** Sample Application **/\n\n$a = 1;\n$b = 2;\n\nlist($a, $b) = hook('a_b', $a, $b);\n\n$str = \"This is my sample application\\n\";\n$str .= \"$a + $b = \".($a+$b).\"\\n\";\n$str .= \"$a * $b = \".($a*$b).\"\\n\";\n\n$str = hook('str', $str);\necho $str;\n?>\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>This is my CRAZY application\n4 + 5 = 9\n4 * 5 = 20\n</code></pre>\n\n<p><strong>Notes:</strong></p>\n\n<p>For this example source code, you must declare all your plugins before the actual source code that you want to be extendable. I've included an example of how to handle single or multiple values being passed to the plugin. The hardest part of this is writing the actual documentation which lists what arguments get passed to each hook.</p>\n\n<p>This is just one method of accomplishing a plugin system in PHP. There are better alternatives, I suggest you check out the WordPress Documentation for more information.</p>\n"
},
{
"answer_id": 147,
"author": "w-ll",
"author_id": 146637,
"author_profile": "https://Stackoverflow.com/users/146637",
"pm_score": 5,
"selected": false,
"text": "<p>The <em>hook</em> and <em>listener</em> method is the most commonly used, but there are other things you can do. Depending on the size of your app, and who your going to allow see the code (is this going to be a FOSS script, or something in house) will influence greatly how you want to allow plugins.</p>\n\n<p>kdeloach has a nice example, but his implementation and hook function is a little unsafe. I would ask for you to give more information of the nature of php app your writing, And how you see plugins fitting in. </p>\n\n<p>+1 to kdeloach from me.</p>\n"
},
{
"answer_id": 86433,
"author": "julz",
"author_id": 16536,
"author_profile": "https://Stackoverflow.com/users/16536",
"pm_score": 4,
"selected": false,
"text": "<p>There's a neat project called <a href=\"http://developer.yahoo.net/blog/archives/2007/10/r3_and_stickleb.html\" rel=\"noreferrer\">Stickleback</a> by Matt Zandstra at Yahoo that handles much of the work for handling plugins in PHP.</p>\n\n<p>It enforces the interface of a plugin class, supports a command line interface and isn't too hard to get up and running - especially if you read the cover story about it in the <a href=\"http://www.phparch.com\" rel=\"noreferrer\">PHP architect magazine</a>.</p>\n"
},
{
"answer_id": 86796,
"author": "THEMike",
"author_id": 7106,
"author_profile": "https://Stackoverflow.com/users/7106",
"pm_score": 4,
"selected": false,
"text": "<p>Good advice is to look how other projects have done it. Many call for having plugins installed and their \"name\" registered for services (like wordpress does) so you have \"points\" in your code where you call a function that identifies registered listeners and executes them. A standard OO design patter is the <a href=\"http://www.phppatterns.com/docs/design/observer_pattern\" rel=\"noreferrer\">Observer Pattern</a>, which would be a good option to implement in a truly object oriented PHP system.</p>\n\n<p>The <a href=\"http://framework.zend.com\" rel=\"noreferrer\">Zend Framework</a> makes use of many hooking methods, and is very nicely architected. That would be a good system to look at.</p>\n"
},
{
"answer_id": 136273,
"author": "andy.gurin",
"author_id": 22388,
"author_profile": "https://Stackoverflow.com/users/22388",
"pm_score": 5,
"selected": false,
"text": "<p>Here is an approach I've used, it's an attempt to copy from Qt signals/slots mechanism, a kind of Observer pattern.\nObjects can emit signals.\nEvery signal has an ID in the system - it's composed by sender's id + object name\nEvery signal can be binded to the receivers, which simply is a \"callable\"\nYou use a bus class to pass the signals to anybody interested in receiving them\nWhen something happens, you \"send\" a signal. \nBelow is and example implementation</p>\n\n<pre><code> <?php\n\nclass SignalsHandler {\n\n\n /**\n * hash of senders/signals to slots\n *\n * @var array\n */\n private static $connections = array();\n\n\n /**\n * current sender\n *\n * @var class|object\n */\n private static $sender;\n\n\n /**\n * connects an object/signal with a slot\n *\n * @param class|object $sender\n * @param string $signal\n * @param callable $slot\n */\n public static function connect($sender, $signal, $slot) {\n if (is_object($sender)) {\n self::$connections[spl_object_hash($sender)][$signal][] = $slot;\n }\n else {\n self::$connections[md5($sender)][$signal][] = $slot;\n }\n }\n\n\n /**\n * sends a signal, so all connected slots are called\n *\n * @param class|object $sender\n * @param string $signal\n * @param array $params\n */\n public static function signal($sender, $signal, $params = array()) {\n self::$sender = $sender;\n if (is_object($sender)) {\n if ( ! isset(self::$connections[spl_object_hash($sender)][$signal])) {\n return;\n }\n foreach (self::$connections[spl_object_hash($sender)][$signal] as $slot) {\n call_user_func_array($slot, (array)$params);\n }\n\n }\n else {\n if ( ! isset(self::$connections[md5($sender)][$signal])) {\n return;\n }\n foreach (self::$connections[md5($sender)][$signal] as $slot) {\n call_user_func_array($slot, (array)$params);\n }\n }\n\n self::$sender = null;\n }\n\n\n /**\n * returns a current signal sender\n *\n * @return class|object\n */\n public static function sender() {\n return self::$sender;\n }\n\n} \n\nclass User {\n\n public function login() {\n /**\n * try to login\n */\n if ( ! $logged ) {\n SignalsHandler::signal(this, 'loginFailed', 'login failed - username not valid' );\n }\n }\n\n}\n\nclass App {\n public static function onFailedLogin($message) {\n print $message;\n }\n}\n\n\n$user = new User();\nSignalsHandler::connect($user, 'loginFailed', array($Log, 'writeLog'));\nSignalsHandler::connect($user, 'loginFailed', array('App', 'onFailedLogin'));\n\n$user->login();\n\n?>\n</code></pre>\n"
},
{
"answer_id": 933700,
"author": "Volomike",
"author_id": 105539,
"author_profile": "https://Stackoverflow.com/users/105539",
"pm_score": 6,
"selected": false,
"text": "<p>So let's say you don't want the Observer pattern because it requires that you change your class methods to handle the task of listening, and want something generic. And let's say you don't want to use <code>extends</code> inheritance because you may already be inheriting in your class from some other class. Wouldn't it be great to have a generic way to make <em>any class pluggable without much effort</em>? Here's how:</p>\n\n<pre><code><?php\n\n////////////////////\n// PART 1\n////////////////////\n\nclass Plugin {\n\n private $_RefObject;\n private $_Class = '';\n\n public function __construct(&$RefObject) {\n $this->_Class = get_class(&$RefObject);\n $this->_RefObject = $RefObject;\n }\n\n public function __set($sProperty,$mixed) {\n $sPlugin = $this->_Class . '_' . $sProperty . '_setEvent';\n if (is_callable($sPlugin)) {\n $mixed = call_user_func_array($sPlugin, $mixed);\n } \n $this->_RefObject->$sProperty = $mixed;\n }\n\n public function __get($sProperty) {\n $asItems = (array) $this->_RefObject;\n $mixed = $asItems[$sProperty];\n $sPlugin = $this->_Class . '_' . $sProperty . '_getEvent';\n if (is_callable($sPlugin)) {\n $mixed = call_user_func_array($sPlugin, $mixed);\n } \n return $mixed;\n }\n\n public function __call($sMethod,$mixed) {\n $sPlugin = $this->_Class . '_' . $sMethod . '_beforeEvent';\n if (is_callable($sPlugin)) {\n $mixed = call_user_func_array($sPlugin, $mixed);\n }\n if ($mixed != 'BLOCK_EVENT') {\n call_user_func_array(array(&$this->_RefObject, $sMethod), $mixed);\n $sPlugin = $this->_Class . '_' . $sMethod . '_afterEvent';\n if (is_callable($sPlugin)) {\n call_user_func_array($sPlugin, $mixed);\n } \n } \n }\n\n} //end class Plugin\n\nclass Pluggable extends Plugin {\n} //end class Pluggable\n\n////////////////////\n// PART 2\n////////////////////\n\nclass Dog {\n\n public $Name = '';\n\n public function bark(&$sHow) {\n echo \"$sHow<br />\\n\";\n }\n\n public function sayName() {\n echo \"<br />\\nMy Name is: \" . $this->Name . \"<br />\\n\";\n }\n\n\n} //end class Dog\n\n$Dog = new Dog();\n\n////////////////////\n// PART 3\n////////////////////\n\n$PDog = new Pluggable($Dog);\n\nfunction Dog_bark_beforeEvent(&$mixed) {\n $mixed = 'Woof'; // Override saying 'meow' with 'Woof'\n //$mixed = 'BLOCK_EVENT'; // if you want to block the event\n return $mixed;\n}\n\nfunction Dog_bark_afterEvent(&$mixed) {\n echo $mixed; // show the override\n}\n\nfunction Dog_Name_setEvent(&$mixed) {\n $mixed = 'Coco'; // override 'Fido' with 'Coco'\n return $mixed;\n}\n\nfunction Dog_Name_getEvent(&$mixed) {\n $mixed = 'Different'; // override 'Coco' with 'Different'\n return $mixed;\n}\n\n////////////////////\n// PART 4\n////////////////////\n\n$PDog->Name = 'Fido';\n$PDog->Bark('meow');\n$PDog->SayName();\necho 'My New Name is: ' . $PDog->Name;\n</code></pre>\n\n<p>In Part 1, that's what you might include with a <code>require_once()</code> call at the top of your PHP script. It loads the classes to make something pluggable.</p>\n\n<p>In Part 2, that's where we load a class. Note I didn't have to do anything special to the class, which is significantly different than the Observer pattern.</p>\n\n<p>In Part 3, that's where we switch our class around into being \"pluggable\" (that is, supports plugins that let us override class methods and properties). So, for instance, if you have a web app, you might have a plugin registry, and you could activate plugins here. Notice also the <code>Dog_bark_beforeEvent()</code> function. If I set <code>$mixed = 'BLOCK_EVENT'</code> before the return statement, it will block the dog from barking and would also block the Dog_bark_afterEvent because there wouldn't be any event.</p>\n\n<p>In Part 4, that's the normal operation code, but notice that what you might think would run does not run like that at all. For instance, the dog does not announce it's name as 'Fido', but 'Coco'. The dog does not say 'meow', but 'Woof'. And when you want to look at the dog's name afterwards, you find it is 'Different' instead of 'Coco'. All those overrides were provided in Part 3.</p>\n\n<p>So how does this work? Well, let's rule out <code>eval()</code> (which everyone says is \"evil\") and rule out that it's not an Observer pattern. So, the way it works is the sneaky empty class called Pluggable, which does not contain the methods and properties used by the Dog class. Thus, since that occurs, the magic methods will engage for us. That's why in parts 3 and 4 we mess with the object derived from the Pluggable class, not the Dog class itself. Instead, we let the Plugin class do the \"touching\" on the Dog object for us. (If that's some kind of design pattern I don't know about -- please let me know.)</p>\n"
},
{
"answer_id": 16141818,
"author": "Tim Groeneveld",
"author_id": 2143004,
"author_profile": "https://Stackoverflow.com/users/2143004",
"pm_score": 3,
"selected": false,
"text": "<p>I am surprised that most of the answers here seem to be geared about plugins that are local to the web application, ie, plugins that run on the local web server.</p>\n\n<p>What about if you wanted the plugins to run on a different - remote - server? The best way to do this would be to provide a form that allows you to define different URLs that would be called when particular events occur in your application.</p>\n\n<p>Different events would send different information based on the event that just occurred.</p>\n\n<p>This way, you would just perform a cURL call to the URL that has been provided to your application (eg over https) where remote servers can perform tasks based on information that has been sent by your application.</p>\n\n<p>This provides two benefits:</p>\n\n<ol>\n<li>You don't have to host any code on your local server (security)</li>\n<li>The code can be on remote servers (extensibility) in different languages other then PHP (portability)</li>\n</ol>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/42",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37/"
] | I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface.
How does one go about writing 'hooks' into their code so that plugins can attach to specific events? | You could use an Observer pattern. A simple functional way to accomplish this:
```
<?php
/** Plugin system **/
$listeners = array();
/* Create an entry point for plugins */
function hook() {
global $listeners;
$num_args = func_num_args();
$args = func_get_args();
if($num_args < 2)
trigger_error("Insufficient arguments", E_USER_ERROR);
// Hook name should always be first argument
$hook_name = array_shift($args);
if(!isset($listeners[$hook_name]))
return; // No plugins have registered this hook
foreach($listeners[$hook_name] as $func) {
$args = $func($args);
}
return $args;
}
/* Attach a function to a hook */
function add_listener($hook, $function_name) {
global $listeners;
$listeners[$hook][] = $function_name;
}
/////////////////////////
/** Sample Plugin **/
add_listener('a_b', 'my_plugin_func1');
add_listener('str', 'my_plugin_func2');
function my_plugin_func1($args) {
return array(4, 5);
}
function my_plugin_func2($args) {
return str_replace('sample', 'CRAZY', $args[0]);
}
/////////////////////////
/** Sample Application **/
$a = 1;
$b = 2;
list($a, $b) = hook('a_b', $a, $b);
$str = "This is my sample application\n";
$str .= "$a + $b = ".($a+$b)."\n";
$str .= "$a * $b = ".($a*$b)."\n";
$str = hook('str', $str);
echo $str;
?>
```
**Output:**
```
This is my CRAZY application
4 + 5 = 9
4 * 5 = 20
```
**Notes:**
For this example source code, you must declare all your plugins before the actual source code that you want to be extendable. I've included an example of how to handle single or multiple values being passed to the plugin. The hardest part of this is writing the actual documentation which lists what arguments get passed to each hook.
This is just one method of accomplishing a plugin system in PHP. There are better alternatives, I suggest you check out the WordPress Documentation for more information. |
48 | <p>Let's say you create a wizard in an HTML form. One button goes back, and one goes forward. Since the <em>back</em> button appears first in the markup when you press <kbd>Enter</kbd>, it will use that button to submit the form.</p>
<p>Example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<!-- Put your cursor in this field and press Enter -->
<input type="text" name="field1" />
<!-- This is the button that will submit -->
<input type="submit" name="prev" value="Previous Page" />
<!-- But this is the button that I WANT to submit -->
<input type="submit" name="next" value="Next Page" />
</form></code></pre>
</div>
</div>
</p>
<p>I would like to get to decide which button is used to submit the form when a user presses <kbd>Enter</kbd>. That way, when you press <kbd>Enter</kbd> the wizard will move to the next page, not the previous. Do you have to use <code>tabindex</code> to do this?</p>
| [
{
"answer_id": 56,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 6,
"selected": false,
"text": "<p>Give your submit buttons the same name like this:</p>\n\n<pre><code><input type=\"submit\" name=\"submitButton\" value=\"Previous Page\" />\n<input type=\"submit\" name=\"submitButton\" value=\"Next Page\" />\n</code></pre>\n\n<p>When the user presses <kbd>Enter</kbd> and the <em>request</em> goes to the server, you can check the value for <code>submitButton</code> on your server-side code which contains a collection of form <code>name/value</code> pairs. For example, in <a href=\"http://en.wikipedia.org/wiki/Active_Server_Pages\" rel=\"noreferrer\">ASP Classic</a>:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>If Request.Form(\"submitButton\") = \"Previous Page\" Then\n ' Code for the previous page\nElseIf Request.Form(\"submitButton\") = \"Next Page\" Then\n ' Code for the next page\nEnd If\n</code></pre>\n\n<p>Reference: <em><a href=\"http://www.chami.com/tips/internet/042599I.html\" rel=\"noreferrer\">Using multiple submit buttons on a single form</a></em></p>\n"
},
{
"answer_id": 58,
"author": "Wally Lawless",
"author_id": 37,
"author_profile": "https://Stackoverflow.com/users/37",
"pm_score": 6,
"selected": false,
"text": "<p>Change the previous button type into a button like this: </p>\n\n<pre><code><input type=\"button\" name=\"prev\" value=\"Previous Page\" />\n</code></pre>\n\n<p>Now the <em>Next</em> button would be the default, plus you could also add the <code>default</code> attribute to it so that your browser will highlight it like so:</p>\n\n<pre><code><input type=\"submit\" name=\"next\" value=\"Next Page\" default />\n</code></pre>\n"
},
{
"answer_id": 411,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 5,
"selected": false,
"text": "<p>If the fact that the first button is used by default is consistent across browsers, put them the right way around in the source code, and then use CSS to switch their apparent positions.</p>\n\n<p><code>float</code> them left and right to switch them around visually, for example.</p>\n"
},
{
"answer_id": 679,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 4,
"selected": false,
"text": "<p>I would use JavaScript to submit the form. The function would be triggered by the OnKeyPress event of the form element and would detect whether the <kbd>Enter</kbd> key was selected. If this is the case, it will submit the form.</p>\n\n<p>Here are two pages that give techniques on how to do this: <a href=\"http://www.htmlcodetutorial.com/forms/index_famsupp_157.html\" rel=\"nofollow noreferrer\">1</a>, <a href=\"http://www.java2s.com/Code/JavaScript/Form-Control/SubmitaformViaEnter.htm\" rel=\"nofollow noreferrer\">2</a>. Based on these, here is an example of usage (based on <a href=\"http://www.htmlcodetutorial.com/forms/index_famsupp_157.html\" rel=\"nofollow noreferrer\">here</a>):</p>\n\n<pre><code><SCRIPT TYPE=\"text/javascript\">//<!--\nfunction submitenter(myfield,e) {\n var keycode;\n if (window.event) {\n keycode = window.event.keyCode;\n } else if (e) {\n keycode = e.which;\n } else {\n return true;\n }\n\n if (keycode == 13) {\n myfield.form.submit();\n return false;\n } else {\n return true;\n }\n}\n//--></SCRIPT>\n\n<INPUT NAME=\"MyText\" TYPE=\"Text\" onKeyPress=\"return submitenter(this,event)\" />\n</code></pre>\n"
},
{
"answer_id": 2452,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": -1,
"selected": false,
"text": "<p>Using the example you gave:</p>\n\n<pre><code><form>\n <input type=\"text\" name=\"field1\" /><!-- Put your cursor in this field and press Enter -->\n <input type=\"submit\" name=\"prev\" value=\"Previous Page\" /> <!-- This is the button that will submit -->\n <input type=\"submit\" name=\"next\" value=\"Next Page\" /> <!-- But this is the button that I WANT to submit -->\n</form>\n</code></pre>\n\n<p>If you click on \"Previous Page\", only the value of \"prev\" will be submitted. If you click on \"Next Page\" only the value of \"next\" will be submitted.</p>\n\n<p>If however, you press <kbd>Enter</kbd> somewhere on the form, neither \"prev\" nor \"next\" will be submitted.</p>\n\n<p>So using pseudocode you could do the following:</p>\n\n<pre><code>If \"prev\" submitted then\n Previous Page was click\nElse If \"next\" submitted then\n Next Page was click\nElse\n No button was click\n</code></pre>\n"
},
{
"answer_id": 27368,
"author": "Scott Gottreu",
"author_id": 2863,
"author_profile": "https://Stackoverflow.com/users/2863",
"pm_score": 4,
"selected": false,
"text": "<p>If you really just want it to work like an install dialog, just give focus to the \"Next\" button OnLoad. </p>\n\n<p>That way if the user hits <kbd>Return</kbd>, the form submits and goes forward. If they want to go back they can hit <kbd>Tab</kbd> or click on the button.</p>\n"
},
{
"answer_id": 27372,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "<p>This cannot be done with pure HTML. You must rely on JavaScript for this trick.</p>\n\n<p>However, if you place two forms on the HTML page you can do this.</p>\n\n<p>Form1 would have the previous button.</p>\n\n<p>Form2 would have any user inputs + the next button.</p>\n\n<p>When the user presses <kbd>Enter</kbd> in Form2, the Next submit button would fire.</p>\n"
},
{
"answer_id": 31910,
"author": "palotasb",
"author_id": 3063,
"author_profile": "https://Stackoverflow.com/users/3063",
"pm_score": 8,
"selected": true,
"text": "<p>I'm just doing the trick of <code>float</code>ing the buttons to the right.</p>\n<p>This way the <code>Prev</code> button is left of the <code>Next</code> button, but the <code>Next</code> comes first in the HTML structure:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.f {\n float: right;\n}\n.clr {\n clear: both;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form action=\"action\" method=\"get\">\n <input type=\"text\" name=\"abc\">\n <div id=\"buttons\">\n <input type=\"submit\" class=\"f\" name=\"next\" value=\"Next\">\n <input type=\"submit\" class=\"f\" name=\"prev\" value=\"Prev\">\n <div class=\"clr\"></div><!-- This div prevents later elements from floating with the buttons. Keeps them 'inside' div#buttons -->\n </div>\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Benefits over other suggestions: no JavaScript code, accessible, and both buttons remain <code>type="submit"</code>.</p>\n"
},
{
"answer_id": 71322,
"author": "Jolyon",
"author_id": 11740,
"author_profile": "https://Stackoverflow.com/users/11740",
"pm_score": 4,
"selected": false,
"text": "<p>This works without JavaScript or CSS in most browsers:</p>\n\n<pre><code><form>\n <p><input type=\"text\" name=\"field1\" /></p>\n <p><a href=\"previous.html\">\n <button type=\"button\">Previous Page</button></a>\n <button type=\"submit\">Next Page</button></p>\n</form>\n</code></pre>\n\n<p>Firefox, Opera, Safari, and Google Chrome all work. <br/> As always, Internet Explorer is the problem.</p>\n\n<p>This version works when JavaScript is turned on:</p>\n\n<pre><code><form>\n <p><input type=\"text\" name=\"field1\" /></p>\n <p><a href=\"previous.html\">\n <button type=\"button\" onclick=\"window.location='previous.html'\">Previous Page</button></a>\n <button type=\"submit\">Next Page</button></p>\n</form>\n</code></pre>\n\n<p>So the flaw in this solution is:</p>\n\n<p>Previous Page does not work if you use Internet Explorer with JavaScript off.</p>\n\n<p>Mind you, the back button still works!</p>\n"
},
{
"answer_id": 71629,
"author": "Chris James",
"author_id": 3193,
"author_profile": "https://Stackoverflow.com/users/3193",
"pm_score": 4,
"selected": false,
"text": "<p>You can do it with CSS.</p>\n\n<p>Put the buttons in the markup with the <code>Next</code> button first, then the <code>Prev</code> button afterwards.</p>\n\n<p>Then use CSS to position them to appear the way you want.</p>\n"
},
{
"answer_id": 10894669,
"author": "jayu",
"author_id": 1427636,
"author_profile": "https://Stackoverflow.com/users/1427636",
"pm_score": 3,
"selected": false,
"text": "<pre><code><input type="submit" name="prev" value="Previous Page"> \n<input type="submit" name="prev" value="Next Page"> \n</code></pre>\n<p>Keep the name of all submit buttons the same: "prev".</p>\n<p>The only difference is the <code>value</code> attribute with unique values. When we create the script, these unique values will help us to figure out which of the submit buttons was pressed.</p>\n<p>And write the following coding:</p>\n<pre><code> btnID = ""\nif Request.Form("prev") = "Previous Page" then\n btnID = "1"\nelse if Request.Form("prev") = "Next Page" then\n btnID = "2"\nend if\n</code></pre>\n"
},
{
"answer_id": 13084655,
"author": "netiul",
"author_id": 669073,
"author_profile": "https://Stackoverflow.com/users/669073",
"pm_score": 5,
"selected": false,
"text": "<p>Sometimes the provided <a href=\"https://stackoverflow.com/questions/48/multiple-submit-buttons-in-an-html-form/31910#31910\">solution by palotasb</a> is not sufficient. There are use cases where for example a "Filter" submits button is placed above buttons like "Next and Previous". I found a workaround for this: <em>copy</em> the submit button which needs to act as the default submit button in a hidden div and place it inside the form above any other submit button.</p>\n<p>Technically it will be submitted by a different button when pressing Enter than when clicking on the visible Next button. But since the name and value are the same, there's no difference in the result.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><html>\n<head>\n <style>\n div.defaultsubmitbutton {\n display: none;\n }\n </style>\n</head>\n<body>\n <form action=\"action\" method=\"get\">\n <div class=\"defaultsubmitbutton\">\n <input type=\"submit\" name=\"next\" value=\"Next\">\n </div>\n <p><input type=\"text\" name=\"filter\"><input type=\"submit\" value=\"Filter\"></p>\n <p>Filtered results</p>\n <input type=\"radio\" name=\"choice\" value=\"1\">Filtered result 1\n <input type=\"radio\" name=\"choice\" value=\"2\">Filtered result 2\n <input type=\"radio\" name=\"choice\" value=\"3\">Filtered result 3\n <div>\n <input type=\"submit\" name=\"prev\" value=\"Prev\">\n <input type=\"submit\" name=\"next\" value=\"Next\">\n </div>\n </form>\n</body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 13594316,
"author": "Kenny Johnson",
"author_id": 1830173,
"author_profile": "https://Stackoverflow.com/users/1830173",
"pm_score": 4,
"selected": false,
"text": "<p>Changing the tab order should be all it takes to accomplish this. Keep it simple. </p>\n\n<p>Another simple option would be to put the back button after the submit button in the HTML code but float it to the left so it appears on the page before the submit button. </p>\n"
},
{
"answer_id": 22139927,
"author": "Samuel Mugisha",
"author_id": 1223431,
"author_profile": "https://Stackoverflow.com/users/1223431",
"pm_score": 3,
"selected": false,
"text": "<p>This is what I have tried out:</p>\n\n<ol>\n<li>You need to make sure you give your buttons different names</li>\n<li>Write an <code>if</code> statement that will do the required action if either button is clicked.</li>\n</ol>\n\n<p> </p>\n\n<pre><code><form>\n <input type=\"text\" name=\"field1\" /> <!-- Put your cursor in this field and press Enter -->\n\n <input type=\"submit\" name=\"prev\" value=\"Previous Page\" /> <!-- This is the button that will submit -->\n <input type=\"submit\" name=\"next\" value=\"Next Page\" /> <!-- But this is the button that I WANT to submit -->\n</form>\n</code></pre>\n\n<p>In PHP,</p>\n\n<pre><code>if(isset($_POST['prev']))\n{\n header(\"Location: previous.html\");\n die();\n}\n\nif(isset($_POST['next']))\n{\n header(\"Location: next.html\");\n die();\n}\n</code></pre>\n"
},
{
"answer_id": 22408408,
"author": "user1591131",
"author_id": 1591131,
"author_profile": "https://Stackoverflow.com/users/1591131",
"pm_score": 4,
"selected": false,
"text": "<p>If you have multiple active buttons on one page then you can do something like this:</p>\n\n<p>Mark the first button you want to trigger on the <kbd>Enter</kbd> keypress as the default button on the form. For the second button, associate it to the <kbd>Backspace</kbd> button on the keyboard. The <kbd>Backspace</kbd> eventcode is 8.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(document).on(\"keydown\", function(event) {\r\n if (event.which.toString() == \"8\") {\r\n var findActiveElementsClosestForm = $(document.activeElement).closest(\"form\");\r\n\r\n if (findActiveElementsClosestForm && findActiveElementsClosestForm.length) {\r\n $(\"form#\" + findActiveElementsClosestForm[0].id + \" .secondary_button\").trigger(\"click\");\r\n }\r\n }\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js\"></script>\r\n\r\n<form action=\"action\" method=\"get\" defaultbutton=\"TriggerOnEnter\">\r\n <input type=\"submit\" id=\"PreviousButton\" name=\"prev\" value=\"Prev\" class=\"secondary_button\" />\r\n <input type=\"submit\" id='TriggerOnEnter' name=\"next\" value=\"Next\" class=\"primary_button\" />\r\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 26365211,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Another simple option would be to put the back button after the submit button in the HTML code, but float it to the left, so it appears on the page before the submit button.</p>\n\n<p>Changing the tab order should be all it takes to accomplish this. Keep it simple.</p>\n"
},
{
"answer_id": 29322619,
"author": "nikkypx",
"author_id": 1395009,
"author_profile": "https://Stackoverflow.com/users/1395009",
"pm_score": 3,
"selected": false,
"text": "<p>From <a href=\"https://html.spec.whatwg.org/multipage/forms.html#implicit-submission\">https://html.spec.whatwg.org/multipage/forms.html#implicit-submission</a></p>\n\n<blockquote>\n <p>A form element's default button is the first submit button in tree\n order whose form owner is that form element.</p>\n \n <p>If the user agent supports letting the user submit a form implicitly\n (for example, on some platforms hitting the \"enter\" key while a text\n field is focused implicitly submits the form)...</p>\n</blockquote>\n\n<p>Having the next input be type=\"submit\" and changing the previous input to type=\"button\" should give the desired default behavior.</p>\n\n<pre><code><form>\n <input type=\"text\" name=\"field1\" /> <!-- put your cursor in this field and press Enter -->\n\n <input type=\"button\" name=\"prev\" value=\"Previous Page\" /> <!-- This is the button that will submit -->\n <input type=\"submit\" name=\"next\" value=\"Next Page\" /> <!-- But this is the button that I WANT to submit -->\n</form>\n</code></pre>\n"
},
{
"answer_id": 32007399,
"author": "GuillaumeS",
"author_id": 1448969,
"author_profile": "https://Stackoverflow.com/users/1448969",
"pm_score": 3,
"selected": false,
"text": "<p>With JavaScript (here jQuery), you can disable the prev button before submitting the form.</p>\n\n<pre><code>$('form').on('keypress', function(event) {\n if (event.which == 13) {\n $('input[name=\"prev\"]').prop('type', 'button');\n }\n});\n</code></pre>\n"
},
{
"answer_id": 32377058,
"author": "MiddleAgedMutantNinjaProgrammer",
"author_id": 832919,
"author_profile": "https://Stackoverflow.com/users/832919",
"pm_score": 3,
"selected": false,
"text": "<p>The first time I came up against this, I came up with an onclick()/JavaScript hack when choices are not prev/next that I still like for its simplicity. It goes like this:</p>\n\n<pre><code>@model myApp.Models.myModel\n\n<script type=\"text/javascript\">\n function doOperation(op) {\n document.getElementById(\"OperationId\").innerText = op;\n // you could also use Ajax to reference the element.\n }\n</script>\n\n<form>\n <input type=\"text\" id = \"TextFieldId\" name=\"TextField\" value=\"\" />\n <input type=\"hidden\" id=\"OperationId\" name=\"Operation\" value=\"\" />\n <input type=\"submit\" name=\"write\" value=\"Write\" onclick='doOperation(\"Write\")'/>\n <input type=\"submit\" name=\"read\" value=\"Read\" onclick='doOperation(\"Read\")'/>\n</form>\n</code></pre>\n\n<p>When either submit button is clicked, it stores the desired operation in a hidden field (which is a string field included in the model the form is associated with) and submits the form to the Controller, which does all the deciding. In the Controller, you simply write:</p>\n\n<pre><code>// Do operation according to which submit button was clicked\n// based on the contents of the hidden Operation field.\nif (myModel.Operation == \"Read\")\n{\n // Do read logic\n}\nelse if (myModel.Operation == \"Write\")\n{\n // Do write logic\n}\nelse\n{\n // Do error logic\n}\n</code></pre>\n\n<p>You can also tighten this up slightly using numeric operation codes to avoid the string parsing, but unless you play with enumerations, the code is less readable, modifiable, and self-documenting and the parsing is trivial, anyway.</p>\n"
},
{
"answer_id": 36206414,
"author": "Barry Franklin",
"author_id": 680563,
"author_profile": "https://Stackoverflow.com/users/680563",
"pm_score": 3,
"selected": false,
"text": "<p>I came across this question when trying to find an answer to basically the same thing, only with ASP.NET controls, when I figured out that the ASP button has a property called <code>UseSubmitBehavior</code> that allows you to set which one does the submitting.</p>\n\n<pre><code><asp:Button runat=\"server\" ID=\"SumbitButton\" UseSubmitBehavior=\"False\" Text=\"Submit\" />\n</code></pre>\n\n<p>Just in case someone is looking for the ASP.NET button way to do it.</p>\n"
},
{
"answer_id": 48171459,
"author": "riskop",
"author_id": 3760049,
"author_profile": "https://Stackoverflow.com/users/3760049",
"pm_score": 2,
"selected": false,
"text": "<p>I solved a very similar problem in this way:</p>\n\n<ol>\n<li><p>If JavaScript is enabled (in most cases nowadays) then all the submit buttons are \"<strong>degraded</strong>\" to buttons at page load via JavaScript (jQuery). Click events on the \"<strong>degraded</strong>\" button typed buttons are also handled via JavaScript.</p></li>\n<li><p>If JavaScript is not enabled then the form is served to the browser with multiple submit buttons. In this case hitting <kbd>Enter</kbd> on a <code>textfield</code> within the form will submit the form with the first button instead of the intended <strong>default</strong>, but at least the form is still usable: you can submit with both the <strong>prev</strong> and <strong>next</strong> buttons.</p></li>\n</ol>\n\n<p>Working example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><html>\r\n <head>\r\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js\"></script>\r\n </head>\r\n\r\n <body>\r\n <form action=\"http://httpbin.org/post\" method=\"post\">\r\n If JavaScript is disabled, then you CAN submit the form\r\n with button1, button2 or button3.\r\n\r\n If you press enter on a text field, then the form is\r\n submitted with the first submit button.\r\n\r\n If JavaScript is enabled, then the submit typed buttons\r\n without the 'defaultSubmitButton' style are converted\r\n to button typed buttons.\r\n\r\n If you press Enter on a text field, then the form is\r\n submitted with the only submit button\r\n (the one with class defaultSubmitButton)\r\n\r\n If you click on any other button in the form, then the\r\n form is submitted with that button's value.\r\n\r\n <br />\r\n\r\n <input type=\"text\" name=\"text1\" ></input>\r\n <button type=\"submit\" name=\"action\" value=\"button1\" >button 1</button>\r\n <br />\r\n\r\n <input type=\"text\" name=\"text2\" ></input>\r\n <button type=\"submit\" name=\"action\" value=\"button2\" >button 2</button>\r\n <br />\r\n\r\n <input type=\"text\" name=\"text3\" ></input>\r\n <button class=\"defaultSubmitButton\" type=\"submit\" name=\"action\" value=\"button3\" >default button</button>\r\n </form>\r\n\r\n <script>\r\n $(document).ready(function(){\r\n\r\n /* Change submit typed buttons without the 'defaultSubmitButton'\r\n style to button typed buttons */\r\n $('form button[type=submit]').not('.defaultSubmitButton').each(function(){\r\n $(this).attr('type', 'button');\r\n });\r\n\r\n /* Clicking on button typed buttons results in:\r\n 1. Setting the form's submit button's value to\r\n the clicked button's value,\r\n 2. Clicking on the form's submit button */\r\n $('form button[type=button]').click(function( event ){\r\n var form = event.target.closest('form');\r\n var submit = $(\"button[type='submit']\",form).first();\r\n submit.val(event.target.value);\r\n submit.click();\r\n });\r\n });\r\n </script>\r\n </body>\r\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 50015400,
"author": "Jyoti mishra",
"author_id": 4890885,
"author_profile": "https://Stackoverflow.com/users/4890885",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>Tabindex</code> to solve this issue. Also changing the order of the buttons would be a more efficient way to achieve this.</p>\n\n<p>Change the order of the buttons and add <code>float</code> values to assign them the desired position you want to show in your <code>HTML</code> view.</p>\n"
},
{
"answer_id": 65239408,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of struggling with multiple submits, JavaScript or anything like that to do some previous/next stuff, an alternative would be to use a carousel to simulate the different pages.\nDoing this :</p>\n<ul>\n<li>You don't need multiple buttons, inputs or submits to do the previous/next thing, you have only one <code>input type="submit"</code> in only one <code>form</code>.</li>\n<li>The values in the whole form are there until the form is submitted.</li>\n<li>The user can go to any previous page and any next page flawlessly to modify the values.</li>\n</ul>\n<p>Example using Bootstrap 5.0.0 :</p>\n<pre><code><div id="carousel" class="carousel slide" data-ride="carousel">\n <form action="index.php" method="post" class="carousel-inner">\n <div class="carousel-item active">\n <input type="text" name="lastname" placeholder="Lastname"/>\n </div>\n <div class="carousel-item">\n <input type="text" name="firstname" placeholder="Firstname"/>\n </div>\n <div class="carousel-item">\n <input type="submit" name="submit" value="Submit"/>\n </div>\n </form>\n <a class="btn-secondary" href="#carousel" role="button" data-slide="prev">Previous page</a>\n <a class="btn-primary" href="#carousel" role="button" data-slide="next">Next page</a>\n</div>\n</code></pre>\n"
},
{
"answer_id": 65548916,
"author": "Prince Owen",
"author_id": 8058709,
"author_profile": "https://Stackoverflow.com/users/8058709",
"pm_score": -1,
"selected": false,
"text": "<p>When a button is clicked with a mouse (and hopefully by touch), it records the X,Y coordinates. This is not the case when it is invoked by a form, and these values are normally zero.</p>\n<p>So you can do something like this:</p>\n<pre><code>function(e) {\n const isArtificial = e.screenX === 0 && e.screenY === 0\n && e.x === 0 && e.y === 0\n && e.clientX === 0 && e.clientY === 0;\n\n if (isArtificial) {\n return; // DO NOTHING\n } else {\n // OPTIONAL: Don't submit the form when clicked\n // e.preventDefault();\n // e.stopPropagation();\n }\n\n // ...Natural code goes here\n}\n</code></pre>\n"
},
{
"answer_id": 65612020,
"author": "Ajay Patidar",
"author_id": 5340811,
"author_profile": "https://Stackoverflow.com/users/5340811",
"pm_score": 0,
"selected": false,
"text": "<p>I think this is an easy solution for this. Change the <em>Previous</em> button <code>type</code> to <code>button</code>, and add a new <code>onclick</code> attribute to the button with value <code>jQuery(this).attr('type','submit');</code>.</p>\n<p>So, when the user clicks on the <em>Previous</em> button then its <code>type</code> will be changed to <code>submit</code> and the form will be submitted with the <em>Previous</em> button.</p>\n<pre><code><form>\n <!-- Put your cursor in this field and press Enter -->\n <input type="text" name="field1" />\n\n <!-- This is the button that will submit -->\n <input type="button" onclick="jQuery(this).attr('type','submit');" name="prev" value="Previous Page" />\n\n <!-- But this is the button that I WANT to submit -->\n <input type="submit" name="next" value="Next Page" />\n</form>\n</code></pre>\n"
},
{
"answer_id": 68941820,
"author": "Stoppeye",
"author_id": 14989607,
"author_profile": "https://Stackoverflow.com/users/14989607",
"pm_score": 1,
"selected": false,
"text": "<p>A maybe somewhat more modern approach over the CSS float method could be a solution using flexbox with the <code>order</code> property on the flex items. It could be something along those lines:</p>\n<pre><code><div style="display: flex">\n <input type="submit" name="next" value="Next Page" style="order: 1" />\n <input type="submit" name="prev" value="Previous Page" style="order: 0" />\n</div>\n</code></pre>\n<p>Of course it depends on your document structure whether this is a feasible approach or not, but I find flex items much easier to control than floating elements.</p>\n"
},
{
"answer_id": 72097973,
"author": "Motine",
"author_id": 4007237,
"author_profile": "https://Stackoverflow.com/users/4007237",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Problem</strong></p>\n<p>A form may have several submit buttons.\nWhen pressing return in any input, the <em>first</em> submit button is used by the browser.\nHowever, sometimes we want to use a different/later button as default.</p>\n<p><strong>Options</strong></p>\n<ol>\n<li>Add a hidden submit button with the same action first (☹️ duplication)</li>\n<li>Put the desired submit button first in the form and then move it to the correct place via CSS (☹️ may not be feasible, may result in cumbersome styling)</li>\n<li>Change the handling of the return key in all form inputs via JavaScript (☹️ needs javascript)</li>\n</ol>\n<p>None of the options is ideal, so we choose 3. because most browsers have JavaScript enabled.</p>\n<p><strong>Chosen solution</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// example implementation\ndocument.addEventListener('DOMContentLoaded', (ev) => {\n for (const defaultSubmitInput of document.querySelectorAll('[data-default-submit]')) {\n for (const formInput of defaultSubmitInput.form.querySelectorAll('input')) {\n if (formInput.dataset.ignoreDefaultSubmit != undefined) { continue; }\n formInput.addEventListener('keypress', (ev) => {\n if (ev.keyCode == 13) {\n ev.preventDefault();\n defaultSubmitInput.click();\n }\n })\n }\n }\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> <!-- example markup -->\n <form action=\"https://postman-echo.com/get\" method=\"get\">\n <input type=\"text\" name=\"field1\">\n <input type=\"submit\" name=\"submit\" value=\"other action\">\n <input type=\"submit\" name=\"submit\" value=\"default action\" data-default-submit> <!-- this button will be used on return -->\n </form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>It may be useful to be able to remove the enhancement from some inputs. This can be achieved by:</p>\n<pre class=\"lang-html prettyprint-override\"><code><input type="text" name="field2" data-ignore-default-submit> <!-- uses browser standard behaviour -->\n</code></pre>\n<p>Here a complete <a href=\"https://codepen.io/motine/pen/wvyBmxO\" rel=\"nofollow noreferrer\">code pen</a>.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/48",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40/"
] | Let's say you create a wizard in an HTML form. One button goes back, and one goes forward. Since the *back* button appears first in the markup when you press `Enter`, it will use that button to submit the form.
Example:
```html
<form>
<!-- Put your cursor in this field and press Enter -->
<input type="text" name="field1" />
<!-- This is the button that will submit -->
<input type="submit" name="prev" value="Previous Page" />
<!-- But this is the button that I WANT to submit -->
<input type="submit" name="next" value="Next Page" />
</form>
```
I would like to get to decide which button is used to submit the form when a user presses `Enter`. That way, when you press `Enter` the wizard will move to the next page, not the previous. Do you have to use `tabindex` to do this? | I'm just doing the trick of `float`ing the buttons to the right.
This way the `Prev` button is left of the `Next` button, but the `Next` comes first in the HTML structure:
```css
.f {
float: right;
}
.clr {
clear: both;
}
```
```html
<form action="action" method="get">
<input type="text" name="abc">
<div id="buttons">
<input type="submit" class="f" name="next" value="Next">
<input type="submit" class="f" name="prev" value="Prev">
<div class="clr"></div><!-- This div prevents later elements from floating with the buttons. Keeps them 'inside' div#buttons -->
</div>
</form>
```
Benefits over other suggestions: no JavaScript code, accessible, and both buttons remain `type="submit"`. |
59 | <p>I have a <code>DataTable</code> with a <code>Name</code> column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the <em>order by</em> clause.</p>
<pre><code>var names =
(from DataRow dr in dataTable.Rows
orderby (string)dr["Name"]
select (string)dr["Name"]).Distinct();
</code></pre>
<p>Why does the <code>orderby</code> not get enforced?</p>
| [
{
"answer_id": 62,
"author": "Bob",
"author_id": 45,
"author_profile": "https://Stackoverflow.com/users/45",
"pm_score": 6,
"selected": false,
"text": "<p><strong>The problem is that the Distinct\n operator does not grant that it will\n maintain the original order of\n values.</strong></p>\n\n<p>So your query will need to work like this</p>\n\n<pre><code>var names = (from DataRow dr in dataTable.Rows\n select (string)dr[\"Name\"]).Distinct().OrderBy( name => name );\n</code></pre>\n"
},
{
"answer_id": 4313,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>Try the following</p>\n\n<pre><code>var names = (from dr in dataTable.Rows\n select (string)dr[\"Name\"]).Distinct().OrderBy(name => name);\n</code></pre>\n\n<p>this should work for what you need.</p>\n"
},
{
"answer_id": 43110,
"author": "a7drew",
"author_id": 4239,
"author_profile": "https://Stackoverflow.com/users/4239",
"pm_score": 6,
"selected": true,
"text": "<p>To make it more readable and maintainable, you can also split it up into multiple LINQ statements.</p>\n\n<ol>\n<li>First, select your data into a new list, let's call it <code>x1</code>, do a projection if desired</li>\n<li>Next, create a distinct list, from <code>x1</code> into <code>x2</code>, using whatever distinction you require</li>\n<li>Finally, create an ordered list, from <code>x2</code> into <code>x3</code>, sorting by whatever you desire </li>\n</ol>\n"
},
{
"answer_id": 342600,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre><code>var sortedTable = (from results in resultTable.AsEnumerable()\nselect (string)results[attributeList]).Distinct().OrderBy(name => name);\n</code></pre>\n"
},
{
"answer_id": 16261469,
"author": "Gavin Fang",
"author_id": 2010092,
"author_profile": "https://Stackoverflow.com/users/2010092",
"pm_score": 3,
"selected": false,
"text": "<p>Try out the following:</p>\n\n<pre><code>dataTable.Rows.Cast<DataRow>().select(dr => dr[\"Name\"].ToString()).Distinct().OrderBy(name => name);\n</code></pre>\n"
},
{
"answer_id": 48526016,
"author": "Philip Raath",
"author_id": 3919949,
"author_profile": "https://Stackoverflow.com/users/3919949",
"pm_score": 2,
"selected": false,
"text": "<p>To abstract: all of the answers have something in common.</p>\n\n<p>OrderBy needs to be the final operation.</p>\n"
},
{
"answer_id": 51021828,
"author": "Presto",
"author_id": 8479567,
"author_profile": "https://Stackoverflow.com/users/8479567",
"pm_score": 2,
"selected": false,
"text": "<p>You can use something like that:</p>\n\n<pre><code>dataTable.Rows.Cast<DataRow>().GroupBy(g => g[\"Name\"]).Select(s => s.First()).OrderBy(o => o[\"Name\"]);\n</code></pre>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/59",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45/"
] | I have a `DataTable` with a `Name` column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the *order by* clause.
```
var names =
(from DataRow dr in dataTable.Rows
orderby (string)dr["Name"]
select (string)dr["Name"]).Distinct();
```
Why does the `orderby` not get enforced? | To make it more readable and maintainable, you can also split it up into multiple LINQ statements.
1. First, select your data into a new list, let's call it `x1`, do a projection if desired
2. Next, create a distinct list, from `x1` into `x2`, using whatever distinction you require
3. Finally, create an ordered list, from `x2` into `x3`, sorting by whatever you desire |
66 | <p>How do you page through a collection in LINQ given that you have a <code>startIndex</code> and a <code>count</code>?</p>
| [
{
"answer_id": 68,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 6,
"selected": false,
"text": "<p>It is very simple with the <code>Skip</code> and <code>Take</code> extension methods.</p>\n\n<pre><code>var query = from i in ideas\n select i;\n\nvar paggedCollection = query.Skip(startIndex).Take(count);\n</code></pre>\n"
},
{
"answer_id": 4521,
"author": "Mike Minutillo",
"author_id": 358,
"author_profile": "https://Stackoverflow.com/users/358",
"pm_score": 7,
"selected": true,
"text": "<p>A few months back I wrote a blog post about Fluent Interfaces and LINQ which used an Extension Method on <code>IQueryable<T></code> and another class to provide the following natural way of paginating a LINQ collection.</p>\n\n<pre><code>var query = from i in ideas\n select i;\nvar pagedCollection = query.InPagesOf(10);\nvar pageOfIdeas = pagedCollection.Page(2);\n</code></pre>\n\n<p>You can get the code from the MSDN Code Gallery Page: <a href=\"http://code.msdn.microsoft.com/productschallenge\" rel=\"noreferrer\">Pipelines, Filters, Fluent API and LINQ to SQL</a>.</p>\n"
},
{
"answer_id": 6719914,
"author": "Nico",
"author_id": 452101,
"author_profile": "https://Stackoverflow.com/users/452101",
"pm_score": 4,
"selected": false,
"text": "<p>This question is somewhat old, but I wanted to post my paging algorithm that shows the whole procedure (including user interaction).</p>\n\n<pre><code>const int pageSize = 10;\nconst int count = 100;\nconst int startIndex = 20;\n\nint took = 0;\nbool getNextPage;\nvar page = ideas.Skip(startIndex);\n\ndo\n{\n Console.WriteLine(\"Page {0}:\", (took / pageSize) + 1);\n foreach (var idea in page.Take(pageSize))\n {\n Console.WriteLine(idea);\n }\n\n took += pageSize;\n if (took < count)\n {\n Console.WriteLine(\"Next page (y/n)?\");\n char answer = Console.ReadLine().FirstOrDefault();\n getNextPage = default(char) != answer && 'y' == char.ToLowerInvariant(answer);\n\n if (getNextPage)\n {\n page = page.Skip(pageSize);\n }\n }\n}\nwhile (getNextPage && took < count);\n</code></pre>\n\n<p>However, if you are after performance, and in production code, we're all after performance, you shouldn't use LINQ's paging as shown above, but rather the underlying <code>IEnumerator</code> to implement paging yourself. As a matter of fact, it is as simple as the LINQ-algorithm shown above, but more performant:</p>\n\n<pre><code>const int pageSize = 10;\nconst int count = 100;\nconst int startIndex = 20;\n\nint took = 0;\nbool getNextPage = true;\nusing (var page = ideas.Skip(startIndex).GetEnumerator())\n{\n do \n {\n Console.WriteLine(\"Page {0}:\", (took / pageSize) + 1);\n\n int currentPageItemNo = 0;\n while (currentPageItemNo++ < pageSize && page.MoveNext())\n {\n var idea = page.Current;\n Console.WriteLine(idea);\n }\n\n took += pageSize;\n if (took < count)\n {\n Console.WriteLine(\"Next page (y/n)?\");\n char answer = Console.ReadLine().FirstOrDefault();\n getNextPage = default(char) != answer && 'y' == char.ToLowerInvariant(answer);\n }\n }\n while (getNextPage && took < count);\n}\n</code></pre>\n\n<p>Explanation: The downside of using <code>Skip()</code> for multiple times in a \"cascading manner\" is, that it will not really store the \"pointer\" of the iteration, where it was last skipped. - Instead the original sequence will be front-loaded with skip calls, which will lead to \"consuming\" the already \"consumed\" pages over and over again. - You can prove that yourself, when you create the sequence <code>ideas</code> so that it yields side effects. -> Even if you have skipped 10-20 and 20-30 and want to process 40+, you'll see all side effects of 10-30 being executed again, before you start iterating 40+.\nThe variant using <code>IEnumerable</code>'s interface directly, will instead remember the position of the end of the last logical page, so no explicit skipping is needed and side effects won't be repeated.</p>\n"
},
{
"answer_id": 9787122,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 4,
"selected": false,
"text": "<p>I solved this a bit differently than what the others have as I had to make my own paginator, with a repeater. So I first made a collection of page numbers for the collection of items that I have:</p>\n\n<pre><code>// assumes that the item collection is \"myItems\"\n\nint pageCount = (myItems.Count + PageSize - 1) / PageSize;\n\nIEnumerable<int> pageRange = Enumerable.Range(1, pageCount);\n // pageRange contains [1, 2, ... , pageCount]\n</code></pre>\n\n<p>Using this I could easily partition the item collection into a collection of \"pages\". A page in this case is just a collection of items (<code>IEnumerable<Item></code>). This is how you can do it using <code>Skip</code> and <code>Take</code> together with selecting the index from the <code>pageRange</code> created above:</p>\n\n<pre><code>IEnumerable<IEnumerable<Item>> pageRange\n .Select((page, index) => \n myItems\n .Skip(index*PageSize)\n .Take(PageSize));\n</code></pre>\n\n<p>Of course you have to handle each page as an additional collection but e.g. if you're nesting repeaters then this is actually easy to handle.</p>\n\n<hr>\n\n<p>The <em>one-liner TLDR</em> version would be this:</p>\n\n<pre><code>var pages = Enumerable\n .Range(0, pageCount)\n .Select((index) => myItems.Skip(index*PageSize).Take(PageSize));\n</code></pre>\n\n<p>Which can be used as this:</p>\n\n<pre><code>for (Enumerable<Item> page : pages) \n{\n // handle page\n\n for (Item item : page) \n {\n // handle item in page\n }\n}\n</code></pre>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/66",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17/"
] | How do you page through a collection in LINQ given that you have a `startIndex` and a `count`? | A few months back I wrote a blog post about Fluent Interfaces and LINQ which used an Extension Method on `IQueryable<T>` and another class to provide the following natural way of paginating a LINQ collection.
```
var query = from i in ideas
select i;
var pagedCollection = query.InPagesOf(10);
var pageOfIdeas = pagedCollection.Page(2);
```
You can get the code from the MSDN Code Gallery Page: [Pipelines, Filters, Fluent API and LINQ to SQL](http://code.msdn.microsoft.com/productschallenge). |
80 | <p>I've written a database generation script in <a href="http://en.wikipedia.org/wiki/SQL" rel="noreferrer">SQL</a> and want to execute it in my <a href="http://en.wikipedia.org/wiki/Adobe_Integrated_Runtime" rel="noreferrer">Adobe AIR</a> application:</p>
<pre><code>Create Table tRole (
roleID integer Primary Key
,roleName varchar(40)
);
Create Table tFile (
fileID integer Primary Key
,fileName varchar(50)
,fileDescription varchar(500)
,thumbnailID integer
,fileFormatID integer
,categoryID integer
,isFavorite boolean
,dateAdded date
,globalAccessCount integer
,lastAccessTime date
,downloadComplete boolean
,isNew boolean
,isSpotlight boolean
,duration varchar(30)
);
Create Table tCategory (
categoryID integer Primary Key
,categoryName varchar(50)
,parent_categoryID integer
);
...
</code></pre>
<p>I execute this in Adobe AIR using the following methods:</p>
<pre><code>public static function RunSqlFromFile(fileName:String):void {
var file:File = File.applicationDirectory.resolvePath(fileName);
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ)
var strSql:String = stream.readUTFBytes(stream.bytesAvailable);
NonQuery(strSql);
}
public static function NonQuery(strSQL:String):void {
var sqlConnection:SQLConnection = new SQLConnection();
sqlConnection.open(File.applicationStorageDirectory.resolvePath(DBPATH));
var sqlStatement:SQLStatement = new SQLStatement();
sqlStatement.text = strSQL;
sqlStatement.sqlConnection = sqlConnection;
try {
sqlStatement.execute();
} catch (error:SQLError) {
Alert.show(error.toString());
}
}
</code></pre>
<p>No errors are generated, however only <code>tRole</code> exists. It seems that it only looks at the first query (up to the semicolon- if I remove it, the query fails). Is there a way to call multiple queries in one statement?</p>
| [
{
"answer_id": 124,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 5,
"selected": true,
"text": "<p>I wound up using this. It is a kind of a hack, but it actually works pretty well. </p>\n\n<p>The only thing is you have to be very careful with your semicolons. : D</p>\n\n<pre><code>var strSql:String = stream.readUTFBytes(stream.bytesAvailable); \nvar i:Number = 0;\nvar strSqlSplit:Array = strSql.split(\";\");\nfor (i = 0; i < strSqlSplit.length; i++){\n NonQuery(strSqlSplit[i].toString());\n}\n</code></pre>\n"
},
{
"answer_id": 10008,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://en.wikipedia.org/wiki/SQLite\" rel=\"noreferrer\">SQLite</a> API has a function called something like <code>sqlite_prepare</code> which takes <em>one</em> statement and prepares it for execution, essentially parsing the SQL and storing it in memory. This means that the SQL only has to be sent once to the database engine even though the statement is executed many times.</p>\n\n<p>Anyway, a statement is a single SQL query, that's just the rule. The AIR SQL API doesn't allow sending raw SQL to SQLite, only single statements, and the reason is, likely, that AIR uses the <code>sqlite_prepare</code> function when it talks to SQLite.</p>\n"
},
{
"answer_id": 3770976,
"author": "stats",
"author_id": 364174,
"author_profile": "https://Stackoverflow.com/users/364174",
"pm_score": 2,
"selected": false,
"text": "<p>What about making your delimiter something a little more complex like \";\\n\" which would not show up all that often. You just have to ensure when creating the file you have a line return or two in there. I end up putting two \"\\n\\n\" into the creation of my files which works well.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/80",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | I've written a database generation script in [SQL](http://en.wikipedia.org/wiki/SQL) and want to execute it in my [Adobe AIR](http://en.wikipedia.org/wiki/Adobe_Integrated_Runtime) application:
```
Create Table tRole (
roleID integer Primary Key
,roleName varchar(40)
);
Create Table tFile (
fileID integer Primary Key
,fileName varchar(50)
,fileDescription varchar(500)
,thumbnailID integer
,fileFormatID integer
,categoryID integer
,isFavorite boolean
,dateAdded date
,globalAccessCount integer
,lastAccessTime date
,downloadComplete boolean
,isNew boolean
,isSpotlight boolean
,duration varchar(30)
);
Create Table tCategory (
categoryID integer Primary Key
,categoryName varchar(50)
,parent_categoryID integer
);
...
```
I execute this in Adobe AIR using the following methods:
```
public static function RunSqlFromFile(fileName:String):void {
var file:File = File.applicationDirectory.resolvePath(fileName);
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ)
var strSql:String = stream.readUTFBytes(stream.bytesAvailable);
NonQuery(strSql);
}
public static function NonQuery(strSQL:String):void {
var sqlConnection:SQLConnection = new SQLConnection();
sqlConnection.open(File.applicationStorageDirectory.resolvePath(DBPATH));
var sqlStatement:SQLStatement = new SQLStatement();
sqlStatement.text = strSQL;
sqlStatement.sqlConnection = sqlConnection;
try {
sqlStatement.execute();
} catch (error:SQLError) {
Alert.show(error.toString());
}
}
```
No errors are generated, however only `tRole` exists. It seems that it only looks at the first query (up to the semicolon- if I remove it, the query fails). Is there a way to call multiple queries in one statement? | I wound up using this. It is a kind of a hack, but it actually works pretty well.
The only thing is you have to be very careful with your semicolons. : D
```
var strSql:String = stream.readUTFBytes(stream.bytesAvailable);
var i:Number = 0;
var strSqlSplit:Array = strSql.split(";");
for (i = 0; i < strSqlSplit.length; i++){
NonQuery(strSqlSplit[i].toString());
}
``` |
85 | <p>What are the best practices around creating flat file database structures in PHP?</p>
<p>A lot of more matured PHP flat file frameworks out there which I attempt to implement SQL-like query syntax which is over the top for my purposes in most cases. (I would just use a database at that point).</p>
<p>Are there any elegant tricks out there to get good performance and features with a small code overhead?</p>
| [
{
"answer_id": 87,
"author": "saint_groceon",
"author_id": 59,
"author_profile": "https://Stackoverflow.com/users/59",
"pm_score": 4,
"selected": false,
"text": "<p>One framework I'm considering would be for a blogging platform. Since just about any possible view of data you would want would be sorted by date, I was thinking about this structure:</p>\n\n<p>One directory per content node:</p>\n\n<pre><code>./content/YYYYMMDDHHMMSS/\n</code></pre>\n\n<p>Subdirectories of each node including </p>\n\n<pre><code>/tags \n/authors \n/comments \n</code></pre>\n\n<p>As well as simple text files in the node directory for pre- and post-rendered content and the like.</p>\n\n<p>This would allow a simple PHP <a href=\"http://us3.php.net/glob\" rel=\"noreferrer\"><code>glob()</code></a> call (and probably a reversal of the result array) to query on just about anything within the content structure:</p>\n\n<pre><code>glob(\"content/*/tags/funny\"); \n</code></pre>\n\n<p>Would return paths including all articles tagged \"funny\".</p>\n"
},
{
"answer_id": 154,
"author": "w-ll",
"author_id": 146637,
"author_profile": "https://Stackoverflow.com/users/146637",
"pm_score": 7,
"selected": true,
"text": "<p>Well, what is the nature of the flat databases. Are they large or small. Is it simple arrays with arrays in them? if its something simple say userprofiles built as such:</p>\n<pre><code>$user = array("name" => "bob", \n "age" => 20,\n "websites" => array("example.com","bob.example.com","bob2.example.com"),\n "and_one" => "more");\n</code></pre>\n<p>and to save or update the <em>db record</em> for that user.</p>\n<pre><code>$dir = "../userdata/"; //make sure to put it bellow what the server can reach.\nfile_put_contents($dir.$user['name'],serialize($user));\n</code></pre>\n<p>and to load the <em>record</em> for the user</p>\n<pre><code>function &get_user($name){\n return unserialize(file_get_contents("../userdata/".$name));\n}\n</code></pre>\n<p>but again this implementation will vary on the application and nature of the database you need.</p>\n"
},
{
"answer_id": 6454,
"author": "yukondude",
"author_id": 726,
"author_profile": "https://Stackoverflow.com/users/726",
"pm_score": 6,
"selected": false,
"text": "<p>You might consider <a href=\"http://www.sqlite.org/\" rel=\"noreferrer\">SQLite</a>. It's almost as simple as flat files, but you do get a SQL engine for querying. It <a href=\"http://ca3.php.net/sqlite\" rel=\"noreferrer\">works well with PHP</a> too.</p>\n"
},
{
"answer_id": 90542,
"author": "Jason",
"author_id": 7391,
"author_profile": "https://Stackoverflow.com/users/7391",
"pm_score": 3,
"selected": false,
"text": "<p>If you're going to use a flat file to persist data, use XML to structure the data. PHP has a <a href=\"http://uk.php.net/xml\" rel=\"noreferrer\">built-in XML parser</a>.</p>\n"
},
{
"answer_id": 90800,
"author": "ofaurax",
"author_id": 15209,
"author_profile": "https://Stackoverflow.com/users/15209",
"pm_score": 3,
"selected": false,
"text": "<p>If you want a human-readable result, you can also use this type of file :</p>\n\n<pre><code>ofaurax|27|male|something|\nanother|24|unknown||\n...\n</code></pre>\n\n<p>This way, you have only one file, you can debug it (and manually fix) easily, you can add fields later (at the end of each line) and the PHP code is simple (for each line, split according to |).</p>\n\n<p>However, the drawbacks is that you should parse the entire file to search something (if you have millions of entry, it's not fine) and you should handle the separator in data (for example if the nick is WaR|ordz).</p>\n"
},
{
"answer_id": 111609,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 5,
"selected": false,
"text": "<p>In my opinion, using a "Flat File Database" in the sense you're meaning (and the answer you've accepted) isn't necessarily the best way to go about things. First of all, using <code>serialize()</code> and <code>unserialize()</code> can cause MAJOR headaches if someone gets in and edits the file (they can, in fact, put arbitrary code in your "database" to be run each time.)</p>\n<p>Personally, I'd say - why not look to the future? There have been so many times that I've had issues because I've been creating my own "proprietary" files, and the project has exploded to a point where it needs a database, and I'm thinking "you know, I wish I'd written this for a database to start with" - because the refactoring of the code takes way too much time and effort.</p>\n<p>From this I've learnt that future proofing my application so that when it gets bigger I don't have to go and spend days refactoring is the way to go forward. How do I do this?</p>\n<p>SQLite. It works as a database, uses SQL, and is pretty easy to change over to MySQL (especially if you're using abstracted classes for database manipulation like I do!)</p>\n<p>In fact, especially with the "accepted answer"'s method, it can drastically cut the memory usage of your app (you don't have to load all the "RECORDS" into PHP)</p>\n"
},
{
"answer_id": 242850,
"author": "Ryan McCue",
"author_id": 2575,
"author_profile": "https://Stackoverflow.com/users/2575",
"pm_score": 3,
"selected": false,
"text": "<p>Here's the code we use for Lilina:</p>\n\n<pre><code><?php\n/**\n * Handler for persistent data files\n *\n * @author Ryan McCue <cubegames@gmail.com>\n * @package Lilina\n * @version 1.0\n * @license http://opensource.org/licenses/gpl-license.php GNU Public License\n */\n\n/**\n * Handler for persistent data files\n *\n * @package Lilina\n */\nclass DataHandler {\n /**\n * Directory to store data.\n *\n * @since 1.0\n *\n * @var string\n */\n protected $directory;\n\n /**\n * Constructor, duh.\n *\n * @since 1.0\n * @uses $directory Holds the data directory, which the constructor sets.\n *\n * @param string $directory \n */\n public function __construct($directory = null) {\n if ($directory === null)\n $directory = get_data_dir();\n\n if (substr($directory, -1) != '/')\n $directory .= '/';\n\n $this->directory = (string) $directory;\n }\n\n /**\n * Prepares filename and content for saving\n *\n * @since 1.0\n * @uses $directory\n * @uses put()\n *\n * @param string $filename Filename to save to\n * @param string $content Content to save to cache\n */\n public function save($filename, $content) {\n $file = $this->directory . $filename;\n\n if(!$this->put($file, $content)) {\n trigger_error(get_class($this) . \" error: Couldn't write to $file\", E_USER_WARNING);\n return false;\n }\n\n return true;\n }\n\n /**\n * Saves data to file\n *\n * @since 1.0\n * @uses $directory\n *\n * @param string $file Filename to save to\n * @param string $data Data to save into $file\n */\n protected function put($file, $data, $mode = false) {\n if(file_exists($file) && file_get_contents($file) === $data) {\n touch($file);\n return true;\n }\n\n if(!$fp = @fopen($file, 'wb')) {\n return false;\n }\n\n fwrite($fp, $data);\n fclose($fp);\n\n $this->chmod($file, $mode);\n return true;\n\n }\n\n /**\n * Change the file permissions\n *\n * @since 1.0\n *\n * @param string $file Absolute path to file\n * @param integer $mode Octal mode\n */\n protected function chmod($file, $mode = false){\n if(!$mode)\n $mode = 0644;\n return @chmod($file, $mode);\n }\n\n /**\n * Returns the content of the cached file if it is still valid\n *\n * @since 1.0\n * @uses $directory\n * @uses check() Check if cache file is still valid\n *\n * @param string $id Unique ID for content type, used to distinguish between different caches\n * @return null|string Content of the cached file if valid, otherwise null\n */\n public function load($filename) {\n return $this->get($this->directory . $filename);\n }\n\n /**\n * Returns the content of the file\n *\n * @since 1.0\n * @uses $directory\n * @uses check() Check if file is valid\n *\n * @param string $id Filename to load data from\n * @return bool|string Content of the file if valid, otherwise null\n */\n protected function get($filename) {\n if(!$this->check($filename))\n return null;\n\n return file_get_contents($filename);\n }\n\n /**\n * Check a file for validity\n *\n * Basically just a fancy alias for file_exists(), made primarily to be\n * overriden.\n *\n * @since 1.0\n * @uses $directory\n *\n * @param string $id Unique ID for content type, used to distinguish between different caches\n * @return bool False if the cache doesn't exist or is invalid, otherwise true\n */\n protected function check($filename){\n return file_exists($filename);\n }\n\n /**\n * Delete a file\n *\n * @param string $filename Unique ID\n */\n public function delete($filename) {\n return unlink($this->directory . $filename);\n }\n}\n\n?>\n</code></pre>\n\n<p>It stores each entry as a separate file, which we found is efficient enough for use (no unneeded data is loaded and it's faster to save).</p>\n"
},
{
"answer_id": 13670880,
"author": "siliconrockstar",
"author_id": 761967,
"author_profile": "https://Stackoverflow.com/users/761967",
"pm_score": 3,
"selected": false,
"text": "<p>IMHO, you have two... er, three options if you want to avoid homebrewing something:</p>\n<ol>\n<li><strong>SQLite</strong></li>\n</ol>\n<p>If you're familiar with PDO, you can install a PDO driver that supports SQLite. Never used it, but I have used PDO a ton with MySQL. I'm going to give this a shot on a current project.</p>\n<ol start=\"2\">\n<li><strong>XML</strong></li>\n</ol>\n<p>Done this many times for relatively small amounts of data. <a href=\"http://us1.php.net/manual/en/intro.xmlreader.php\" rel=\"nofollow noreferrer\">XMLReader</a> is a lightweight, read-forward, cursor-style class. <a href=\"http://us1.php.net/manual/en/intro.simplexml.php\" rel=\"nofollow noreferrer\">SimpleXML</a> makes it simple to read an XML document into an object that you can access just like any other class instance.</p>\n<ol start=\"3\">\n<li><strong>JSON</strong> (update)</li>\n</ol>\n<p>Good option for smallish amounts of data, just read/write file and json_decode/json_encode. Not sure if PHP offers a structure to navigate a JSON tree without loading it all in memory though.</p>\n"
},
{
"answer_id": 13960906,
"author": "jpcrevoisier",
"author_id": 1916991,
"author_profile": "https://Stackoverflow.com/users/1916991",
"pm_score": 3,
"selected": false,
"text": "<p>I have written two simple functions designed to store data in a file. You can judge for yourself if it's useful in this case.\nThe point is to save a php variable (if it's either an array a string or an object) to a file.</p>\n\n<pre><code><?php\nfunction varname(&$var) {\n $oldvalue=$var;\n $var='AAAAB3NzaC1yc2EAAAABIwAAAQEAqytmUAQKMOj24lAjqKJC2Gyqhbhb+DmB9eDDb8+QcFI+QOySUpYDn884rgKB6EAtoFyOZVMA6HlNj0VxMKAGE+sLTJ40rLTcieGRCeHJ/TI37e66OrjxgB+7tngKdvoG5EF9hnoGc4eTMpVUDdpAK3ykqR1FIclgk0whV7cEn/6K4697zgwwb5R2yva/zuTX+xKRqcZvyaF3Ur0Q8T+gvrAX8ktmpE18MjnA5JuGuZFZGFzQbvzCVdN52nu8i003GEFmzp0Ny57pWClKkAy3Q5P5AR2BCUwk8V0iEX3iu7J+b9pv4LRZBQkDujaAtSiAaeG2cjfzL9xIgWPf+J05IQ==';\n foreach($GLOBALS as $var_name => $value) {\n if ($value === 'AAAAB3NzaC1yc2EAAAABIwAAAQEAqytmUAQKMOj24lAjqKJC2Gyqhbhb+DmB9eDDb8+QcFI+QOySUpYDn884rgKB6EAtoFyOZVMA6HlNj0VxMKAGE+sLTJ40rLTcieGRCeHJ/TI37e66OrjxgB+7tngKdvoG5EF9hnoGc4eTMpVUDdpAK3ykqR1FIclgk0whV7cEn/6K4697zgwwb5R2yva/zuTX+xKRqcZvyaF3Ur0Q8T+gvrAX8ktmpE18MjnA5JuGuZFZGFzQbvzCVdN52nu8i003GEFmzp0Ny57pWClKkAy3Q5P5AR2BCUwk8V0iEX3iu7J+b9pv4LRZBQkDujaAtSiAaeG2cjfzL9xIgWPf+J05IQ==')\n {\n $var=$oldvalue;\n return $var_name;\n }\n }\n $var=$oldvalue;\n return false;\n}\n\nfunction putphp(&$var, $file=false)\n {\n $varname=varname($var);\n if(!$file)\n {\n $file=$varname.'.php';\n }\n $pathinfo=pathinfo($file);\n if(file_exists($file))\n {\n if(is_dir($file))\n {\n $file=$pathinfo['dirname'].'/'.$pathinfo['basename'].'/'.$varname.'.php';\n }\n }\n file_put_contents($file,'<?php'.\"\\n\\$\".$varname.'='.var_export($var, true).\";\\n\");\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 14149357,
"author": "Michael Burt",
"author_id": 1947156,
"author_profile": "https://Stackoverflow.com/users/1947156",
"pm_score": 3,
"selected": false,
"text": "<p>Just pointing out a potential problem with a flat file database with this type of system:</p>\n\n<pre><code>data|some text|more data\n\nrow 2 data|bla hbalh|more data\n</code></pre>\n\n<p>...etc</p>\n\n<p>The problem is that the cell data contains a \"|\" or a \"\\n\" then the data will be lost. Sometimes it would be easier to split by combinations of letters that most people wouldn't use.</p>\n\n<p>For example:</p>\n\n<p>Column splitter: <code>#$% (Shift+345)</code></p>\n\n<p>Row splitter: <code>^&* (Shift+678)</code></p>\n\n<p>Text file: <code>test data#$%blah blah#$%^&*new row#$%new row data 2</code></p>\n\n<p>Then use: <code>explode(\"#$%\", $data); use foreach, the explode again to separate columns</code></p>\n\n<p>Or anything along these lines. Also, I might add that flat file databases are good for systems with small amounts of data (ie. less than 20 rows), but become huge memory hogs for larger databases.</p>\n"
},
{
"answer_id": 16339974,
"author": "omran",
"author_id": 2343402,
"author_profile": "https://Stackoverflow.com/users/2343402",
"pm_score": 3,
"selected": false,
"text": "<p>This one is inspiring as a practical solution:<br>\n<a href=\"https://github.com/mhgolkar/FlatFire\" rel=\"noreferrer\">https://github.com/mhgolkar/FlatFire</a><br>\nIt uses multiple strategies to handling data...<br>\n[Copied from Readme File]</p>\n\n<h3>Free or Structured or Mixed</h3>\n\n<pre><code>- STRUCTURED\nRegular (table, row, column) format.\n[DATABASE]\n/ \\\nTX TableY\n \\_____________________________\n |ROW_0 Colum_0 Colum_1 Colum_2|\n |ROW_1 Colum_0 Colum_1 Colum_2|\n |_____________________________|\n- FREE\nMore creative data storing. You can store data in any structure you want for each (free) element, its similar to storing an array with a unique \"Id\".\n[DATABASE]\n/ \\\nEX ElementY (ID)\n \\________________\n |Field_0 Value_0 |\n |Field_1 Value_1 |\n |Field_2 Value_2 |\n |________________|\nrecall [ID]: get_free(\"ElementY\") --> array([Field_0]=>Value_0,[Field_1]=>Value_1...\n- MIXD (Mixed)\nMixed databases can store both free elements and tables.If you add a table to a free db or a free element to a structured db, flat fire will automatically convert FREE or SRCT to MIXD database.\n[DATABASE]\n/ \\\nEX TY\n</code></pre>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/85",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/59/"
] | What are the best practices around creating flat file database structures in PHP?
A lot of more matured PHP flat file frameworks out there which I attempt to implement SQL-like query syntax which is over the top for my purposes in most cases. (I would just use a database at that point).
Are there any elegant tricks out there to get good performance and features with a small code overhead? | Well, what is the nature of the flat databases. Are they large or small. Is it simple arrays with arrays in them? if its something simple say userprofiles built as such:
```
$user = array("name" => "bob",
"age" => 20,
"websites" => array("example.com","bob.example.com","bob2.example.com"),
"and_one" => "more");
```
and to save or update the *db record* for that user.
```
$dir = "../userdata/"; //make sure to put it bellow what the server can reach.
file_put_contents($dir.$user['name'],serialize($user));
```
and to load the *record* for the user
```
function &get_user($name){
return unserialize(file_get_contents("../userdata/".$name));
}
```
but again this implementation will vary on the application and nature of the database you need. |
88 | <p>I am porting a game, that was originally written for the Win32 API, to Linux (well, porting the OS X port of the Win32 port to Linux).</p>
<p>I have implemented <code>QueryPerformanceCounter</code> by giving the uSeconds since the process start up: </p>
<pre><code>BOOL QueryPerformanceCounter(LARGE_INTEGER* performanceCount)
{
gettimeofday(&currentTimeVal, NULL);
performanceCount->QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec);
performanceCount->QuadPart *= (1000 * 1000);
performanceCount->QuadPart += (currentTimeVal.tv_usec - startTimeVal.tv_usec);
return true;
}
</code></pre>
<p>This, coupled with <code>QueryPerformanceFrequency()</code> giving a constant 1000000 as the frequency, works well <b>on my machine</b>, giving me a 64-bit variable that contains <code>uSeconds</code> since the program's start-up.</p>
<p>So <em>is this portable?</em> I don't want to discover it works differently if the kernel was compiled in a certain way or anything like that. I am fine with it being non-portable to something other than Linux, however.</p>
| [
{
"answer_id": 93,
"author": "CodingWithoutComments",
"author_id": 25,
"author_profile": "https://Stackoverflow.com/users/25",
"pm_score": 2,
"selected": false,
"text": "<p>From my experience, and from what I've read across the internet, the answer is \"No,\" it is not guaranteed. It depends on CPU speed, operating system, flavor of Linux, etc.</p>\n"
},
{
"answer_id": 98,
"author": "Louis Brandy",
"author_id": 2089740,
"author_profile": "https://Stackoverflow.com/users/2089740",
"pm_score": 7,
"selected": true,
"text": "<p>Maybe. But you have bigger problems. <code>gettimeofday()</code> can result in incorrect timings if there are processes on your system that change the timer (ie, ntpd). On a \"normal\" linux, though, I believe the resolution of <code>gettimeofday()</code> is 10us. It can jump forward and backward and time, consequently, based on the processes running on your system. This effectively makes the answer to your question no.</p>\n\n<p>You should look into <code>clock_gettime(CLOCK_MONOTONIC)</code> for timing intervals. It suffers from several less issues due to things like multi-core systems and external clock settings.</p>\n\n<p>Also, look into the <code>clock_getres()</code> function.</p>\n"
},
{
"answer_id": 99,
"author": "CodingWithoutComments",
"author_id": 25,
"author_profile": "https://Stackoverflow.com/users/25",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>The actual resolution of gettimeofday() depends on the hardware architecture. Intel processors as well as SPARC machines offer high resolution timers that measure microseconds. Other hardware architectures fall back to the system’s timer, which is typically set to 100 Hz. In such cases, the time resolution will be less accurate. </p>\n</blockquote>\n\n<p>I obtained this answer from <a href=\"http://web.archive.org/web/20160711223333/http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=272\" rel=\"nofollow noreferrer\">High Resolution Time Measurement and Timers, Part I</a></p>\n"
},
{
"answer_id": 367,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": false,
"text": "<p><strong>High Resolution, Low Overhead Timing for Intel Processors</strong></p>\n\n<p>If you're on Intel hardware, here's how to read the CPU real-time instruction counter. It will tell you the number of CPU cycles executed since the processor was booted. This is probably the finest-grained counter you can get for performance measurement.</p>\n\n<p>Note that this is the number of CPU cycles. On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds. Converting this to a double is quite handy.</p>\n\n<p>When I run this on my box, I get</p>\n\n<pre><code>11867927879484732\n11867927879692217\nit took this long to call printf: 207485\n</code></pre>\n\n<p>Here's the <a href=\"http://cs.smu.ca/~jamuir/rdtscpm1.pdf\" rel=\"noreferrer\">Intel developer's guide</a> that gives tons of detail.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdint.h>\n\ninline uint64_t rdtsc() {\n uint32_t lo, hi;\n __asm__ __volatile__ (\n \"xorl %%eax, %%eax\\n\"\n \"cpuid\\n\"\n \"rdtsc\\n\"\n : \"=a\" (lo), \"=d\" (hi)\n :\n : \"%ebx\", \"%ecx\");\n return (uint64_t)hi << 32 | lo;\n}\n\nmain()\n{\n unsigned long long x;\n unsigned long long y;\n x = rdtsc();\n printf(\"%lld\\n\",x);\n y = rdtsc();\n printf(\"%lld\\n\",y);\n printf(\"it took this long to call printf: %lld\\n\",y-x);\n}\n</code></pre>\n"
},
{
"answer_id": 522,
"author": "Joe Shaw",
"author_id": 156,
"author_profile": "https://Stackoverflow.com/users/156",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>So it says microseconds explicitly, but says the resolution of the system clock is unspecified. I suppose resolution in this context means how the smallest amount it will ever be incremented?</p>\n</blockquote>\n\n<p>The data structure is defined as having microseconds as a unit of measurement, but that doesn't mean that the clock or operating system is actually capable of measuring that finely.</p>\n\n<p>Like other people have suggested, <code>gettimeofday()</code> is bad because setting the time can cause clock skew and throw off your calculation. <code>clock_gettime(CLOCK_MONOTONIC)</code> is what you want, and <code>clock_getres()</code> will tell you the precision of your clock.</p>\n"
},
{
"answer_id": 931,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": false,
"text": "<p>@Bernard:</p>\n\n<blockquote>\n <p>I have to admit, most of your example went straight over my head. It does compile, and seems to work, though. Is this safe for SMP systems or SpeedStep?</p>\n</blockquote>\n\n<p>That's a good question... I think the code's ok.\nFrom a practical standpoint, we use it in my company every day,\nand we run on a pretty wide array of boxes, everything from 2-8 cores.\nOf course, YMMV, etc, but it seems to be a reliable and low-overhead\n(because it doesn't make a context switch into system-space) method\nof timing.</p>\n\n<p>Generally how it works is:</p>\n\n<ul>\n<li>declare the block of code to be assembler (and volatile, so the\noptimizer will leave it alone).</li>\n<li>execute the CPUID instruction. In addition to getting some CPU information\n(which we don't do anything with) it synchronizes the CPU's execution buffer\nso that the timings aren't affected by out-of-order execution.</li>\n<li>execute the rdtsc (read timestamp) execution. This fetches the number of\nmachine cycles executed since the processor was reset. This is a 64-bit\nvalue, so with current CPU speeds it will wrap around every 194 years or so.\nInterestingly, in the original Pentium reference, they note it wraps around every\n5800 years or so.</li>\n<li>the last couple of lines store the values from the registers into\nthe variables hi and lo, and put that into the 64-bit return value.</li>\n</ul>\n\n<p>Specific notes:</p>\n\n<ul>\n<li><p>out-of-order execution can cause incorrect results, so we execute the\n\"cpuid\" instruction which in addition to giving you some information\nabout the cpu also synchronizes any out-of-order instruction execution.</p></li>\n<li><p>Most OS's synchronize the counters on the CPUs when they start, so\nthe answer is good to within a couple of nano-seconds.</p></li>\n<li><p>The hibernating comment is probably true, but in practice you\nprobably don't care about timings across hibernation boundaries.</p></li>\n<li><p>regarding speedstep: Newer Intel CPUs compensate for the speed\nchanges and returns an adjusted count. I did a quick scan over\nsome of the boxes on our network and found only one box that\ndidn't have it: a Pentium 3 running some old database server.\n(these are linux boxes, so I checked with: grep constant_tsc /proc/cpuinfo)</p></li>\n<li><p>I'm not sure about the AMD CPUs, we're primarily an Intel shop,\nalthough I know some of our low-level systems gurus did an\nAMD evaluation.</p></li>\n</ul>\n\n<p>Hope this satisfies your curiosity, it's an interesting and (IMHO)\nunder-studied area of programming. You know when Jeff and Joel were\ntalking about whether or not a programmer should know C? I was\nshouting at them, \"hey forget that high-level C stuff... assembler\nis what you should learn if you want to know what the computer is\ndoing!\"</p>\n"
},
{
"answer_id": 1290,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 4,
"selected": false,
"text": "<p>Wine is actually using gettimeofday() to implement QueryPerformanceCounter() and it is known to make many Windows games work on Linux and Mac.</p>\n\n<p>Starts <a href=\"http://source.winehq.org/source/dlls/kernel32/cpu.c#L312\" rel=\"noreferrer\">http://source.winehq.org/source/dlls/kernel32/cpu.c#L312</a></p>\n\n<p>leads to <a href=\"http://source.winehq.org/source/dlls/ntdll/time.c#L448\" rel=\"noreferrer\">http://source.winehq.org/source/dlls/ntdll/time.c#L448</a></p>\n"
},
{
"answer_id": 14807,
"author": "Doug",
"author_id": 1618,
"author_profile": "https://Stackoverflow.com/users/1618",
"pm_score": 2,
"selected": false,
"text": "<p>Reading the RDTSC is not reliable in SMP systems, since each CPU maintains their own counter and each counter is not guaranteed to by synchronized with respect to another CPU.</p>\n\n<p>I might suggest trying <strong><code>clock_gettime(CLOCK_REALTIME)</code></strong>. The posix manual indicates that this should be implemented on all compliant systems. It can provide a nanosecond count, but you probably will want to check <strong><code>clock_getres(CLOCK_REALTIME)</code></strong> on your system to see what the actual resolution is.</p>\n"
},
{
"answer_id": 14817,
"author": "David Schlosnagle",
"author_id": 1750,
"author_profile": "https://Stackoverflow.com/users/1750",
"pm_score": 4,
"selected": false,
"text": "<p>You may be interested in <a href=\"http://juliusdavies.ca/posix_clocks/clock_realtime_linux_faq.html\" rel=\"noreferrer\">Linux FAQ for <code>clock_gettime(CLOCK_REALTIME)</code></a></p>\n"
},
{
"answer_id": 11211298,
"author": "bames53",
"author_id": 365496,
"author_profile": "https://Stackoverflow.com/users/365496",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/98/\">This answer</a> mentions problems with the clock being adjusted. Both your problems guaranteeing tick units and the problems with the time being adjusted are solved in C++11 with the <code><chrono></code> library.</p>\n\n<p>The clock <code>std::chrono::steady_clock</code> is guaranteed not to be adjusted, and furthermore it will advance at a constant rate relative to real time, so technologies like SpeedStep must not affect it.</p>\n\n<p>You can get typesafe units by converting to one of the <code>std::chrono::duration</code> specializations, such as <code>std::chrono::microseconds</code>. With this type there's no ambiguity about the units used by the tick value. However, keep in mind that the clock doesn't necessarily have this resolution. You can convert a duration to attoseconds without actually having a clock that accurate.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/88",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | I am porting a game, that was originally written for the Win32 API, to Linux (well, porting the OS X port of the Win32 port to Linux).
I have implemented `QueryPerformanceCounter` by giving the uSeconds since the process start up:
```
BOOL QueryPerformanceCounter(LARGE_INTEGER* performanceCount)
{
gettimeofday(¤tTimeVal, NULL);
performanceCount->QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec);
performanceCount->QuadPart *= (1000 * 1000);
performanceCount->QuadPart += (currentTimeVal.tv_usec - startTimeVal.tv_usec);
return true;
}
```
This, coupled with `QueryPerformanceFrequency()` giving a constant 1000000 as the frequency, works well **on my machine**, giving me a 64-bit variable that contains `uSeconds` since the program's start-up.
So *is this portable?* I don't want to discover it works differently if the kernel was compiled in a certain way or anything like that. I am fine with it being non-portable to something other than Linux, however. | Maybe. But you have bigger problems. `gettimeofday()` can result in incorrect timings if there are processes on your system that change the timer (ie, ntpd). On a "normal" linux, though, I believe the resolution of `gettimeofday()` is 10us. It can jump forward and backward and time, consequently, based on the processes running on your system. This effectively makes the answer to your question no.
You should look into `clock_gettime(CLOCK_MONOTONIC)` for timing intervals. It suffers from several less issues due to things like multi-core systems and external clock settings.
Also, look into the `clock_getres()` function. |
109 | <p>Recently our site has been deluged with the resurgence of the <a href="https://en.wikipedia.org/wiki/Asprox_botnet" rel="noreferrer">Asprox botnet</a> <a href="http://en.wikipedia.org/wiki/SQL_injection" rel="noreferrer">SQL injection</a> attack. Without going into details, the attack attempts to execute SQL code by encoding the <a href="http://en.wikipedia.org/wiki/Transact-SQL" rel="noreferrer">T-SQL</a> commands in an ASCII encoded BINARY string. It looks something like this:</p>
<pre><code>DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST(0x44004500...06F007200%20AS%20NVARCHAR(4000));EXEC(@S);--
</code></pre>
<p>I was able to decode this in SQL, but I was a little wary of doing this since I didn't know exactly what was happening at the time.</p>
<p>I tried to write a simple decode tool, so I could decode this type of text without even touching <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="noreferrer">SQL Server</a>. The main part I need to be decoded is:</p>
<pre><code>CAST(0x44004500...06F007200 AS
NVARCHAR(4000))
</code></pre>
<p>I've tried all of the following commands with no luck:</p>
<pre><code>txtDecodedText.Text =
System.Web.HttpUtility.UrlDecode(txtURLText.Text);
txtDecodedText.Text =
Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(txtURLText.Text));
txtDecodedText.Text =
Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(txtURLText.Text));
txtDecodedText.Text =
Encoding.ASCII.GetString(Encoding.Unicode.GetBytes(txtURLText.Text));
txtDecodedText.Text =
Encoding.Unicode.GetString(Convert.FromBase64String(txtURLText.Text));
</code></pre>
<p>What is the proper way to translate this encoding without using SQL Server? Is it possible? I'll take VB.NET code since I'm familiar with that too.</p>
<hr>
<p>Okay, I'm sure I'm missing something here, so here's where I'm at.</p>
<p>Since my input is a basic string, I started with just a snippet of the encoded portion - 4445434C41 (which translates to DECLA) - and the first attempt was to do this...</p>
<pre><code>txtDecodedText.Text = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(txtURL.Text));
</code></pre>
<p>...and all it did was return the exact same thing that I put in since it converted each character into is a byte.</p>
<p>I realized that I need to parse every two characters into a byte manually since I don't know of any methods yet that will do that, so now my little decoder looks something like this:</p>
<pre><code>while (!boolIsDone)
{
bytURLChar = byte.Parse(txtURLText.Text.Substring(intParseIndex, 2));
bytURL[intURLIndex] = bytURLChar;
intParseIndex += 2;
intURLIndex++;
if (txtURLText.Text.Length - intParseIndex < 2)
{
boolIsDone = true;
}
}
txtDecodedText.Text = Encoding.UTF8.GetString(bytURL);
</code></pre>
<p>Things look good for the first couple of pairs, but then the loop balks when it gets to the "4C" pair and says that the string is in the incorrect format.</p>
<p>Interestingly enough, when I step through the debugger and to the GetString method on the byte array that I was able to parse up to that point, I get ",-+" as the result.</p>
<p>How do I figure out what I'm missing - do I need to do a "direct cast" for each byte instead of attempting to parse it?</p>
| [
{
"answer_id": 304,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 3,
"selected": false,
"text": "<p>Try removing the <code>0x</code> first and then call <code>Encoding.UTF8.GetString</code>. I think that may work.</p>\n\n<p>Essentially: 0x44004500</p>\n\n<p>Remove the 0x, and then always two bytes are one character:</p>\n\n<pre><code>44 00 = D\n\n45 00 = E\n\n6F 00 = o\n\n72 00 = r\n</code></pre>\n\n<p>So it's definitely a Unicode/UTF format with two bytes/character.</p>\n"
},
{
"answer_id": 2585,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 6,
"selected": true,
"text": "<p>I went back to Michael's post, did some more poking and realized that I did need to do a double conversion, and eventually worked out this little nugget:</p>\n\n<pre><code>Convert.ToString(Convert.ToChar(Int32.Parse(EncodedString.Substring(intParseIndex, 2), System.Globalization.NumberStyles.HexNumber)));\n</code></pre>\n\n<p>From there I simply made a loop to go through all the characters 2 by 2 and get them \"hexified\" and then translated to a string.</p>\n\n<p>To Nick, and anybody else interested, I went ahead and <a href=\"http://www.codeplex.com/urldecoder\" rel=\"nofollow noreferrer\">posted my little application</a> over in <a href=\"http://en.wikipedia.org/wiki/CodePlex\" rel=\"nofollow noreferrer\">CodePlex</a>. Feel free to use/modify as you need.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
] | Recently our site has been deluged with the resurgence of the [Asprox botnet](https://en.wikipedia.org/wiki/Asprox_botnet) [SQL injection](http://en.wikipedia.org/wiki/SQL_injection) attack. Without going into details, the attack attempts to execute SQL code by encoding the [T-SQL](http://en.wikipedia.org/wiki/Transact-SQL) commands in an ASCII encoded BINARY string. It looks something like this:
```
DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST(0x44004500...06F007200%20AS%20NVARCHAR(4000));EXEC(@S);--
```
I was able to decode this in SQL, but I was a little wary of doing this since I didn't know exactly what was happening at the time.
I tried to write a simple decode tool, so I could decode this type of text without even touching [SQL Server](http://en.wikipedia.org/wiki/Microsoft_SQL_Server). The main part I need to be decoded is:
```
CAST(0x44004500...06F007200 AS
NVARCHAR(4000))
```
I've tried all of the following commands with no luck:
```
txtDecodedText.Text =
System.Web.HttpUtility.UrlDecode(txtURLText.Text);
txtDecodedText.Text =
Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(txtURLText.Text));
txtDecodedText.Text =
Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(txtURLText.Text));
txtDecodedText.Text =
Encoding.ASCII.GetString(Encoding.Unicode.GetBytes(txtURLText.Text));
txtDecodedText.Text =
Encoding.Unicode.GetString(Convert.FromBase64String(txtURLText.Text));
```
What is the proper way to translate this encoding without using SQL Server? Is it possible? I'll take VB.NET code since I'm familiar with that too.
---
Okay, I'm sure I'm missing something here, so here's where I'm at.
Since my input is a basic string, I started with just a snippet of the encoded portion - 4445434C41 (which translates to DECLA) - and the first attempt was to do this...
```
txtDecodedText.Text = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(txtURL.Text));
```
...and all it did was return the exact same thing that I put in since it converted each character into is a byte.
I realized that I need to parse every two characters into a byte manually since I don't know of any methods yet that will do that, so now my little decoder looks something like this:
```
while (!boolIsDone)
{
bytURLChar = byte.Parse(txtURLText.Text.Substring(intParseIndex, 2));
bytURL[intURLIndex] = bytURLChar;
intParseIndex += 2;
intURLIndex++;
if (txtURLText.Text.Length - intParseIndex < 2)
{
boolIsDone = true;
}
}
txtDecodedText.Text = Encoding.UTF8.GetString(bytURL);
```
Things look good for the first couple of pairs, but then the loop balks when it gets to the "4C" pair and says that the string is in the incorrect format.
Interestingly enough, when I step through the debugger and to the GetString method on the byte array that I was able to parse up to that point, I get ",-+" as the result.
How do I figure out what I'm missing - do I need to do a "direct cast" for each byte instead of attempting to parse it? | I went back to Michael's post, did some more poking and realized that I did need to do a double conversion, and eventually worked out this little nugget:
```
Convert.ToString(Convert.ToChar(Int32.Parse(EncodedString.Substring(intParseIndex, 2), System.Globalization.NumberStyles.HexNumber)));
```
From there I simply made a loop to go through all the characters 2 by 2 and get them "hexified" and then translated to a string.
To Nick, and anybody else interested, I went ahead and [posted my little application](http://www.codeplex.com/urldecoder) over in [CodePlex](http://en.wikipedia.org/wiki/CodePlex). Feel free to use/modify as you need. |
126 | <p>What is the "purist" or "correct" way to access an object's properties from within an object method that is not a getter/setter method?</p>
<p>I know that from outside of the object you should use a getter/setter, but from within would you just do:</p>
<p>Java:</p>
<pre><code>String property = this.property;
</code></pre>
<p>PHP:</p>
<pre><code>$property = $this->property;
</code></pre>
<p>or would you do:</p>
<p>Java:</p>
<pre><code>String property = this.getProperty();
</code></pre>
<p>PHP:</p>
<pre><code>$property = $this->getProperty();
</code></pre>
<p>Forgive me if my Java is a little off, it's been a year since I programmed in Java...</p>
<p><strong>EDIT:</strong></p>
<p>It seems people are assuming I am talking about private or protected variables/properties only. When I learned OO I was taught to use getters/setters for every single property even if it was public (and actually I was told never to make any variable/property public). So, I may be starting off from a false assumption from the get go. It appears that people answering this question are maybe saying that you should have public properties and that those don't need getters and setters, which goes against what I was taught, and what I was talking about, although maybe that needs to be discussed as well. That's probably a good topic for a different question though...</p>
| [
{
"answer_id": 127,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 7,
"selected": true,
"text": "<p>This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that <em>needs</em> to run every time that property is set, and the property is being set internally w/o that setter being called).</p>\n"
},
{
"answer_id": 128,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 4,
"selected": false,
"text": "<p>It depends on how the property is used. For example, say you have a student object that has a name property. You could use your Get method to pull the name from the database, if it hasn't been retrieved already. This way you are reducing unnecessary calls to the database.</p>\n\n<p>Now let's say you have a private integer counter in your object that counts the number of times the name has been called. You may want to not use the Get method from inside the object because it would produce an invalid count.</p>\n"
},
{
"answer_id": 139,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>Am I just going overboard here?</p>\n</blockquote>\n\n<p>Perhaps ;)</p>\n\n<p>Another approach would be to utilize a private/protected method to actually do the getting (caching/db/etc), and a public wrapper for it that increments the count:</p>\n\n<p>PHP:</p>\n\n<pre><code>public function getName() {\n $this->incrementNameCalled();\n return $this->_getName();\n}\n\nprotected function _getName() {\n return $this->name;\n}\n</code></pre>\n\n<p>and then from within the object itself:</p>\n\n<p>PHP:</p>\n\n<pre><code>$name = $this->_getName();\n</code></pre>\n\n<p>This way you can still use that first argument for something else (like sending a flag for whether or not to used cached data here perhaps).</p>\n"
},
{
"answer_id": 142,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 3,
"selected": false,
"text": "<p>Well, it seems with C# 3.0 properties' default implementation, the decision is taken for you; you HAVE to set the property using the (possibly private) property setter.</p>\n\n<p>I personally only use the private member-behind when not doing so would cause the object to fall in an less than desirable state, such as when initializing or when caching/lazy loading is involved.</p>\n"
},
{
"answer_id": 143,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 3,
"selected": false,
"text": "<p>As stated in some of the comments: Sometimes you should, sometimes you shouldn't. The great part about private variables is that you are able to see all the places they are used when you change something. If your getter/setter does something you need, use it. If it doesn't matter you decide.</p>\n\n<p>The opposite case could be made that if you use the getter/setter and somebody changes the getter/setter they have to analyze all the places the getter and setter is used internally to see if it messes something up.</p>\n"
},
{
"answer_id": 169,
"author": "MojoFilter",
"author_id": 93,
"author_profile": "https://Stackoverflow.com/users/93",
"pm_score": 5,
"selected": false,
"text": "<p>Personally, I feel like it's important to remain consistent. If you have getters and setters, use them. The only time I would access a field directly is when the accessor has a lot of overhead. It may feel like you're bloating your code unnecessarily, but it can certainly save a whole lot of headache in the future. The classic example:</p>\n\n<p>Later on, you may desire to change the way that field works. Maybe it should be calculated on-the-fly or maybe you would like to use a different type for the backing store. If you are accessing properties directly, a change like that can break an awful lot of code in one swell foop.</p>\n"
},
{
"answer_id": 3485,
"author": "Telcontar",
"author_id": 518,
"author_profile": "https://Stackoverflow.com/users/518",
"pm_score": 3,
"selected": false,
"text": "<p>I can be wrong because I'm autodidact, but I NEVER user public properties in my Java classes, they are always private or protected, so that outside code must access by getters/setters. It's better for maintenance / modification purposes. And for inside class code... If getter method is trivial I use the property directly, but I always use the setter methods because I could easily add code to fire events if I wish.</p>\n"
},
{
"answer_id": 14968,
"author": "Brendon-Van-Heyzen",
"author_id": 1425,
"author_profile": "https://Stackoverflow.com/users/1425",
"pm_score": 3,
"selected": false,
"text": "<p>i've found using setters/getters made my code easier to read. I also like the control it gives when other classes use the methods and if i change the data the property will store.</p>\n"
},
{
"answer_id": 14980,
"author": "Mel",
"author_id": 1763,
"author_profile": "https://Stackoverflow.com/users/1763",
"pm_score": 3,
"selected": false,
"text": "<p>Private fields with public or protected properties. Access to the values should go through the properties, and be copied to a local variable if they will be used more than once in a method. If and ONLY if you have the rest of your application so totally tweaked, rocked out, and otherwise optimized to where accessing values by going through their assosciated properties has become a bottleneck (And that will never EVER happen, I guarantee) should you even begin to consider letting anything other than the properties touch their backing variables directly.</p>\n\n<p>.NET developers can use automatic properties to enforce this since you can't even see the backing variables at design time.</p>\n"
},
{
"answer_id": 22083,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 3,
"selected": false,
"text": "<p>If you mean "most encapsulation" by "purist", then I typically declare all my fields as private and then use "this.field" from within the class itself. For other classes, including subclasses, I access instance state using the getters.</p>\n"
},
{
"answer_id": 22111,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 3,
"selected": false,
"text": "<p>If I don't edit the property, I'll use a public method <code>get_property()</code> unless it's a special occasion such as a MySQLi object inside another object in which case I'll just make the property public and refer to it as <code>$obj->object_property</code>.</p>\n<p>Inside the object it's always $this->property for me.</p>\n"
},
{
"answer_id": 62045,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I like the answer by <a href=\"https://stackoverflow.com/questions/126/how-would-you-access-object-properties-from-within-an-object-method#132\">cmcculloh</a>, but it seems like the most correct one is the answer by <a href=\"https://stackoverflow.com/questions/126/how-would-you-access-object-properties-from-within-an-object-method#127\">Greg Hurlman</a>. Use getter/setter all the time if you started using them from the get-go and/or you are used to working with them.</p>\n<p>As an aside, I personally find that using getter/setter makes the code easier to read and to debug later on.</p>\n"
},
{
"answer_id": 98244,
"author": "moffdub",
"author_id": 10759,
"author_profile": "https://Stackoverflow.com/users/10759",
"pm_score": 5,
"selected": false,
"text": "<p>I'm fairly surprised at how unanimous the sentiment is that <code>getters</code> and setters are fine and good. I suggest the incendiary article by Allen Holub \"<a href=\"http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html\" rel=\"noreferrer\">Getters And Setters Are Evil</a>\". Granted, the title is for shock value, but the author makes valid points.</p>\n\n<p>Essentially, if you have <code>getters</code> and <code>setters</code> for each and every private field, you are making those fields as good as public. You'd be very hard-pressed to change the type of a private field without ripple effects to every class that calls that <code>getter</code>.</p>\n\n<p>Moreover, from a strictly OO point of view, objects should be responding to messages (methods) that correspond to their (hopefully) single responsibility. The vast majority of <code>getters</code> and <code>setters</code> don't make sense for their constituent objects;<code>Pen.dispenseInkOnto(Surface)</code> makes more sense to me than <code>Pen.getColor()</code>.</p>\n\n<p>Getters and setters also encourage users of the class to ask the object for some data, perform a calculation, and then set some other value in the object, better known as procedural programming. You'd be better served to simply tell the object to do what you were going to in the first place; also known as the <a href=\"http://en.wikipedia.org/wiki/GRASP_%28object-oriented_design%29#Information_Expert\" rel=\"noreferrer\">Information Expert</a> idiom.</p>\n\n<p>Getters and setters, however, are necessary evils at the boundary of layers -- UI, persistence, and so forth. Restricted access to a class's internals, such as C++'s friend keyword, Java's package protected access, .NET's internal access, and the <a href=\"http://moffdub.wordpress.com/2008/09/17/friend-classes-in-java-and-c-sharp/\" rel=\"noreferrer\">Friend Class Pattern</a> can help you reduce the visibility of <code>getters</code> and setters to only those who need them.</p>\n"
},
{
"answer_id": 128396,
"author": "Martin Spamer",
"author_id": 15527,
"author_profile": "https://Stackoverflow.com/users/15527",
"pm_score": 3,
"selected": false,
"text": "<p>The question doesn't require an opinion based answer. It is a subject well covered by computing science for decades from the principle of high <a href=\"https://en.wikipedia.org/wiki/Cohesion_(computer_science)\" rel=\"nofollow noreferrer\">cohesion</a>, low <a href=\"https://en.wikipedia.org/wiki/Coupling_(computer_programming)\" rel=\"nofollow noreferrer\">coupling</a> and the <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID principles</a>.</p>\n<p>The <em>purist</em>, read correct, OO way is to minimise coupling and maximise cohesions. Therefore both should be avoided and the <a href=\"https://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">Law of Demeter</a> followed by using the <a href=\"http://c2.com/cgi/wiki?TellDontAsk\" rel=\"nofollow noreferrer\">Tell Don't Ask</a> approach.</p>\n<p>Instead of getting the value of the object's property, which <a href=\"https://stackoverflow.com/questions/2832017/what-is-the-difference-between-loose-coupling-and-tight-coupling-in-object-orien\">tightly couples</a> the two class, use the object as a parameter e.g.</p>\n<pre><code> doSomethingWithProperty() {\n doSomethingWith( this.property ) ;\n }\n</code></pre>\n<p>Where the property was a native type, e.g. int, use an access method, name it for problem domain not the programming domain.</p>\n<pre><code> doSomethingWithProperty( this.daysPerWeek() ) ;\n</code></pre>\n<p>These will allow you to maintain encapsulation and any post-conditions or dependent invariants. You can also use the setter method to maintain any pre-conditions or dependent invariants, however don't fall into the trap of naming them setters, go back to the Hollywood Principle for naming when using the idiom.</p>\n"
},
{
"answer_id": 128488,
"author": "Unlabeled Meat",
"author_id": 20291,
"author_profile": "https://Stackoverflow.com/users/20291",
"pm_score": 4,
"selected": false,
"text": "<p>PHP offers a myriad of ways to handle this, including magic methods <code>__get</code> and <code>__set</code>, but I prefer explicit getters and setters. Here's why:</p>\n\n<ol>\n<li>Validation can be placed in setters (and getters for that matter)</li>\n<li>Intellisense works with explicit methods</li>\n<li>No question whether a property is read only, write only or read-write</li>\n<li>Retrieving virtual properties (ie, calculated values) looks the same as regular properties </li>\n<li>You can easily set an object property that is never actually defined anywhere, which then goes undocumented </li>\n</ol>\n"
},
{
"answer_id": 157081,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 3,
"selected": false,
"text": "<p>It depends. It's more a style issue than anything else, and there is no hard rule.</p>\n"
},
{
"answer_id": 2099971,
"author": "Aadith Ramia",
"author_id": 122466,
"author_profile": "https://Stackoverflow.com/users/122466",
"pm_score": 3,
"selected": false,
"text": "<p>It is better to use the accessor methods, even within the object. Here are the points that come to my mind immediately:</p>\n<ol>\n<li><p>It should be done in the interest of maintaining consistency with accesses made from outside the object.</p>\n</li>\n<li><p>In some cases, these accessor methods could be doing more than just accessing the field; they could be doing some additional processing (this is rare though). If this is the case, accessing the field directly would mean that you are missing that additional processing, and your program could go awry if this processing is always to be done during those accesses.</p>\n</li>\n</ol>\n"
},
{
"answer_id": 6237699,
"author": "Egg Vans",
"author_id": 783844,
"author_profile": "https://Stackoverflow.com/users/783844",
"pm_score": 4,
"selected": false,
"text": "<p>I must be missing the point here, why would you use a getter inside an object to access a property of that object?</p>\n\n<p>Taking this to its conclusion the getter should call a getter, which should call a getter.</p>\n\n<p>So I'd say inside an object method access a property directly, especially seeing as calling another method in that object (which will just access the property directly anyway then return it) is just a pointless, wasteful exercise (or have I misunderstood the question).</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
] | What is the "purist" or "correct" way to access an object's properties from within an object method that is not a getter/setter method?
I know that from outside of the object you should use a getter/setter, but from within would you just do:
Java:
```
String property = this.property;
```
PHP:
```
$property = $this->property;
```
or would you do:
Java:
```
String property = this.getProperty();
```
PHP:
```
$property = $this->getProperty();
```
Forgive me if my Java is a little off, it's been a year since I programmed in Java...
**EDIT:**
It seems people are assuming I am talking about private or protected variables/properties only. When I learned OO I was taught to use getters/setters for every single property even if it was public (and actually I was told never to make any variable/property public). So, I may be starting off from a false assumption from the get go. It appears that people answering this question are maybe saying that you should have public properties and that those don't need getters and setters, which goes against what I was taught, and what I was talking about, although maybe that needs to be discussed as well. That's probably a good topic for a different question though... | This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that *needs* to run every time that property is set, and the property is being set internally w/o that setter being called). |
146 | <p>I have a website that plays mp3s in a flash player. If a user clicks 'play' the flash player automatically downloads an mp3 and starts playing it. </p>
<p>Is there an easy way to track how many times a particular song clip (or any binary file) has been downloaded?</p>
<hr>
<blockquote>
<p>Is the play link a link to the actual
mp3 file or to some javascript code
that pops up a player?</p>
<p>If the latter, you can easily add your
own logging code in there to track the
number of hits to it.</p>
<p>If the former, you'll need something
that can track the web server log
itself and make that distinction. My
hosting plan comes with Webalizer,
which does this nicely.</p>
</blockquote>
<p>It's a javascript code so that answers that. </p>
<p>However, it would be nice to know how to track downloads using the other method (without switching hosts).</p>
| [
{
"answer_id": 148,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 3,
"selected": false,
"text": "<p>Is the play link a link to the actual mp3 file or to some javascript code that pops up a player? </p>\n\n<p>If the latter, you can easily add your own logging code in there to track the number of hits to it.</p>\n\n<p>If the former, you'll need something that can track the web server log itself and make that distinction. My hosting plan comes with webalizer, which does this nicely.</p>\n"
},
{
"answer_id": 152,
"author": "w-ll",
"author_id": 146637,
"author_profile": "https://Stackoverflow.com/users/146637",
"pm_score": 6,
"selected": true,
"text": "<p>The funny thing is I wrote a php media gallery for all my musics 2 days ago. I had a similar problem. I'm using <a href=\"http://musicplayer.sourceforge.net/\" rel=\"nofollow noreferrer\">http://musicplayer.sourceforge.net/</a> for the player. And the playlist is built via php. All music requests go to a script called xfer.php?file=WHATEVER</p>\n<pre><code>$filename = base64_url_decode($_REQUEST['file']);\nheader("Cache-Control: public");\nheader('Content-disposition: attachment; filename='.basename($filename));\nheader("Content-Transfer-Encoding: binary");\nheader('Content-Length: '. filesize($filename));\n\n// Put either file counting code here, either a db or static files\n//\nreadfile($filename); //and spit the user the file\n\nfunction base64_url_decode($input) {\n return base64_decode(strtr($input, '-_,', '+/='));\n}\n</code></pre>\n<p>And when you call files use something like:</p>\n<pre><code>function base64_url_encode($input) {\n return strtr(base64_encode($input), '+/=', '-_,');\n}\n</code></pre>\n<p><a href=\"http://us.php.net/manual/en/function.base64-encode.php\" rel=\"nofollow noreferrer\">http://us.php.net/manual/en/function.base64-encode.php</a></p>\n<p>If you are using some JavaScript or a flash player (JW player for example) that requires the actual link of an mp3 file or whatever, you can append the text "&type=.mp3" so the final link becomes something like:\n"www.example.com/xfer.php?file=34842ffjfjxfh&type=.mp3". That way it looks like it ends with an mp3 extension without affecting the file link.</p>\n"
},
{
"answer_id": 153,
"author": "saint_groceon",
"author_id": 59,
"author_profile": "https://Stackoverflow.com/users/59",
"pm_score": 4,
"selected": false,
"text": "<p>You could even set up an Apache .htaccess directive that converts *.mp3 requests into the querystring dubayou is working with. It might be an elegant way to keep the direct request and still be able to slipstream log function into the response.</p>\n"
},
{
"answer_id": 158,
"author": "Tim Boland",
"author_id": 70,
"author_profile": "https://Stackoverflow.com/users/70",
"pm_score": 5,
"selected": false,
"text": "<p>Use your httpd log files. Install <a href=\"http://awstats.sourceforge.net/\" rel=\"noreferrer\">http://awstats.sourceforge.net/</a></p>\n"
},
{
"answer_id": 44446,
"author": "Mike H",
"author_id": 4563,
"author_profile": "https://Stackoverflow.com/users/4563",
"pm_score": 2,
"selected": false,
"text": "<p>Is there a database for your music library? If there is any server code that runs when downloading the mp3 then you can add extra code there to increment the play count. You could also have javascript make a second request to increment the play count, but this could lead to people/robots falsely incrementing counts.</p>\n\n<p>I used to work for an internet-radio site and we used separate tables to track the time every song was played. Our streams were powered by a perl script running icecast, so we triggered a database request every time a new track started playing. Then to compute the play count we would run a query to count how many times a song's id was in the play log.</p>\n"
},
{
"answer_id": 195266,
"author": "Vinay Y S",
"author_id": 27183,
"author_profile": "https://Stackoverflow.com/users/27183",
"pm_score": 4,
"selected": false,
"text": "<p>If your song / binary file was served by apache, you can easily grep the access_log to find out the number of downloads. A simple post-logrotate script can grep the logs and maintain your count statistics in a db.\nThis has the performance advantage by not being in your live request code path. Doing non-critical things like stats offline is a good idea to scale your website to large number of users.</p>\n"
},
{
"answer_id": 1507462,
"author": "randomx",
"author_id": 172896,
"author_profile": "https://Stackoverflow.com/users/172896",
"pm_score": 5,
"selected": false,
"text": "<p>Use bash:</p>\n\n<pre><code>grep mp3 /var/log/httpd/access_log | wc\n</code></pre>\n"
},
{
"answer_id": 37722221,
"author": "icc97",
"author_id": 327074,
"author_profile": "https://Stackoverflow.com/users/327074",
"pm_score": 2,
"selected": false,
"text": "<p>The problem I had with things like AWStats / reading through web server logs is that large downloads can often be split in data chunks within the logs. This makes reconciling the exact number of downloads quite hard.</p>\n\n<p>I'd suggest the Google Analytics <a href=\"https://developers.google.com/analytics/devguides/collection/analyticsjs/events\" rel=\"nofollow\">Event Tracking</a>, as this will register once per click on a download link.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30/"
] | I have a website that plays mp3s in a flash player. If a user clicks 'play' the flash player automatically downloads an mp3 and starts playing it.
Is there an easy way to track how many times a particular song clip (or any binary file) has been downloaded?
---
>
> Is the play link a link to the actual
> mp3 file or to some javascript code
> that pops up a player?
>
>
> If the latter, you can easily add your
> own logging code in there to track the
> number of hits to it.
>
>
> If the former, you'll need something
> that can track the web server log
> itself and make that distinction. My
> hosting plan comes with Webalizer,
> which does this nicely.
>
>
>
It's a javascript code so that answers that.
However, it would be nice to know how to track downloads using the other method (without switching hosts). | The funny thing is I wrote a php media gallery for all my musics 2 days ago. I had a similar problem. I'm using <http://musicplayer.sourceforge.net/> for the player. And the playlist is built via php. All music requests go to a script called xfer.php?file=WHATEVER
```
$filename = base64_url_decode($_REQUEST['file']);
header("Cache-Control: public");
header('Content-disposition: attachment; filename='.basename($filename));
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($filename));
// Put either file counting code here, either a db or static files
//
readfile($filename); //and spit the user the file
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_,', '+/='));
}
```
And when you call files use something like:
```
function base64_url_encode($input) {
return strtr(base64_encode($input), '+/=', '-_,');
}
```
<http://us.php.net/manual/en/function.base64-encode.php>
If you are using some JavaScript or a flash player (JW player for example) that requires the actual link of an mp3 file or whatever, you can append the text "&type=.mp3" so the final link becomes something like:
"www.example.com/xfer.php?file=34842ffjfjxfh&type=.mp3". That way it looks like it ends with an mp3 extension without affecting the file link. |
164 | <p><strong>Edit:</strong> This question was written in 2008, which was like 3 internet ages ago. If this question is still relevant to your environment, please accept my condolences. Everyone else should convert into a format <a href="https://videojs.com/html5-video-support/" rel="noreferrer">supported by your browsers</a> (That would be H.264 if Internet Explorer is needed, and probably AV1, VP8/VP9 if not) and use the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video" rel="noreferrer"><code><video></code> element</a>.</p>
<hr />
<p>We are using <a href="http://en.wikipedia.org/wiki/Windows_Media_Video" rel="noreferrer">WMV</a> videos on an internal site, and we are embedding them into web sites. This works quite well on Internet Explorer, but not on Firefox. I've found ways to make it work in Firefox, but then it stops working in Internet Explorer.</p>
<p>We do not want to use Silverlight just yet, especially since we cannot be sure that all clients will be running Windows XP with Windows Media Player installed.</p>
<p>Is there some sort of Universal Code that embeds WMP into both Internet Explorer and Firefox, or do we need to implement some user-agent-detection and deliver different HTML for different browsers?</p>
| [
{
"answer_id": 167,
"author": "Grant",
"author_id": 30,
"author_profile": "https://Stackoverflow.com/users/30",
"pm_score": 3,
"selected": false,
"text": "<p>You could use conditional comments to get IE and Firefox to do different things</p>\n\n<pre><code><![if !IE]>\n<p> Firefox only code</p>\n<![endif]>\n\n<!--[if IE]>\n<p>Internet Explorer only code</p>\n<![endif]-->\n</code></pre>\n\n<p>The browsers themselves will ignore code that isn't meant for them to read.</p>\n"
},
{
"answer_id": 407,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 3,
"selected": false,
"text": "<p><s>The best way to deploy video on the web is using Flash - it's much easier to embed cleanly into a web page and will play on more or less any browser and platform combination. The only reason to use Windows Media Player is if you're streaming content and you need extraordinarily strong digital rights management, and even then providers are now starting to use Flash even for these. See BBC's iPlayer for a superb example.</p>\n\n<p>I would suggest that you switch to Flash even for internal use. You never know who is going to need to access it in the future, and this will give you the best possible future compatibility.</s></p>\n\n<p>EDIT - March 20 2013. \nInteresting how these old questions resurface from time to time! How different the world is today and how dated this all seems. I would not recommend a Flash only route today by any means - best practice these days would probably be to use HTML 5 to embed H264 encoded video, with a Flash fallback as described here: <a href=\"http://diveintohtml5.info/video.html\" rel=\"noreferrer\">http://diveintohtml5.info/video.html</a></p>\n"
},
{
"answer_id": 699,
"author": "Grant",
"author_id": 30,
"author_profile": "https://Stackoverflow.com/users/30",
"pm_score": 7,
"selected": true,
"text": "<p>The following works for me in Firefox and Internet Explorer:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><object id=\"mediaplayer\" classid=\"clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95\" codebase=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701\" standby=\"loading microsoft windows media player components...\" type=\"application/x-oleobject\" width=\"320\" height=\"310\">\n<param name=\"filename\" value=\"./test.wmv\">\n <param name=\"animationatstart\" value=\"true\">\n <param name=\"transparentatstart\" value=\"true\">\n <param name=\"autostart\" value=\"true\">\n <param name=\"showcontrols\" value=\"true\">\n <param name=\"ShowStatusBar\" value=\"true\">\n <param name=\"windowlessvideo\" value=\"true\">\n <embed src=\"./test.wmv\" autostart=\"true\" showcontrols=\"true\" showstatusbar=\"1\" bgcolor=\"white\" width=\"320\" height=\"310\">\n</object>\n</code></pre>\n"
},
{
"answer_id": 971,
"author": "Peter Burns",
"author_id": 101,
"author_profile": "https://Stackoverflow.com/users/101",
"pm_score": 2,
"selected": false,
"text": "<p>Encoding flash video is actually very easy with ffmpeg. You can use one command to convert from just about any video format, ffmpeg is smart enough to figure the rest out, and it'll use every processor on your machine. Invoking it is easy:</p>\n\n<pre><code>ffmpeg -i input.avi output.flv\n</code></pre>\n\n<p>ffmpeg will guess at the bitrate you want, but if you'd like to specify one, you can use the -b option, so <code>-b 500000</code> is 500kbps for example. There's a ton of options of course, but I generally get good results without much tinkering. This is a good place to start if you're looking for more options: <a href=\"http://ffmpeg.mplayerhq.hu/ffmpeg-doc.html#SEC9\" rel=\"nofollow noreferrer\">video options</a>.</p>\n\n<p>You don't need a special web server to show flash video. I've done just fine by simply pushing .flv files up to a standard web server, and linking to them with a good swf player, like <a href=\"http://flowplayer.org/\" rel=\"nofollow noreferrer\">flowplayer</a>.</p>\n\n<p>WMVs are fine if you can be sure that all of your users will always use [a recent, up to date version of] Windows only, but even then, Flash is often a better fit for the web. The player is even extremely skinnable and can be controlled with javascript.</p>\n"
},
{
"answer_id": 6230,
"author": "Jake McGraw",
"author_id": 302,
"author_profile": "https://Stackoverflow.com/users/302",
"pm_score": 4,
"selected": false,
"text": "<p>May I suggest the <a href=\"http://malsup.com/jquery/media/\" rel=\"noreferrer\">jQuery Media Plugin</a>? Provides embed code for all kinds of video, not just WMV and does browser detection, keeping all that messy switch/case statements out of your templates.</p>\n"
},
{
"answer_id": 278953,
"author": "Jim Nelson",
"author_id": 32168,
"author_profile": "https://Stackoverflow.com/users/32168",
"pm_score": 3,
"selected": false,
"text": "<p>Elizabeth Castro has an interesting article on this problem: <a href=\"http://www.alistapart.com/articles/byebyeembed/\" rel=\"noreferrer\">Bye Bye Embed</a>. Worth a read on how she attacked this problem, as well as handling QuickTime content.</p>\n"
},
{
"answer_id": 1227988,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Use the following. It works in Firefox and Internet Explorer.</p>\n\n<pre><code> <object id=\"MediaPlayer1\" width=\"690\" height=\"500\" classid=\"CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95\"\n codebase=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701\"\n standby=\"Loading Microsoft® Windows® Media Player components...\" type=\"application/x-oleobject\"\n >\n <param name=\"FileName\" value='<%= GetSource() %>' />\n <param name=\"AutoStart\" value=\"True\" />\n <param name=\"DefaultFrame\" value=\"mainFrame\" />\n <param name=\"ShowStatusBar\" value=\"0\" />\n <param name=\"ShowPositionControls\" value=\"0\" />\n <param name=\"showcontrols\" value=\"0\" />\n <param name=\"ShowAudioControls\" value=\"0\" />\n <param name=\"ShowTracker\" value=\"0\" />\n <param name=\"EnablePositionControls\" value=\"0\" />\n\n\n <!-- BEGIN PLUG-IN HTML FOR FIREFOX-->\n <embed type=\"application/x-mplayer2\" pluginspage=\"http://www.microsoft.com/Windows/MediaPlayer/\"\n src='<%= GetSource() %>' align=\"middle\" width=\"600\" height=\"500\" defaultframe=\"rightFrame\"\n id=\"MediaPlayer2\" />\n</code></pre>\n\n<p>And in JavaScript,</p>\n\n<pre><code> function playVideo() {\n try{\n if(-1 != navigator.userAgent.indexOf(\"MSIE\"))\n {\n var obj = document.getElementById(\"MediaPlayer1\");\n obj.Play();\n\n }\n else\n {\n var player = document.getElementById(\"MediaPlayer2\");\n player.controls.play();\n\n }\n } \n catch(error) {\n alert(error)\n } \n\n\n }\n</code></pre>\n"
},
{
"answer_id": 1689995,
"author": "Vonzy",
"author_id": 205189,
"author_profile": "https://Stackoverflow.com/users/205189",
"pm_score": 2,
"selected": false,
"text": "<p>I have found something that Actually works in both FireFox and IE, on Elizabeth Castro's site (thanks to the link on this site) - I have tried all other versions here, but could not make them work in both the browsers</p>\n\n<pre><code><object classid=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\" \n id=\"player\" width=\"320\" height=\"260\">\n <param name=\"url\" \n value=\"http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv\" />\n <param name=\"src\" \n value=\"http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv\" />\n <param name=\"showcontrols\" value=\"true\" />\n <param name=\"autostart\" value=\"true\" />\n <!--[if !IE]>-->\n <object type=\"video/x-ms-wmv\" \n data=\"http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv\" \n width=\"320\" height=\"260\">\n <param name=\"src\" \n value=\"http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv\" />\n <param name=\"autostart\" value=\"true\" />\n <param name=\"controller\" value=\"true\" />\n </object>\n <!--<![endif]-->\n</object>\n</code></pre>\n\n<p>Check her site out: <a href=\"http://www.alistapart.com/articles/byebyeembed/\" rel=\"nofollow noreferrer\">http://www.alistapart.com/articles/byebyeembed/</a> and the version with the classid in the initial object tag</p>\n"
},
{
"answer_id": 16966864,
"author": "Perseus",
"author_id": 2354121,
"author_profile": "https://Stackoverflow.com/users/2354121",
"pm_score": 2,
"selected": false,
"text": "<p>I found a good article about <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/dd562847.aspx\" rel=\"nofollow\">using the WMP with Firefox</a> on MSDN.</p>\n\n<p>Based on MSDN's article and after doing some trials and errors, I found using JavaScript is better than using conditional comments or nested \"EMBED/OBJECT\" tags.</p>\n\n<p>I made a JS function that generate WMP object based on given arguments:</p>\n\n<pre><code><script type=\"text/javascript\">\n function generateWindowsMediaPlayer(\n holderId, // String\n height, // Number\n width, // Number\n videoUrl // String\n // you can declare more arguments for more flexibility\n ) {\n var holder = document.getElementById(holderId);\n\n var player = '<object ';\n player += 'height=\"' + height.toString() + '\" ';\n player += 'width=\"' + width.toString() + '\" ';\n\n videoUrl = encodeURI(videoUrl); // Encode for special characters\n\n if (navigator.userAgent.indexOf(\"MSIE\") < 0) {\n // Chrome, Firefox, Opera, Safari\n //player += 'type=\"application/x-ms-wmp\" '; //Old Edition\n player += 'type=\"video/x-ms-wmp\" '; //New Edition, suggested by MNRSullivan (Read Comments)\n player += 'data=\"' + videoUrl + '\" >';\n }\n else {\n // Internet Explorer\n player += 'classid=\"clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6\" >';\n player += '<param name=\"url\" value=\"' + videoUrl + '\" />';\n }\n\n player += '<param name=\"autoStart\" value=\"false\" />';\n player += '<param name=\"playCount\" value=\"1\" />';\n player += '</object>';\n\n holder.innerHTML = player;\n }\n</script>\n</code></pre>\n\n<p>Then I used that function by writing some markups and inline JS like these:</p>\n\n<pre><code><div id='wmpHolder'></div>\n\n<script type=\"text/javascript\"> \n window.addEventListener('load', generateWindowsMediaPlayer('wmpHolder', 240, 320, 'http://mysite.com/path/video.ext'));\n</script>\n</code></pre>\n\n<p>You can use <strong><em>jQuery.ready</em></strong> instead of <strong><em>window load event</em></strong> to making the codes more backward-compatible and cross-browser.</p>\n\n<p>I tested the codes over IE 9-10, Chrome 27, Firefox 21, Opera 12 and Safari 5, on Windows 7/8.</p>\n"
},
{
"answer_id": 65250970,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>December 2020 :</p>\n<ul>\n<li>We have now Firefox 83.0 and Chrome 87.0</li>\n<li>Internet Explorer is dead, it has been replaced by the new Chromium-based Edge 87.0</li>\n<li>Silverlight is dead</li>\n<li>Windows XP is dead</li>\n<li>WMV is not a standard : <a href=\"https://www.w3schools.com/html/html_media.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/html/html_media.asp</a></li>\n</ul>\n<p>To answer the question :</p>\n<ul>\n<li>You have to convert your WMV file to another format : MP4, WebM or Ogg video.</li>\n<li>Then embed it in your page with <a href=\"https://www.w3schools.com/html/html5_video.asp\" rel=\"nofollow noreferrer\">the HTML 5 <code><video></code> element</a>.</li>\n</ul>\n<p>I think this question should be closed.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | **Edit:** This question was written in 2008, which was like 3 internet ages ago. If this question is still relevant to your environment, please accept my condolences. Everyone else should convert into a format [supported by your browsers](https://videojs.com/html5-video-support/) (That would be H.264 if Internet Explorer is needed, and probably AV1, VP8/VP9 if not) and use the [`<video>` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video).
---
We are using [WMV](http://en.wikipedia.org/wiki/Windows_Media_Video) videos on an internal site, and we are embedding them into web sites. This works quite well on Internet Explorer, but not on Firefox. I've found ways to make it work in Firefox, but then it stops working in Internet Explorer.
We do not want to use Silverlight just yet, especially since we cannot be sure that all clients will be running Windows XP with Windows Media Player installed.
Is there some sort of Universal Code that embeds WMP into both Internet Explorer and Firefox, or do we need to implement some user-agent-detection and deliver different HTML for different browsers? | The following works for me in Firefox and Internet Explorer:
```html
<object id="mediaplayer" classid="clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701" standby="loading microsoft windows media player components..." type="application/x-oleobject" width="320" height="310">
<param name="filename" value="./test.wmv">
<param name="animationatstart" value="true">
<param name="transparentatstart" value="true">
<param name="autostart" value="true">
<param name="showcontrols" value="true">
<param name="ShowStatusBar" value="true">
<param name="windowlessvideo" value="true">
<embed src="./test.wmv" autostart="true" showcontrols="true" showstatusbar="1" bgcolor="white" width="320" height="310">
</object>
``` |
173 | <p>I want to get my databases under version control.</p>
<p>I'll always want to have at least <em>some</em> data in there (as <a href="https://stackoverflow.com/users/80/alumb">alumb</a> mentions: user types and administrators). I'll also often want a large collection of generated test data for performance measurements.</p>
<p>How would I apply version control to my database?</p>
| [
{
"answer_id": 195,
"author": "alumb",
"author_id": 80,
"author_profile": "https://Stackoverflow.com/users/80",
"pm_score": 5,
"selected": false,
"text": "<p>This is one of the \"hard problems\" surrounding development. As far as I know there are no perfect solutions. </p>\n\n<p>If you only need to store the database structure and not the data you can export the database as SQL queries. (in Enterprise Manager: Right click on database -> Generate SQL script. I recommend setting the \"create one file per object\" on the options tab) You can then commit these text files to svn and make use of svn's diff and logging functions. </p>\n\n<p>I have this tied together with a Batch script that takes a couple parameters and sets up the database. I also added some additional queries that enter default data like user types and the admin user. (If you want more info on this, post something and I can put the script somewhere accessible)</p>\n\n<p>If you need to keep all of the data as well, I recommend keeping a back up of the database and using Redgate (<a href=\"http://www.red-gate.com/\" rel=\"noreferrer\">http://www.red-gate.com/</a>) products to do the comparisons. They don't come cheap, but they are worth every penny.</p>\n"
},
{
"answer_id": 516,
"author": "ESV",
"author_id": 150,
"author_profile": "https://Stackoverflow.com/users/150",
"pm_score": 9,
"selected": true,
"text": "<p>Martin Fowler wrote my favorite article on the subject, <a href=\"http://martinfowler.com/articles/evodb.html\" rel=\"noreferrer\">http://martinfowler.com/articles/evodb.html</a>. I choose not to put schema dumps in under version control as <em>alumb</em> and others suggest because I want an easy way to upgrade my production database.</p>\n\n<p>For a web application where I'll have a single production database instance, I use two techniques:</p>\n\n<h1>Database Upgrade Scripts</h1>\n\n<p>A sequence database upgrade scripts that contain the DDL necessary to move the schema from version N to N+1. (These go in your version control system.) A _version_history_ table, something like</p>\n\n<pre><code>create table VersionHistory (\n Version int primary key,\n UpgradeStart datetime not null,\n UpgradeEnd datetime\n );\n</code></pre>\n\n<p>gets a new entry every time an upgrade script runs which corresponds to the new version.</p>\n\n<p>This ensures that it's easy to see what version of the database schema exists and that database upgrade scripts are run only once. Again, these are <strong>not</strong> database dumps. Rather, each script represents the <strong>changes</strong> necessary to move from one version to the next. They're the script that you apply to your production database to \"upgrade\" it.</p>\n\n<h1>Developer Sandbox Synchronization</h1>\n\n<ol>\n<li>A script to backup, sanitize, and shrink a production database. Run this after each upgrade to the production DB.</li>\n<li>A script to restore (and tweak, if necessary) the backup on a developer's workstation. Each developer runs this script after each upgrade to the production DB.</li>\n</ol>\n\n<p><em>A caveat: My automated tests run against a schema-correct but empty database, so this advice will not perfectly suit your needs.</em></p>\n"
},
{
"answer_id": 521,
"author": "Matt",
"author_id": 154,
"author_profile": "https://Stackoverflow.com/users/154",
"pm_score": 3,
"selected": false,
"text": "<p>You didn't mention any specifics about your target environment or constraints, so this may not be entirely applicable... but if you're looking for a way to effectively track an evolving DB schema and aren't adverse to the idea of using Ruby, ActiveRecord's migrations are right up your alley.</p>\n\n<p>Migrations programatically define database transformations using a Ruby DSL; each transformation can be applied or (usually) rolled back, allowing you to jump to a different version of your DB schema at any given point in time. The file defining these transformations can be checked into version control like any other piece of source code.</p>\n\n<p>Because migrations are a part of <a href=\"http://ar.rubyonrails.com/\" rel=\"noreferrer\">ActiveRecord</a>, they typically find use in full-stack Rails apps; however, you can use ActiveRecord independent of Rails with minimal effort. See <a href=\"http://rails.aizatto.com/2007/05/27/activerecord-migrations-without-rails/\" rel=\"noreferrer\">here</a> for a more detailed treatment of using AR's migrations outside of Rails.</p>\n"
},
{
"answer_id": 599,
"author": "engtech",
"author_id": 175,
"author_profile": "https://Stackoverflow.com/users/175",
"pm_score": 3,
"selected": false,
"text": "<p>The typical solution is to dump the database as necessary and backup those files.</p>\n\n<p>Depending on your development platform, there may be opensource plugins available. Rolling your own code to do it is usually fairly trivial.</p>\n\n<p>Note: You may want to backup the database dump instead of putting it into version control. The files can get huge fast in version control, and cause your entire source control system to become slow (I'm recalling a CVS horror story at the moment).</p>\n"
},
{
"answer_id": 4088,
"author": "Lance Fisher",
"author_id": 571,
"author_profile": "https://Stackoverflow.com/users/571",
"pm_score": 4,
"selected": false,
"text": "<p>You could also look at a migrations solution. These allow you to specify your database schema in C# code, and roll your database version up and down using MSBuild.</p>\n\n<p>I'm currently using <a href=\"https://dbup.github.io/\" rel=\"noreferrer\">DbUp</a>, and it's been working well.</p>\n"
},
{
"answer_id": 4096,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 3,
"selected": false,
"text": "<p>We don't store the database schema, we store the changes to the database. What we do is store the schema changes so that we build a change script for any version of the database and apply it to our customer's databases. I wrote an database utility app that gets distributed with our main application that can read that script and know which updates need to be applied. It also has enough smarts to refresh views and stored procedures as needed.</p>\n"
},
{
"answer_id": 5322,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 4,
"selected": false,
"text": "<p>We use <a href=\"http://www.innovartis.co.uk/\" rel=\"noreferrer\">DBGhost</a> to manage our SQL database. Then you put your scripts to build a new database in your version control, and it'll either build a new database, or upgrade any existing database to the schema in version control. That way you don't have to worry about creating change scripts (although you can still do that, if for example you want to change the data type of a column and need to convert data).</p>\n"
},
{
"answer_id": 5336,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 3,
"selected": false,
"text": "<p>If you have a small database and you want to version the entire thing, <a href=\"http://weblogs.asp.net/jgalloway/archive/2006/10/28/Batch-files-to-check-SQL-2005-_2800_MDF_2900_-files-in-and-out-of-Subversion-source-control.aspx\" rel=\"nofollow noreferrer\">this batch script</a> might help. It detaches, compresses, and checks a MSSQL database MDF file in to Subversion.</p>\n<p>If you mostly want to version your schema and just have a small amount of reference data, you can possibly use <a href=\"http://web.archive.org/web/20120419154556/http://blog.wekeroad.com:80/blog/subsonic-using-migrations\" rel=\"nofollow noreferrer\">SubSonic Migrations</a> to handle that. The benefit there is that you can easily migrate up or down to any specific version.</p>\n"
},
{
"answer_id": 22917,
"author": "TheEmirOfGroofunkistan",
"author_id": 1874,
"author_profile": "https://Stackoverflow.com/users/1874",
"pm_score": 3,
"selected": false,
"text": "<p>We just started using Team Foundation Server. If your database is medium sized, then visual studio has some nice project integrations with built in compare, data compare, database refactoring tools, database testing framework, and even data generation tools.</p>\n\n<p>But, that model doesn't fit very large or third party databases (that encrypt objects) very well. So, what we've done is to store only our customized objects. Visual Studio / Team foundation server works very well for that.</p>\n\n<p><a href=\"http://blogs.msdn.com/gertd/\" rel=\"noreferrer\">TFS Database chief arch. blog</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/tfs2008/default.aspx\" rel=\"noreferrer\">MS TFS site</a></p>\n"
},
{
"answer_id": 27508,
"author": "Dane",
"author_id": 2929,
"author_profile": "https://Stackoverflow.com/users/2929",
"pm_score": 6,
"selected": false,
"text": "<p>Red Gate's SQL Compare product not only allows you to do object-level comparisons, and generate change scripts from that, but it also allows you to export your database objects into a folder hierarchy organized by object type, with one [objectname].sql creation script per object in these directories. The object-type hierarchy is like this:</p>\n\n<p>\\Functions<br>\n\\Security<br>\n\\Security\\Roles<br>\n\\Security\\Schemas<br>\n\\Security\\Users<br>\n\\Stored Procedures<br>\n\\Tables </p>\n\n<p>If you dump your scripts to the same root directory after you make changes, you can use this to update your SVN repo, and keep a running history of each object individually.</p>\n"
},
{
"answer_id": 75083,
"author": "Dave Jackson",
"author_id": 12328,
"author_profile": "https://Stackoverflow.com/users/12328",
"pm_score": 3,
"selected": false,
"text": "<p>A while ago I found a VB bas module that used DMO and VSS objects to get an entire db scripted off and into VSS. I turned it into a VB Script and posted it <a href=\"http://glossopian.co.uk/pmwiki.php?n=Main.DBtoVSS\" rel=\"nofollow noreferrer\">here</a>. You can easily take out the VSS calls and use the DMO stuff to generate all the scripts, and then call SVN from the same batch file that calls the VBScript to check them in.</p>\n"
},
{
"answer_id": 75330,
"author": "jeffjakub",
"author_id": 12600,
"author_profile": "https://Stackoverflow.com/users/12600",
"pm_score": 5,
"selected": false,
"text": "<p>You might want to look at Liquibase (<a href=\"http://www.liquibase.org/\" rel=\"noreferrer\">http://www.liquibase.org/</a>). Even if you don't use the tool itself it handles the concepts of database change management or refactoring pretty well.</p>\n"
},
{
"answer_id": 125609,
"author": "Andrew Swan",
"author_id": 10433,
"author_profile": "https://Stackoverflow.com/users/10433",
"pm_score": 3,
"selected": false,
"text": "<p>Because our app has to work across multiple RDBMSs, we store our schema definition in version control using the database-neutral <a href=\"http://db.apache.org/torque/\" rel=\"noreferrer\">Torque</a> format (XML). We also version-control the reference data for our database in XML format as follows (where \"Relationship\" is one of the reference tables):</p>\n\n<pre><code> <Relationship RelationshipID=\"1\" InternalName=\"Manager\"/>\n <Relationship RelationshipID=\"2\" InternalName=\"Delegate\"/>\n etc.\n</code></pre>\n\n<p>We then use home-grown tools to generate the schema upgrade and reference data upgrade scripts that are required to go from version X of the database to version X + 1.</p>\n"
},
{
"answer_id": 125655,
"author": "Silvercode",
"author_id": 16663,
"author_profile": "https://Stackoverflow.com/users/16663",
"pm_score": 4,
"selected": false,
"text": "<p>It is a good approach to save database scripts into version control with change scripts so that you can upgrade any one database you have. Also you might want to save schemas for different versions so that you can create a full database without having to apply all the change scripts. Handling the scripts should be automated so that you don't have to do manual work.</p>\n\n<p>I think its important to have a separate database for every developer and not use a shared database. That way the developers can create test cases and development phases independently from other developers.</p>\n\n<p>The automating tool should have means for handling database metadata, which tells what databases are in what state of development and which tables contain version controllable data and so on.</p>\n"
},
{
"answer_id": 126936,
"author": "Jonathan",
"author_id": 6910,
"author_profile": "https://Stackoverflow.com/users/6910",
"pm_score": 3,
"selected": false,
"text": "<p>To make the dump to a source code control system that little bit faster, you can see which objects have changed since last time by using the version information in sysobjects.</p>\n\n<p><strong>Setup:</strong> Create a table in each database you want to check incrementally to hold the version information from the last time you checked it (empty on the first run). Clear this table if you want to re-scan your whole data structure.</p>\n\n<pre><code>IF ISNULL(OBJECT_ID('last_run_sysversions'), 0) <> 0 DROP TABLE last_run_sysversions\nCREATE TABLE last_run_sysversions (\n name varchar(128), \n id int, base_schema_ver int,\n schema_ver int,\n type char(2)\n)\n</code></pre>\n\n<p><strong>Normal running mode:</strong> You can take the results from this sql, and generate sql scripts for just the ones you're interested in, and put them into a source control of your choice.</p>\n\n<pre><code>IF ISNULL(OBJECT_ID('tempdb.dbo.#tmp'), 0) <> 0 DROP TABLE #tmp\nCREATE TABLE #tmp (\n name varchar(128), \n id int, base_schema_ver int,\n schema_ver int,\n type char(2)\n)\n\nSET NOCOUNT ON\n\n-- Insert the values from the end of the last run into #tmp\nINSERT #tmp (name, id, base_schema_ver, schema_ver, type) \nSELECT name, id, base_schema_ver, schema_ver, type FROM last_run_sysversions\n\nDELETE last_run_sysversions\nINSERT last_run_sysversions (name, id, base_schema_ver, schema_ver, type)\nSELECT name, id, base_schema_ver, schema_ver, type FROM sysobjects\n\n-- This next bit lists all differences to scripts.\nSET NOCOUNT OFF\n\n--Renamed.\nSELECT 'renamed' AS ChangeType, t.name, o.name AS extra_info, 1 AS Priority\nFROM sysobjects o INNER JOIN #tmp t ON o.id = t.id\nWHERE o.name <> t.name /*COLLATE*/\nAND o.type IN ('TR', 'P' ,'U' ,'V')\nUNION \n\n--Changed (using alter)\nSELECT 'changed' AS ChangeType, o.name /*COLLATE*/, \n 'altered' AS extra_info, 2 AS Priority\nFROM sysobjects o INNER JOIN #tmp t ON o.id = t.id \nWHERE (\n o.base_schema_ver <> t.base_schema_ver\nOR o.schema_ver <> t.schema_ver\n)\nAND o.type IN ('TR', 'P' ,'U' ,'V')\nAND o.name NOT IN ( SELECT oi.name \n FROM sysobjects oi INNER JOIN #tmp ti ON oi.id = ti.id\n WHERE oi.name <> ti.name /*COLLATE*/\n AND oi.type IN ('TR', 'P' ,'U' ,'V')) \nUNION\n\n--Changed (actually dropped and recreated [but not renamed])\nSELECT 'changed' AS ChangeType, t.name, 'dropped' AS extra_info, 2 AS Priority\nFROM #tmp t\nWHERE t.name IN ( SELECT ti.name /*COLLATE*/ FROM #tmp ti\n WHERE NOT EXISTS (SELECT * FROM sysobjects oi\n WHERE oi.id = ti.id))\nAND t.name IN ( SELECT oi.name /*COLLATE*/ FROM sysobjects oi\n WHERE NOT EXISTS (SELECT * FROM #tmp ti\n WHERE oi.id = ti.id)\n AND oi.type IN ('TR', 'P' ,'U' ,'V'))\nUNION\n\n--Deleted\nSELECT 'deleted' AS ChangeType, t.name, '' AS extra_info, 0 AS Priority\nFROM #tmp t\nWHERE NOT EXISTS (SELECT * FROM sysobjects o\n WHERE o.id = t.id)\nAND t.name NOT IN ( SELECT oi.name /*COLLATE*/ FROM sysobjects oi\n WHERE NOT EXISTS (SELECT * FROM #tmp ti\n WHERE oi.id = ti.id)\n AND oi.type IN ('TR', 'P' ,'U' ,'V'))\nUNION\n\n--Added\nSELECT 'added' AS ChangeType, o.name /*COLLATE*/, '' AS extra_info, 4 AS Priority\nFROM sysobjects o\nWHERE NOT EXISTS (SELECT * FROM #tmp t\n WHERE o.id = t.id)\nAND o.type IN ('TR', 'P' ,'U' ,'V')\nAND o.name NOT IN ( SELECT ti.name /*COLLATE*/ FROM #tmp ti\n WHERE NOT EXISTS (SELECT * FROM sysobjects oi\n WHERE oi.id = ti.id))\nORDER BY Priority ASC\n</code></pre>\n\n<p><strong>Note:</strong> If you use a non-standard collation in any of your databases, you will need to replace <code>/* COLLATE */</code> with your database collation. i.e. <code>COLLATE Latin1_General_CI_AI</code></p>\n"
},
{
"answer_id": 187617,
"author": "Christopher Klein",
"author_id": 17632,
"author_profile": "https://Stackoverflow.com/users/17632",
"pm_score": 3,
"selected": false,
"text": "<p>We needed to version our SQL database after we migrated to an x64 platform and our old version broke with the migration. We wrote a C# application which used SQLDMO to map out all of the SQL objects to a folder:</p>\n<pre>\n Root\n ServerName\n DatabaseName\n Schema Objects\n Database Triggers*\n .ddltrigger.sql\n Functions\n ..function.sql\n Security\n Roles\n Application Roles\n .approle.sql\n Database Roles\n .role.sql\n Schemas*\n .schema.sql\n Users\n .user.sql\n Storage\n Full Text Catalogs*\n .fulltext.sql\n Stored Procedures\n ..proc.sql\n Synonyms*\n .synonym.sql\n Tables\n ..table.sql\n Constraints\n ...chkconst.sql\n ...defconst.sql\n Indexes\n ...index.sql\n Keys\n ...fkey.sql\n ...pkey.sql\n ...ukey.sql\n Triggers\n ...trigger.sql\n Types\n User-defined Data Types\n ..uddt.sql\n XML Schema Collections*\n ..xmlschema.sql\n Views\n ..view.sql\n Indexes\n ...index.sql\n Triggers\n ...trigger.sql\n</pre>\n<p>The application would then compare the newly written version with the version stored in SVN, and if there were differences it would update SVN.\nWe determined that running the process once a night was sufficient since we did not make that many changes to SQL. It allows us to track changes to all the objects we care about plus it allows us to rebuild our full schema in the event of a serious problem.</p>\n"
},
{
"answer_id": 204180,
"author": "alexis.kennedy",
"author_id": 6725,
"author_profile": "https://Stackoverflow.com/users/6725",
"pm_score": 4,
"selected": false,
"text": "<p>+1 for everyone who's recommended the RedGate tools, with an additional recommendation and a caveat.</p>\n\n<p>SqlCompare also has a decently documented API: so you can, for instance, write a console app which syncs your source controlled scripts folder with a CI integration testing database on checkin, so that when someone checks in a change to the schema from their scripts folder it's automatically deployed along with the matching application code change. This helps close the gap with developers who are forgetful about propagating changes in their local db up to a shared development DB (about half of us, I think :) ).</p>\n\n<p>A caveat is that with a scripted solution or otherwise, the RedGate tools are sufficiently smooth that it's easy to forget about SQL realities underlying the abstraction. If you rename all the columns in a table, SqlCompare has no way to map the old columns to the new columns and will drop all the data in the table. It will generate warnings but I've seen people click past that. There's a general point here worth making, I think, that you can only automate DB versioning and upgrade so far - the abstractions are very leaky.</p>\n"
},
{
"answer_id": 870412,
"author": "Remus Rusanu",
"author_id": 105929,
"author_profile": "https://Stackoverflow.com/users/105929",
"pm_score": 3,
"selected": false,
"text": "<p>I'm also using a version in the database stored via the database extended properties family of procedures. My application has scripts for each version step (ie. move from 1.1 to 1.2). When deployed, it looks at the current version and then runs the scripts one by one until it reaches the last app version. There is no script that has the straight 'final' version, even deploy on a clean DB does the deploy via a series of upgrade steps.</p>\n\n<p>Now what I like to add is that I've seen two days ago a presentation on the MS campus about the new and upcoming VS DB edition. The presentation was focused specifically on this topic and I was blown out of the water. You should definitely check it out, the new facilities are focused on keeping schema definition in T-SQL scripts (CREATEs), a runtime delta engine to compare deployment schema with defined schema and doing the delta ALTERs and integration with source code integration, up to and including MSBUILD continuous integration for automated build drops. The drop will contain a new file type, the .dbschema files, that can be taken to the deployment site and a command line tool can do the actual 'deltas' and run the deployment.\nI have a blog entry on this topic with links to the VSDE downloads, you should check them out: <a href=\"http://rusanu.com/2009/05/15/version-control-and-your-database/\" rel=\"noreferrer\">http://rusanu.com/2009/05/15/version-control-and-your-database/</a></p>\n"
},
{
"answer_id": 872240,
"author": "dariol",
"author_id": 3644960,
"author_profile": "https://Stackoverflow.com/users/3644960",
"pm_score": 3,
"selected": false,
"text": "<p>It's simple.</p>\n\n<ol>\n<li><p>When the base project is ready then you must create full database script. This script is commited to SVN. It is first version.</p></li>\n<li><p>After that all developers creates change scripts (ALTER..., new tables, sprocs, etc).</p></li>\n<li><p>When you need current version then you should execute all new change scripts.</p></li>\n<li><p>When app is released to production then you go back to 1 (but then it will be successive version of course).</p></li>\n</ol>\n\n<p>Nant will help you to execute those change scripts. :)</p>\n\n<p>And remember. Everything works fine when there is discipline. Every time when database change is commited then corresponding functions in code are commited too.</p>\n"
},
{
"answer_id": 1092187,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Every database should be under source-code control. What is lacking is a tool to automatically script all database objects - and \"configuration data\" - to file, which then can be added to any source control system. If you are using SQL Server, then my solution is here : <a href=\"http://dbsourcetools.codeplex.com/\" rel=\"noreferrer\">http://dbsourcetools.codeplex.com/</a> . Have fun.\n- Nathan.</p>\n"
},
{
"answer_id": 1238100,
"author": "Liron Levi",
"author_id": 145606,
"author_profile": "https://Stackoverflow.com/users/145606",
"pm_score": 2,
"selected": false,
"text": "<p>In my experience the solution is twofold:</p>\n\n<ol>\n<li><p>You need to handle changes to the development database that are done by multiple developers during development.</p></li>\n<li><p>You need to handle database upgrades in customers sites.</p></li>\n</ol>\n\n<p>In order to handle #1 you'll need a strong database diff/merge tool. The best tool should be able to perform automatic merge as much as possible while allowing you to resolve unhandled conflicts manually. </p>\n\n<p>The perfect tool should handle merge operations by using a 3-way merge algorithm that brings into account the changes that were made in the THEIRS database and the MINE database, relative to the BASE database.</p>\n\n<p>I wrote a commercial tool that provides manual merge support for SQLite databases and I'm currently adding support for 3-way merge algorithm for SQLite. Check it out at <a href=\"http://www.sqlitecompare.com\" rel=\"nofollow noreferrer\">http://www.sqlitecompare.com</a></p>\n\n<p>In order to handle #2 you will need an upgrade framework in place. </p>\n\n<p>The basic idea is to develop an automatic upgrade framework that knows how to upgrade from an existing SQL schema to the newer SQL schema and can build an upgrade path for every existing DB installation. </p>\n\n<p>Check out my article on the subject in <a href=\"http://www.codeproject.com/KB/database/sqlite_upgrade.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/database/sqlite_upgrade.aspx</a> to get a general idea of what I'm talking about. </p>\n\n<p>Good Luck</p>\n\n<p>Liron Levi</p>\n"
},
{
"answer_id": 1664083,
"author": "Kuberchaun",
"author_id": 102388,
"author_profile": "https://Stackoverflow.com/users/102388",
"pm_score": 2,
"selected": false,
"text": "<p>Check out DBGhost <a href=\"http://www.innovartis.co.uk/\" rel=\"nofollow noreferrer\">http://www.innovartis.co.uk/</a>. I have used in an automated fashion for 2 years now and it works great. It allows our DB builds to happen much like a Java or C build happens, except for the database. You know what I mean.</p>\n"
},
{
"answer_id": 3156406,
"author": "David Atkinson",
"author_id": 167364,
"author_profile": "https://Stackoverflow.com/users/167364",
"pm_score": 5,
"selected": false,
"text": "<p>Here at Red Gate we offer a tool, <a href=\"http://www.red-gate.com/products/SQL_Source_Control/index.htm\" rel=\"nofollow noreferrer\">SQL Source Control</a>, which uses SQL Compare technology to link your database with a TFS or SVN repository. This tool integrates into SSMS and lets you work as you would normally, except it now lets you commit the objects.</p>\n\n<p>For a migrations-based approach (more suited for automated deployments), we offer <a href=\"http://www.red-gate.com/products/sql-development/readyroll/\" rel=\"nofollow noreferrer\">SQL Change Automation</a> (formerly called ReadyRoll), which creates and manages a set of incremental scripts as a Visual Studio project.</p>\n\n<p>In SQL Source Control it is possible to specify static data tables. These are stored in source control as INSERT statements.</p>\n\n<p>If you're talking about test data, we'd recommend that you either generate test data with a tool or via a post-deployment script you define, or you simply restore a production backup to the dev environment.</p>\n"
},
{
"answer_id": 3775063,
"author": "ScaleOvenStove",
"author_id": 12268,
"author_profile": "https://Stackoverflow.com/users/12268",
"pm_score": 3,
"selected": false,
"text": "<p>I wrote this app a while ago, <a href=\"http://sqlschemasourcectrl.codeplex.com/\" rel=\"noreferrer\">http://sqlschemasourcectrl.codeplex.com/</a> which will scan your MSFT SQL db's as often as you want and automatically dump your objects (tables, views, procs, functions, sql settings) into SVN. Works like a charm. I use it with Unfuddle (which allows me to get alerts on checkins)</p>\n"
},
{
"answer_id": 5108862,
"author": "Rolf Wessels",
"author_id": 327825,
"author_profile": "https://Stackoverflow.com/users/327825",
"pm_score": 3,
"selected": false,
"text": "<p>I agree with ESV answer and for that exact reason I started a little project a while back to help maintain database updates in a very simple file which could then be maintained a long side out source code. It allows easy updates to developers as well as UAT and Production. The tool works on SQL Server and MySQL.</p>\n<p>Some project features:</p>\n<ul>\n<li>Allows schema changes</li>\n<li>Allows value tree population</li>\n<li>Allows separate test data inserts for eg. UAT</li>\n<li>Allows option for rollback (not automated)</li>\n<li>Maintains support for SQL server and MySQL</li>\n<li>Has the ability to import your existing database into version control with one simple command (SQL server only ... still working on MySQL)</li>\n</ul>\n<p>Please check out the <a href=\"http://code.google.com/p/databaseversioncontrol/\" rel=\"nofollow noreferrer\">code</a> for some more information.</p>\n"
},
{
"answer_id": 5122171,
"author": "roman m",
"author_id": 3661,
"author_profile": "https://Stackoverflow.com/users/3661",
"pm_score": 4,
"selected": false,
"text": "<p>With VS 2010, use the Database project.</p>\n\n<ol>\n<li>Script out your database </li>\n<li>Make changes to scripts or directly on\nyour db server </li>\n<li>Sync up using Data >\n Schema Compare</li>\n</ol>\n\n<p>Makes a perfect DB versioning solution, and makes syncing DB's a breeze. </p>\n"
},
{
"answer_id": 31001490,
"author": "Srivathsa Harish Venkataramana",
"author_id": 1301703,
"author_profile": "https://Stackoverflow.com/users/1301703",
"pm_score": 3,
"selected": false,
"text": "<p>It's a very old question, however, many people are trying to solve this even now. All they have to do is to research about Visual Studio Database Projects. Without this, any database development looks very feeble. From code organization to deployment to versioning, it simplifies everything.</p>\n"
},
{
"answer_id": 31024342,
"author": "McRobert",
"author_id": 4870511,
"author_profile": "https://Stackoverflow.com/users/4870511",
"pm_score": 5,
"selected": false,
"text": "<p>First, you must choose the version control system that is right for you: </p>\n\n<ul>\n<li><p>Centralized Version Control system - a standard system where users check out/check in before/after they work on files, and the files are being kept in a single central server</p></li>\n<li><p>Distributed Version Control system - a system where the repository is being cloned, and each clone is actually the full backup of the repository, so if any server crashes, then any cloned repository can be used to restore it\nAfter choosing the right system for your needs, you'll need to setup the repository which is the core of every version control system\nAll this is explained in the following article: <a href=\"http://solutioncenter.apexsql.com/sql-server-source-control-part-i-understanding-source-control-basics/\" rel=\"noreferrer\">http://solutioncenter.apexsql.com/sql-server-source-control-part-i-understanding-source-control-basics/</a></p></li>\n</ul>\n\n<p>After setting up a repository, and in case of a central version control system a working folder, you can read <a href=\"http://solutioncenter.apexsql.com/sql-server-source-control-part-ii-integration/\" rel=\"noreferrer\" title=\"this article\">this article</a>. It shows how to setup source control in a development environment using: </p>\n\n<ul>\n<li><p>SQL Server Management Studio via the MSSCCI provider, </p></li>\n<li><p>Visual Studio and SQL Server Data Tools</p></li>\n<li>A 3rd party tool ApexSQL Source Control</li>\n</ul>\n"
},
{
"answer_id": 41573374,
"author": "Endi Zhupani",
"author_id": 4464567,
"author_profile": "https://Stackoverflow.com/users/4464567",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest using comparison tools to improvise a version control system for your database. Two good alternatives are <a href=\"http://www.xsql.com/products/sql_server_schema_compare/?utm_source=pragmatic&utm_medium=articles&utm_campaign=xsql\" rel=\"nofollow noreferrer\">xSQL Schema Compare</a> and <a href=\"http://www.xsql.com/products/sql_server_data_compare/?utm_source=pragmatic&utm_medium=articles&utm_campaign=xsql\" rel=\"nofollow noreferrer\">xSQL Data Compare</a>.</p>\n<p>Now, if your goal is to have only the database's schema under version control you can simply use xSQL Schema Compare to generate xSQL Snapshots of the schema and add these files in your version control. Then, to revert or update to a specific version, just compare the current version of the database with the snapshot for the destination version.</p>\n<p>Also, if you want to have the data under version control as well, you can use xSQL Data Compare to generate change scripts for you database and add the .sql files in your version control. You could then execute these scripts to revert / update to any version you want. Keep in mind that for the 'revert' functionality you need to generate change scripts that, when executed, will make Version 3 the same as Version 2 and for the 'update' functionality, you need to generate change scripts that do the opposite.</p>\n<p>Lastly, with some basic batch programming skills you can automate the whole process by using the command line versions of xSQL Schema Compare and xSQL Data Compare</p>\n<p>Disclaimer: I'm affiliated to xSQL.</p>\n"
},
{
"answer_id": 74309858,
"author": "Zach Musgrave",
"author_id": 1733179,
"author_profile": "https://Stackoverflow.com/users/1733179",
"pm_score": 0,
"selected": false,
"text": "<p>An alternative to version controlling your database is to use a version-controlled database, of which there are now several.</p>\n<p><a href=\"https://www.dolthub.com/blog/2021-09-17-database-version-control/\" rel=\"nofollow noreferrer\">https://www.dolthub.com/blog/2021-09-17-database-version-control/</a></p>\n<p>These products don't apply version control on top of another type of database -- they are their own database engines that support version control operations. So you need to migrate to them or start building on them in the first place.</p>\n<p>I write one of them, DoltDB, which combines the interfaces of MySQL and Git. Check it out here:</p>\n<p><a href=\"https://github.com/dolthub/dolt\" rel=\"nofollow noreferrer\">https://github.com/dolthub/dolt</a></p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | I want to get my databases under version control.
I'll always want to have at least *some* data in there (as [alumb](https://stackoverflow.com/users/80/alumb) mentions: user types and administrators). I'll also often want a large collection of generated test data for performance measurements.
How would I apply version control to my database? | Martin Fowler wrote my favorite article on the subject, <http://martinfowler.com/articles/evodb.html>. I choose not to put schema dumps in under version control as *alumb* and others suggest because I want an easy way to upgrade my production database.
For a web application where I'll have a single production database instance, I use two techniques:
Database Upgrade Scripts
========================
A sequence database upgrade scripts that contain the DDL necessary to move the schema from version N to N+1. (These go in your version control system.) A \_version\_history\_ table, something like
```
create table VersionHistory (
Version int primary key,
UpgradeStart datetime not null,
UpgradeEnd datetime
);
```
gets a new entry every time an upgrade script runs which corresponds to the new version.
This ensures that it's easy to see what version of the database schema exists and that database upgrade scripts are run only once. Again, these are **not** database dumps. Rather, each script represents the **changes** necessary to move from one version to the next. They're the script that you apply to your production database to "upgrade" it.
Developer Sandbox Synchronization
=================================
1. A script to backup, sanitize, and shrink a production database. Run this after each upgrade to the production DB.
2. A script to restore (and tweak, if necessary) the backup on a developer's workstation. Each developer runs this script after each upgrade to the production DB.
*A caveat: My automated tests run against a schema-correct but empty database, so this advice will not perfectly suit your needs.* |
174 | <p>I want to print HTML from a C# web service. The web browser control is overkill, and does not function well in a service environment, nor does it function well on a system with very tight security constraints. Is there any sort of free <code>.NET</code> library that will support the printing of a basic HTML page? Here is the code I have so far, which does not run properly.</p>
<pre><code>public void PrintThing(string document)
{
if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
{
Thread thread =
new Thread((ThreadStart) delegate { PrintDocument(document); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
else
{
PrintDocument(document);
}
}
protected void PrintDocument(string document)
{
WebBrowser browser = new WebBrowser();
browser.DocumentText = document;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Print();
}
</code></pre>
<p>This works fine when called from UI-type threads, but nothing happens when called from a service-type thread. Changing <code>Print()</code> to <code>ShowPrintPreviewDialog()</code> yields the following IE script error:</p>
<blockquote>
<p><strong>Error:</strong> <code>dialogArguments.___IE_PrintType</code> is null or not an object. </p>
<p>URL: <code>res://ieframe.dll/preview.dlg</code></p>
</blockquote>
<p>And a small empty print preview dialog appears.</p>
| [
{
"answer_id": 290,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 3,
"selected": false,
"text": "<p>I know that Visual Studio itself (at least in 2003 version) references the IE dll directly to render the \"Design View\".</p>\n\n<p>It may be worth looking into that.</p>\n\n<p>Otherwise, I can't think of anything beyond the Web Browser control.</p>\n"
},
{
"answer_id": 768,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 5,
"selected": false,
"text": "<p>You can print from the command line using the following:</p>\n\n<blockquote>\n <p>rundll32.exe\n %WINDIR%\\System32\\mshtml.dll,PrintHTML\n \"%1\"</p>\n</blockquote>\n\n<p>Where %1 is the file path of the HTML file to be printed.</p>\n\n<p>If you don't need to print from memory (or can afford to write to the disk in a temp file) you can use:</p>\n\n<pre><code>using (Process printProcess = new Process())\n{\n string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);\n printProcess.StartInfo.FileName = systemPath + @\"\\rundll32.exe\";\n printProcess.StartInfo.Arguments = systemPath + @\"\\mshtml.dll,PrintHTML \"\"\" + fileToPrint + @\"\"\"\";\n printProcess.Start();\n}\n</code></pre>\n\n<p>N.B. This only works on Windows 2000 and above I think.</p>\n"
},
{
"answer_id": 108827,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": -1,
"selected": false,
"text": "<p>I don't know the specific tools, but there are some utilities that record / replay clicks. In other words, you could automate the \"click\" on the print dialog. (I know this is a hack, but when all else fails...)</p>\n"
},
{
"answer_id": 1008517,
"author": "NastyNateDoggy",
"author_id": 124479,
"author_profile": "https://Stackoverflow.com/users/124479",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe this will help. <a href=\"http://www.codeproject.com/KB/printing/printhml.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/printing/printhml.aspx</a>\nAlso not sure what thread you are trying to access the browser control from, but it needs to be STA</p>\n\n<p>Note - The project referred to in the link does allow you to navigate to a page and perform a print without showing the print dialog.</p>\n"
},
{
"answer_id": 2624191,
"author": "user314783",
"author_id": 314783,
"author_profile": "https://Stackoverflow.com/users/314783",
"pm_score": 2,
"selected": false,
"text": "<p>If you've got it in the budget (~$3000), check out <a href=\"http://www.princexml.com\" rel=\"nofollow noreferrer\">PrinceXML</a>.</p>\n\n<p>It will render HTML into a PDF, functions well in a service environment, and supports advanced features such as not breaking a page in the middle of a table cell (which a lot of browsers don't currently support). </p>\n"
},
{
"answer_id": 11970128,
"author": "Colonel Panic",
"author_id": 284795,
"author_profile": "https://Stackoverflow.com/users/284795",
"pm_score": 3,
"selected": false,
"text": "<p>Easy! Split your problem into two simpler parts:</p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/a/5635643/284795\">render the HTML to PDF</a></li>\n<li>print the PDF (<a href=\"http://blog.kowalczyk.info/software/sumatrapdf/manual.html#manual-cmd-line\" rel=\"noreferrer\">SumatraPDF</a>)</li>\n</ol>\n\n<blockquote>\n <ul>\n <li><code>-print-to-default $file.pdf</code> prints a PDF file on a default printer </li>\n <li><code>-print-to $printer_name $file.pdf</code> prints a PDF on a given printer</li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 57838787,
"author": "AnthonyVO",
"author_id": 438458,
"author_profile": "https://Stackoverflow.com/users/438458",
"pm_score": 2,
"selected": false,
"text": "<p>I tool that works very well for me is HiQPdf. <a href=\"https://www.hiqpdf.com/\" rel=\"nofollow noreferrer\">https://www.hiqpdf.com/</a></p>\n\n<p>The price is reasonable (starts at $245) and it can render HTML to a PDF and also manage the printing of the PDF files directly.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96/"
] | I want to print HTML from a C# web service. The web browser control is overkill, and does not function well in a service environment, nor does it function well on a system with very tight security constraints. Is there any sort of free `.NET` library that will support the printing of a basic HTML page? Here is the code I have so far, which does not run properly.
```
public void PrintThing(string document)
{
if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
{
Thread thread =
new Thread((ThreadStart) delegate { PrintDocument(document); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
else
{
PrintDocument(document);
}
}
protected void PrintDocument(string document)
{
WebBrowser browser = new WebBrowser();
browser.DocumentText = document;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Print();
}
```
This works fine when called from UI-type threads, but nothing happens when called from a service-type thread. Changing `Print()` to `ShowPrintPreviewDialog()` yields the following IE script error:
>
> **Error:** `dialogArguments.___IE_PrintType` is null or not an object.
>
>
> URL: `res://ieframe.dll/preview.dlg`
>
>
>
And a small empty print preview dialog appears. | You can print from the command line using the following:
>
> rundll32.exe
> %WINDIR%\System32\mshtml.dll,PrintHTML
> "%1"
>
>
>
Where %1 is the file path of the HTML file to be printed.
If you don't need to print from memory (or can afford to write to the disk in a temp file) you can use:
```
using (Process printProcess = new Process())
{
string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
printProcess.StartInfo.FileName = systemPath + @"\rundll32.exe";
printProcess.StartInfo.Arguments = systemPath + @"\mshtml.dll,PrintHTML """ + fileToPrint + @"""";
printProcess.Start();
}
```
N.B. This only works on Windows 2000 and above I think. |
175 | <p>I want to be able to display a normal YouTube video with overlaid annotations, consisting of coloured rectangles for each frame. The only requirement is that this should be done programmatically. </p>
<p>YouTube has annotations now, but require you to use their front end to create them by hand. I want to be able to generate them. What's the best way of doing this?</p>
<p>Some ideas:</p>
<blockquote>
<ol>
<li>Build your own Flash player (ew?)</li>
<li>Somehow draw over the YouTube Flash player. Will this work?</li>
<li>Reverse engineer & hijack YouTube's annotation system. Either messing with the local files or redirecting its attempt to download
the annotations. (using Greasemonkey? Firefox plugin?)</li>
</ol>
</blockquote>
<p>Idea that doesn't count: </p>
<blockquote>
<p>download the video</p>
</blockquote>
| [
{
"answer_id": 7157,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 3,
"selected": false,
"text": "<p>The player itself has a <a href=\"http://code.google.com/apis/youtube/js_api_reference.html\" rel=\"noreferrer\">Javascript API</a> that might be useful for syncing the video if you choose to make your own <code>annotation-thingamajig</code>.</p>\n"
},
{
"answer_id": 65659,
"author": "nerdabilly",
"author_id": 8349,
"author_profile": "https://Stackoverflow.com/users/8349",
"pm_score": 4,
"selected": false,
"text": "<p>YouTube provides an <a href=\"http://code.google.com/apis/youtube/flash_api_reference.html\" rel=\"noreferrer\">ActionScript API</a>.</p>\n\n<p>Using this, you could load the videos into Flash using their API and then have your Flash app create the annotations on a layer above the video. </p>\n\n<p>Or, alternatively, if you want to stay away from creating something in Flash, using YouTube's JavaScript API you could draw HTML DIVs over the YouTube player on your web page. Just remember when you embed the player to have <code>WMODE=\"transparent\"</code> in the params list. </p>\n\n<p>So using the example from YouTube:</p>\n\n<pre><code> <script type=\"text/javascript\">\n\n var params = { allowScriptAccess: \"always\" };\n var atts = { id: \"myytplayer\", wmode: \"transparent\" };\n swfobject.embedSWF(\"http://www.youtube.com/v/VIDEO_ID&enablejsapi=1&playerapiid=ytplayer\", \n \"ytapiplayer\", \"425\", \"356\", \"8\", null, null, params, atts);\n\n </script>\n</code></pre>\n\n<p>And then you should be able to draw your annotations over the YouTube movie using CSS/DHTML. </p>\n"
},
{
"answer_id": 106818,
"author": "marstonstudio",
"author_id": 19447,
"author_profile": "https://Stackoverflow.com/users/19447",
"pm_score": 3,
"selected": false,
"text": "<p>Joe Berkovitz has written a sample application called <code>ReviewTube</code> which \"Allows users to create time-based subtitles for any YouTube video, a la closed captioning. These captions become publicly accessible, and visitors to the site can browse the set of videos with captions. Think of it as a “subtitle graffiti wall” for YouTube!\"</p>\n\n<p>The app is the example used to demonstrate the MVCS framework/approach for building Flex applications.</p>\n\n<p><a href=\"http://www.joeberkovitz.com/blog/reviewtube/\" rel=\"noreferrer\">http://www.joeberkovitz.com/blog/reviewtube/</a></p>\n\n<p>Not sure if this will help with the colored rectangles and whatnot, but it's a decent place to start.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2089740/"
] | I want to be able to display a normal YouTube video with overlaid annotations, consisting of coloured rectangles for each frame. The only requirement is that this should be done programmatically.
YouTube has annotations now, but require you to use their front end to create them by hand. I want to be able to generate them. What's the best way of doing this?
Some ideas:
>
> 1. Build your own Flash player (ew?)
> 2. Somehow draw over the YouTube Flash player. Will this work?
> 3. Reverse engineer & hijack YouTube's annotation system. Either messing with the local files or redirecting its attempt to download
> the annotations. (using Greasemonkey? Firefox plugin?)
>
>
>
Idea that doesn't count:
>
> download the video
>
>
> | YouTube provides an [ActionScript API](http://code.google.com/apis/youtube/flash_api_reference.html).
Using this, you could load the videos into Flash using their API and then have your Flash app create the annotations on a layer above the video.
Or, alternatively, if you want to stay away from creating something in Flash, using YouTube's JavaScript API you could draw HTML DIVs over the YouTube player on your web page. Just remember when you embed the player to have `WMODE="transparent"` in the params list.
So using the example from YouTube:
```
<script type="text/javascript">
var params = { allowScriptAccess: "always" };
var atts = { id: "myytplayer", wmode: "transparent" };
swfobject.embedSWF("http://www.youtube.com/v/VIDEO_ID&enablejsapi=1&playerapiid=ytplayer",
"ytapiplayer", "425", "356", "8", null, null, params, atts);
</script>
```
And then you should be able to draw your annotations over the YouTube movie using CSS/DHTML. |
176 | <p>On one Linux Server running Apache and PHP 5, we have multiple Virtual Hosts with separate log files. We cannot seem to separate the php <code>error_log</code> between virtual hosts.</p>
<p>Overriding this setting in the <code><Location></code> of the <code>httpd.conf</code> does not seem to do anything.</p>
<p>Is there a way to have separate php <code>error_logs</code> for each Virtual Host?</p>
| [
{
"answer_id": 207,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 7,
"selected": true,
"text": "<p>To set the <em>Apache</em> (<em>not the PHP</em>) log, the easiest way to do this would be to do:</p>\n\n<pre><code><VirtualHost IP:Port>\n # Stuff,\n # More Stuff,\n ErrorLog /path/where/you/want/the/error.log\n</VirtualHost>\n</code></pre>\n\n<p>If there is no leading \"/\" it is assumed to be relative.</p>\n\n<p><a href=\"http://httpd.apache.org/docs/1.3/mod/core.html#errorlog\" rel=\"noreferrer\">Apache Error Log Page</a></p>\n"
},
{
"answer_id": 236,
"author": "Mat",
"author_id": 48,
"author_profile": "https://Stackoverflow.com/users/48",
"pm_score": 3,
"selected": false,
"text": "<p>The default behaviour for error_log() is to output to the Apache error log. If this isn't happening check your php.ini settings for the error_log directive. Leave it unset to use the Apache log file for the current vhost.</p>\n"
},
{
"answer_id": 297,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 4,
"selected": false,
"text": "<p>I usually just specify this in an <code>.htaccess</code> file <em>or</em> the <code>vhost.conf</code> on the domain I'm working on. Add this to one of these files:</p>\n\n<pre><code>php_admin_value error_log \"/var/www/vhosts/example.com/error_log\"\n</code></pre>\n"
},
{
"answer_id": 6568,
"author": "ejunker",
"author_id": 796,
"author_profile": "https://Stackoverflow.com/users/796",
"pm_score": 2,
"selected": false,
"text": "<p>My Apache had something like this in httpd.conf. Just change the ErrorLog and CustomLog settings </p>\n\n<pre><code><VirtualHost myvhost:80>\n ServerAdmin webmaster@dummy-host.example.com\n DocumentRoot /opt/web\n ServerName myvhost\n ErrorLog logs/myvhost-error_log\n CustomLog logs/myvhost-access_log common\n</VirtualHost>\n</code></pre>\n"
},
{
"answer_id": 34044,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 3,
"selected": false,
"text": "<p>Try adding the <code>php_value error_log '/path/to/php_error_log</code> to your VirtualHost configuration.</p>\n"
},
{
"answer_id": 118200,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You can try:</p>\n<pre><code> <VirtualHost myvhost:80>\n php_value error_log "/var/log/httpd/vhost_php_error_log"\n </Virtual Host>\n</code></pre>\n<p>But I'm not sure if it is going to work. I tried on my sites with no success.</p>\n"
},
{
"answer_id": 118222,
"author": "James Hartig",
"author_id": 45530,
"author_profile": "https://Stackoverflow.com/users/45530",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, you can try,</p>\n\n<pre><code>php_value error_log \"/var/log/php_log\" \n</code></pre>\n\n<p>in <code>.htaccess</code> or you can have users use <code>ini_set()</code> in the beginning of their scripts if they want to have logging.</p>\n\n<p>Another option would be to enable scripts to default to the <code>php.ini</code> in the folder with the script, then go to the user/host's root folder, then to the server's root, or something similar. This would allow hosts to add their own <code>php.ini</code> values and their own <code>error_log</code> locations.</p>\n"
},
{
"answer_id": 1077264,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>php_value error_log \"/var/log/httpd/vhost_php_error_log\"\n</code></pre>\n\n<p>It works for me, but I have to change the permission of the log file.</p>\n\n<p>or Apache will write the log to the its <code>error_log</code>.</p>\n"
},
{
"answer_id": 2569128,
"author": "rkulla",
"author_id": 308062,
"author_profile": "https://Stackoverflow.com/users/308062",
"pm_score": 3,
"selected": false,
"text": "<p>Don't set <code>error_log</code> to where your <code>syslog</code> stuff goes, <code>eg /var/log/apache2</code>, because they errors will get intercepted by <code>ErrorLog</code>. Instead, create a <code>subdir</code> in your <em>project folder</em> for logs and do <code>php_value</code> <code>error_log \"/path/to/project/logs\"</code>. This goes for both <code>.htaccess</code> <em>files and vhosts</em>. Also make sure you put <code>php_flag</code> <code>log_errors</code> on</p>\n"
},
{
"answer_id": 3576664,
"author": "Clutch",
"author_id": 25143,
"author_profile": "https://Stackoverflow.com/users/25143",
"pm_score": 7,
"selected": false,
"text": "<p>If somebody comes looking it should look like this:</p>\n<pre><code><VirtualHost *:80>\n ServerName example.com\n DocumentRoot /var/www/domains/example.com/html\n ErrorLog /var/www/domains/example.com/apache.error.log\n CustomLog /var/www/domains/example.com/apache.access.log common\n php_flag log_errors on\n php_flag display_errors on\n php_value error_reporting 2147483647\n php_value error_log /var/www/domains/example.com/php.error.log\n</VirtualHost>\n</code></pre>\n<p>This is for <em>development only</em> since <code>display_error</code> is turned on. You will notice that the Apache error log is separate from the PHP error log. The good stuff is in <code>php.error.log</code>.</p>\n<p>Take a look here for the <code>error_reporting</code> key <a href=\"http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting\" rel=\"noreferrer\">http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting</a></p>\n"
},
{
"answer_id": 50618440,
"author": "Parveen Chauhan",
"author_id": 7013481,
"author_profile": "https://Stackoverflow.com/users/7013481",
"pm_score": 2,
"selected": false,
"text": "<p>Create Simple VirtualHost:</p>\n\n<p>example hostname:- <code>thecontrolist.localhost</code></p>\n\n<ol>\n<li><p>C:\\Windows\\System32\\drivers\\etc</p>\n\n<p><code>127.0.0.1 thecontrolist.localhost</code> in hosts file </p></li>\n<li><p>C:\\xampp\\apache\\conf\\extra\\httpd-vhosts.conf </p>\n\n<pre><code><VirtualHost *>\n ServerName thecontrolist.localhost\n ServerAlias thecontrolist.localhost\n DocumentRoot \"/xampp/htdocs/thecontrolist\"\n <Directory \"/xampp/htdocs/thecontrolist\">\n Options +Indexes +Includes +FollowSymLinks +MultiViews\n AllowOverride All\n Require local\n </Directory>\n</VirtualHost>\n</code></pre></li>\n<li><p>Don't Forget to restart Your apache. \nfor more <a href=\"https://wiki.apache.org/httpd/ExampleVhosts\" rel=\"nofollow noreferrer\">check</a> this link</p></li>\n</ol>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | On one Linux Server running Apache and PHP 5, we have multiple Virtual Hosts with separate log files. We cannot seem to separate the php `error_log` between virtual hosts.
Overriding this setting in the `<Location>` of the `httpd.conf` does not seem to do anything.
Is there a way to have separate php `error_logs` for each Virtual Host? | To set the *Apache* (*not the PHP*) log, the easiest way to do this would be to do:
```
<VirtualHost IP:Port>
# Stuff,
# More Stuff,
ErrorLog /path/where/you/want/the/error.log
</VirtualHost>
```
If there is no leading "/" it is assumed to be relative.
[Apache Error Log Page](http://httpd.apache.org/docs/1.3/mod/core.html#errorlog) |
180 | <p>This is something I've pseudo-solved many times and have never quite found a solution for.</p>
<p>The problem is to come up with a way to generate <code>N</code> colors, that are as distinguishable as possible where <code>N</code> is a parameter.</p>
| [
{
"answer_id": 199,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 2,
"selected": false,
"text": "<p>I've read somewhere the human eye can't distinguish between less than 4 values apart. so This is something to keep in mind. The following algorithm does not compensate for this.</p>\n\n<p>I'm not sure this is exactly what you want, but this is one way to randomly generate non-repeating color values:</p>\n\n<p>(beware, inconsistent pseudo-code ahead)</p>\n\n<pre><code>//colors entered as 0-255 [R, G, B]\ncolors = []; //holds final colors to be used\nrand = new Random();\n\n//assumes n is less than 16,777,216\nrandomGen(int n){\n while (len(colors) < n){\n //generate a random number between 0,255 for each color\n newRed = rand.next(256);\n newGreen = rand.next(256);\n newBlue = rand.next(256);\n temp = [newRed, newGreen, newBlue];\n //only adds new colors to the array\n if temp not in colors {\n colors.append(temp);\n }\n }\n}\n</code></pre>\n\n<p>One way you could optimize this for better visibility would be to compare the distance between each new color and all the colors in the array:</p>\n\n<pre><code>for item in color{\n itemSq = (item[0]^2 + item[1]^2 + item[2]^2])^(.5);\n tempSq = (temp[0]^2 + temp[1]^2 + temp[2]^2])^(.5);\n dist = itemSq - tempSq;\n dist = abs(dist);\n}\n//NUMBER can be your chosen distance apart.\nif dist < NUMBER and temp not in colors {\n colors.append(temp);\n}\n</code></pre>\n\n<p>But this approach would significantly slow down your algorithm.</p>\n\n<p>Another way would be to scrap the randomness and systematically go through every 4 values and add a color to an array in the above example.</p>\n"
},
{
"answer_id": 529,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 3,
"selected": false,
"text": "<p>Isn't it also a factor which order you set up the colors?</p>\n\n<p>Like if you use Dillie-Os idea you need to mix the colors as much as possible. \n0 64 128 256 is from one to the next. but 0 256 64 128 in a wheel would be more \"apart\"</p>\n\n<p>Does this make sense?</p>\n"
},
{
"answer_id": 539,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 6,
"selected": true,
"text": "<p>My first thought on this is \"how to generate N vectors in a space that maximize distance from each other.\"</p>\n\n<p>You can see that the RGB (or any other scale you use that forms a basis in color space) are just vectors. Take a look at <a href=\"http://mathworld.wolfram.com/topics/RandomPointPicking.html\" rel=\"noreferrer\">Random Point Picking</a>. Once you have a set of vectors that are maximized apart, you can save them in a hash table or something for later, and just perform random rotations on them to get all the colors you desire that are maximally apart from each other!</p>\n\n<p>Thinking about this problem more, it would be better to map the colors in a linear manner, possibly (0,0,0) → (255,255,255) lexicographically, and then distribute them evenly.</p>\n\n<p>I really don't know how well this will work, but it should since, let us say:</p>\n\n<pre><code>n = 10\n</code></pre>\n\n<p>we know we have 16777216 colors (256^3).</p>\n\n<p>We can use <a href=\"https://stackoverflow.com/questions/561/using-combinations-of-sets-as-test-data#794\">Buckles Algorithm 515</a> to find the lexicographically indexed color.<img src=\"https://i.stack.imgur.com/gEuCs.gif\" alt=\"\\frac {\\binom {256^3} {3}} {n} * i\">. You'll probably have to edit the algorithm to avoid overflow and probably add some minor speed improvements.</p>\n"
},
{
"answer_id": 59760,
"author": "Liudvikas Bukys",
"author_id": 5845,
"author_profile": "https://Stackoverflow.com/users/5845",
"pm_score": 4,
"selected": false,
"text": "<p>It would be best to find colors maximally distant in a \"perceptually uniform\" colorspace, e.g. CIELAB (using Euclidean distance between L*, a*, b* coordinates as your distance metric) and then converting to the colorspace of your choice. Perceptual uniformity is achieved by tweaking the colorspace to approximate the non-linearities in the human visual system.</p>\n"
},
{
"answer_id": 93908,
"author": "hadley",
"author_id": 16632,
"author_profile": "https://Stackoverflow.com/users/16632",
"pm_score": 4,
"selected": false,
"text": "<p>Some related resources:</p>\n\n<p><a href=\"http://colorbrewer.org\" rel=\"noreferrer\">ColorBrewer</a> - Sets of colours designed to be maximally distinguishable for use on maps.</p>\n\n<p><a href=\"http://epub.wu-wien.ac.at/dyn/openURL?id=oai:epub.wu-wien.ac.at:epub-wu-01_c87\" rel=\"noreferrer\">Escaping RGBland: Selecting Colors for Statistical Graphics</a> - A technical report describing a set of algorithms for generating good (i.e. maximally distinguishable) colour sets in the hcl colour space.</p>\n"
},
{
"answer_id": 143966,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": 3,
"selected": false,
"text": "<p>Here is some code to allocate RGB colors evenly around a HSL color wheel of specified luminosity.</p>\n\n<pre><code>class cColorPicker\n{\npublic:\n void Pick( vector<DWORD>&v_picked_cols, int count, int bright = 50 );\nprivate:\n DWORD HSL2RGB( int h, int s, int v );\n unsigned char ToRGB1(float rm1, float rm2, float rh);\n};\n/**\n\n Evenly allocate RGB colors around HSL color wheel\n\n @param[out] v_picked_cols a vector of colors in RGB format\n @param[in] count number of colors required\n @param[in] bright 0 is all black, 100 is all white, defaults to 50\n\n based on Fig 3 of http://epub.wu-wien.ac.at/dyn/virlib/wp/eng/mediate/epub-wu-01_c87.pdf?ID=epub-wu-01_c87\n\n*/\n\nvoid cColorPicker::Pick( vector<DWORD>&v_picked_cols, int count, int bright )\n{\n v_picked_cols.clear();\n for( int k_hue = 0; k_hue < 360; k_hue += 360/count )\n v_picked_cols.push_back( HSL2RGB( k_hue, 100, bright ) );\n}\n/**\n\n Convert HSL to RGB\n\n based on http://www.codeguru.com/code/legacy/gdi/colorapp_src.zip\n\n*/\n\nDWORD cColorPicker::HSL2RGB( int h, int s, int l )\n{\n DWORD ret = 0;\n unsigned char r,g,b;\n\n float saturation = s / 100.0f;\n float luminance = l / 100.f;\n float hue = (float)h;\n\n if (saturation == 0.0) \n {\n r = g = b = unsigned char(luminance * 255.0);\n }\n else\n {\n float rm1, rm2;\n\n if (luminance <= 0.5f) rm2 = luminance + luminance * saturation; \n else rm2 = luminance + saturation - luminance * saturation;\n rm1 = 2.0f * luminance - rm2; \n r = ToRGB1(rm1, rm2, hue + 120.0f); \n g = ToRGB1(rm1, rm2, hue);\n b = ToRGB1(rm1, rm2, hue - 120.0f);\n }\n\n ret = ((DWORD)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16)));\n\n return ret;\n}\n\n\nunsigned char cColorPicker::ToRGB1(float rm1, float rm2, float rh)\n{\n if (rh > 360.0f) rh -= 360.0f;\n else if (rh < 0.0f) rh += 360.0f;\n\n if (rh < 60.0f) rm1 = rm1 + (rm2 - rm1) * rh / 60.0f; \n else if (rh < 180.0f) rm1 = rm2;\n else if (rh < 240.0f) rm1 = rm1 + (rm2 - rm1) * (240.0f - rh) / 60.0f; \n\n return static_cast<unsigned char>(rm1 * 255);\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n vector<DWORD> myCols;\n cColorPicker colpick;\n colpick.Pick( myCols, 20 );\n for( int k = 0; k < (int)myCols.size(); k++ )\n printf(\"%d: %d %d %d\\n\", k+1,\n ( myCols[k] & 0xFF0000 ) >>16,\n ( myCols[k] & 0xFF00 ) >>8,\n ( myCols[k] & 0xFF ) );\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 7815745,
"author": "Mauro",
"author_id": 678455,
"author_profile": "https://Stackoverflow.com/users/678455",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function random_color($i = null, $n = 10, $sat = .5, $br = .7) {\n $i = is_null($i) ? mt_rand(0,$n) : $i;\n $rgb = hsv2rgb(array($i*(360/$n), $sat, $br));\n for ($i=0 ; $i<=2 ; $i++) \n $rgb[$i] = dechex(ceil($rgb[$i]));\n return implode('', $rgb);\n}\n\nfunction hsv2rgb($c) { \n list($h,$s,$v)=$c; \n if ($s==0) \n return array($v,$v,$v); \n else { \n $h=($h%=360)/60; \n $i=floor($h); \n $f=$h-$i; \n $q[0]=$q[1]=$v*(1-$s); \n $q[2]=$v*(1-$s*(1-$f)); \n $q[3]=$q[4]=$v; \n $q[5]=$v*(1-$s*$f); \n return(array($q[($i+4)%6]*255,$q[($i+2)%6]*255,$q[$i%6]*255)); //[1] \n } \n}\n</code></pre>\n<p>So just call the <code>random_color()</code> function where <code>$i</code> identifies the color, <code>$n</code> the number of possible colors, <code>$sat</code> the saturation and <code>$br</code> the brightness.</p>\n"
},
{
"answer_id": 21634390,
"author": "Adi Shavit",
"author_id": 135862,
"author_profile": "https://Stackoverflow.com/users/135862",
"pm_score": 2,
"selected": false,
"text": "<p>To achieve "most distinguishable" we need to use a perceptual color space like Lab (or any other perceptually linear color space) other than RGB. Also, we can quantize this space to reduce the size of the space.</p>\n<p>Generate the full 3D space with all possible quantized entries and run the K-means algorithm with <code>K=N</code>. The resulting centers/"means" should be approximately most distinguishable from each other.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2089740/"
] | This is something I've pseudo-solved many times and have never quite found a solution for.
The problem is to come up with a way to generate `N` colors, that are as distinguishable as possible where `N` is a parameter. | My first thought on this is "how to generate N vectors in a space that maximize distance from each other."
You can see that the RGB (or any other scale you use that forms a basis in color space) are just vectors. Take a look at [Random Point Picking](http://mathworld.wolfram.com/topics/RandomPointPicking.html). Once you have a set of vectors that are maximized apart, you can save them in a hash table or something for later, and just perform random rotations on them to get all the colors you desire that are maximally apart from each other!
Thinking about this problem more, it would be better to map the colors in a linear manner, possibly (0,0,0) → (255,255,255) lexicographically, and then distribute them evenly.
I really don't know how well this will work, but it should since, let us say:
```
n = 10
```
we know we have 16777216 colors (256^3).
We can use [Buckles Algorithm 515](https://stackoverflow.com/questions/561/using-combinations-of-sets-as-test-data#794) to find the lexicographically indexed color.![\frac {\binom {256^3} {3}} {n} * i](https://i.stack.imgur.com/gEuCs.gif). You'll probably have to edit the algorithm to avoid overflow and probably add some minor speed improvements. |
227 | <p>I have the following arrays:</p>
<pre><code>$artist = array("the roots", "michael jackson", "billy idol", "more", "and more", "and_YET_MORE");
$count = array(5, 3, 9, 1, 1, 3);
</code></pre>
<p>I want to generate a tag cloud that will have artists with a higher number in <code>$count</code> enclosed in <code>h6</code> tags and the lowest enclosed <code>h1</code> tags.</p>
| [
{
"answer_id": 253,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 5,
"selected": false,
"text": "<p>Off the top of my head...</p>\n\n<pre><code>$artist = array(\"the roots\",\"michael jackson\",\"billy idol\",\"more\",\"and more\",\"and_YET_MORE\");\n$count = array(5,3,9,1,1,3);\n$highest = max($count);\nfor (int $x = 0; $x < count($artist); $x++)\n{\n $normalized = $count[$x] / $highest;\n $heading = ceil($normalized * 6); // 6 heading types\n echo \"<h\".$heading.\">\".$artist[$x].\"</h\".$heading.\">\";\n}\n</code></pre>\n"
},
{
"answer_id": 274,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 3,
"selected": false,
"text": "<p>@Ryan</p>\n\n<p>That's correct but it actually makes the tags with the least number, larger. This code has been tested:</p>\n\n<pre><code>$artist = array(\"the roots\",\"michael jackson\",\"billy idol\",\"more\",\"and more\",\"and_YET_MORE\");\n$count = array(5,3,9,1,1,3);\n$highest = max($count);\nfor ($x = 0; $x < count($artist); $x++) {\n $normalized = ($highest - $count[$x]+1) / $highest;\n $heading = ceil($normalized * 6); // 6 heading types\n echo \"<h$heading>{$artist[$x]}</h$heading>\";\n}\n</code></pre>\n"
},
{
"answer_id": 676,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 5,
"selected": false,
"text": "<p>Perhaps this is a little academic and off topic but <code>hX</code> tags are probably not the best choice for a tag cloud for reasons of document structure and all that sort of thing.</p>\n\n<p>Maybe <code>span</code>s or an <code>ol</code> with appropriate class attributes (plus some CSS)?</p>\n"
},
{
"answer_id": 87863,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Have used this snippet for a while, credit is prism-perfect.net. Doesn't use H tags though</p>\n\n<pre><code><div id=\"tags\">\n <div class=\"title\">Popular Searches</div>\n <?php\n // Snippet taken from [prism-perfect.net]\n\n include \"/path/to/public_html/search/settings/database.php\";\n include \"/path/to/public_html/search/settings/conf.php\";\n\n $query = \"SELECT query AS tag, COUNT(*) AS quantity\n FROM sphider_query_log\n WHERE results > 0\n GROUP BY query\n ORDER BY query ASC\n LIMIT 10\";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ($row = mysql_fetch_array($result)) {\n\n $tags[$row['tag']] = $row['quantity'];\n }\n\n // change these font sizes if you will\n $max_size = 30; // max font size in %\n $min_size = 11; // min font size in %\n\n // get the largest and smallest array values\n $max_qty = max(array_values($tags));\n $min_qty = min(array_values($tags));\n\n // find the range of values\n $spread = $max_qty - $min_qty;\n if (0 == $spread) { // we don't want to divide by zero\n $spread = 1;\n }\n\n // determine the font-size increment\n // this is the increase per tag quantity (times used)\n $step = ($max_size - $min_size)/($spread);\n\n // loop through our tag array\n foreach ($tags as $key => $value) {\n\n // calculate CSS font-size\n // find the $value in excess of $min_qty\n // multiply by the font-size increment ($size)\n // and add the $min_size set above\n $size = $min_size + (($value - $min_qty) * $step);\n // uncomment if you want sizes in whole %:\n // $size = ceil($size);\n\n // you'll need to put the link destination in place of the /search/search.php...\n // (assuming your tag links to some sort of details page)\n echo '<a href=\"/search/search.php?query='.$key.'&search=1\" style=\"font-size: '.$size.'px\"';\n // perhaps adjust this title attribute for the things that are tagged\n echo ' title=\"'.$value.' things tagged with '.$key.'\"';\n echo '>'.$key.'</a> ';\n // notice the space at the end of the link\n }\n ?>\n</div>\n</code></pre>\n"
},
{
"answer_id": 164758,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>As a helper in Rails:</p>\n\n<pre><code>def tag_cloud (strings, counts)\n max = counts.max\n strings.map { |a| \"<span style='font-size:#{((counts[strings.index(a)] * 4.0)/max).ceil}em'>#{a}</span> \" }\nend\n</code></pre>\n\n<p>Call this from the view:</p>\n\n<pre><code><%= tag_cloud($artists, $counts) %>\n</code></pre>\n\n<p>This outputs <code><span style='font-size:_em'></code> elements in an array that will be converted to a string in the view to ultimately render like so:</p>\n\n<pre><code><span style='font-size:3em'>the roots</span>\n<span style='font-size:2em'>michael jackson</span> \n<span style='font-size:4em'>billy idol</span> \n<span style='font-size:1em'>more</span> \n<span style='font-size:1em'>and more</span> \n<span style='font-size:2em'>and_YET_MORE</span> \n</code></pre>\n\n<p>It would be better to have a <code>class</code> attribute and reference the classes in a style sheet as mentioned by Brendan above. Much better than using <code>h1-h6</code> semantically and there's less style baggage with a <code><span></code>.</p>\n"
},
{
"answer_id": 2943318,
"author": "berkes",
"author_id": 73673,
"author_profile": "https://Stackoverflow.com/users/73673",
"pm_score": 6,
"selected": true,
"text": "<p>You will want to add a logarithmic function to it too. (taken from tagadelic, my Drupal module to create tag clouds <a href=\"http://drupal.org/project/tagadelic\" rel=\"noreferrer\">http://drupal.org/project/tagadelic</a>):</p>\n\n<pre><code>db_query('SELECT COUNT(*) AS count, id, name FROM ... ORDER BY count DESC');\n\n$steps = 6;\n$tags = array();\n$min = 1e9;\n$max = -1e9;\n\nwhile ($tag = db_fetch_object($result)) {\n $tag->number_of_posts = $tag->count; #sets the amount of items a certain tag has attached to it\n $tag->count = log($tag->count);\n $min = min($min, $tag->count);\n $max = max($max, $tag->count);\n $tags[$tag->tid] = $tag;\n}\n// Note: we need to ensure the range is slightly too large to make sure even\n// the largest element is rounded down.\n$range = max(.01, $max - $min) * 1.0001;\n\nforeach ($tags as $key => $value) {\n $tags[$key]->weight = 1 + floor($steps * ($value->count - $min) / $range);\n}\n</code></pre>\n\n<p>Then in your view or template:</p>\n\n<pre><code>foreach ($tags as $tag) {\n $output .= \"<h$tag->weight>$tag->name</h$tag->weight>\"\n}\n</code></pre>\n"
},
{
"answer_id": 3249162,
"author": "danieli",
"author_id": 83382,
"author_profile": "https://Stackoverflow.com/users/83382",
"pm_score": 2,
"selected": false,
"text": "<p>This method is for <code>SQL/PostgreSQL</code> fanatics. It does the entire job in the database, and it prints text with \"slugified\" link. It uses Doctrine <code>ORM</code> just for the sql call, I'm not using objects. \nSuppose we have 10 sizes:</p>\n\n<pre><code>public function getAllForTagCloud($fontSizes = 10)\n{\n $sql = sprintf(\"SELECT count(tag) as tagcount,tag,slug, \n floor((count(*) * %d )/(select max(t) from \n (select count(tag) as t from magazine_tag group by tag) t)::numeric(6,2)) \n as ranking \n from magazine_tag mt group by tag,slug\", $fontSizes);\n\n $q = Doctrine_Manager::getInstance()->getCurrentConnection();\n return $q->execute($sql);\n}\n</code></pre>\n\n<p>then you print them with some CSS class, from .tagranking10 (the best) to .tagranking1 (the worst):</p>\n\n<pre><code><?php foreach ($allTags as $tag): ?>\n <span class=\"<?php echo 'tagrank'.$tag['ranking'] ?>\">\n <?php echo sprintf('<a rel=\"tag\" href=\"/search/by/tag/%s\">%s</a>', \n $tag['slug'], $tag['tag']\n ); ?>\n </span>\n<?php endforeach; ?>\n</code></pre>\n\n<p>and this is the <code>CSS</code>:</p>\n\n<pre><code>/* put your size of choice */\n.tagrank1{font-size: 0.3em;}\n.tagrank2{font-size: 0.4em;}\n.tagrank3{font-size: 0.5em;} \n/* go on till tagrank10 */\n</code></pre>\n\n<p>This method displays all tags. If you have a lot of them, you probably don't want your tag cloud to become a <em>tag storm</em>. In that case you would append an <code>HAVING TO</code> clause to your SQL query:</p>\n\n<pre><code>-- minimum tag count is 8 --\n\nHAVING count(tag) > 7\n</code></pre>\n\n<p>That's all</p>\n"
},
{
"answer_id": 41906389,
"author": "Durgaprasad",
"author_id": 3391693,
"author_profile": "https://Stackoverflow.com/users/3391693",
"pm_score": 2,
"selected": false,
"text": "<p>I know it's a very old post, still I'm posting my view as it may help someone in future.</p>\n<p>Here is the tagcloud I used in my website:\n<a href=\"http://www.vbausefulcodes.in/\" rel=\"nofollow noreferrer\">http://www.vbausefulcodes.in/</a></p>\n<pre><code><?php\n$input= array("vba","macros","excel","outlook","powerpoint","access","database","interview questions","sendkeys","word","excel projects","visual basic projects","excel vba","macro","excel visual basic","tutorial","programming","learn macros","vba examples");\n\n$rand_tags = array_rand($input, 5);\nfor ($x = 0; $x <= 4; $x++) {\n $size = rand ( 1 , 4 );\n echo "<font size='$size'>" . $input[$rand_tags[$x]] . " " . "</font>";\n}\n\necho "<br>";\n$rand_tags = array_rand($input, 7);\nfor ($x = 0; $x <= 6; $x++) {\n $size = rand ( 1 , 4 );\n echo "<font size='$size'>" . $input[$rand_tags[$x]] . " " . "</font>";\n}\n\necho "<br>";\n$rand_tags = array_rand($input, 5);\nfor ($x = 0; $x <= 4; $x++) {\n $size = rand ( 1 , 4 );\n echo "<font size='$size'>" . $input[$rand_tags[$x]] . " " . "</font>";\n}\n?>\n</code></pre>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146637/"
] | I have the following arrays:
```
$artist = array("the roots", "michael jackson", "billy idol", "more", "and more", "and_YET_MORE");
$count = array(5, 3, 9, 1, 1, 3);
```
I want to generate a tag cloud that will have artists with a higher number in `$count` enclosed in `h6` tags and the lowest enclosed `h1` tags. | You will want to add a logarithmic function to it too. (taken from tagadelic, my Drupal module to create tag clouds <http://drupal.org/project/tagadelic>):
```
db_query('SELECT COUNT(*) AS count, id, name FROM ... ORDER BY count DESC');
$steps = 6;
$tags = array();
$min = 1e9;
$max = -1e9;
while ($tag = db_fetch_object($result)) {
$tag->number_of_posts = $tag->count; #sets the amount of items a certain tag has attached to it
$tag->count = log($tag->count);
$min = min($min, $tag->count);
$max = max($max, $tag->count);
$tags[$tag->tid] = $tag;
}
// Note: we need to ensure the range is slightly too large to make sure even
// the largest element is rounded down.
$range = max(.01, $max - $min) * 1.0001;
foreach ($tags as $key => $value) {
$tags[$key]->weight = 1 + floor($steps * ($value->count - $min) / $range);
}
```
Then in your view or template:
```
foreach ($tags as $tag) {
$output .= "<h$tag->weight>$tag->name</h$tag->weight>"
}
``` |
231 | <p>How do I make it so <code>mailto:</code> links will be registered with my program?</p>
<p>How would I then handle that event in my program?</p>
<p>Most of the solutions I found from a quick Google search are how to do this manually, but I need to do this automatically for users of my program if they click a button, such as "set as default email client".</p>
<p>#Edit:
Removed reference to Delphi, because the answer is independent of your language.</p>
| [
{
"answer_id": 233,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 4,
"selected": false,
"text": "<p>From what I've seen, there are a few registry keys that set the default mail client. One of them is:</p>\n<p>System Key: <code>[HKEY_CLASSES_ROOT\\mailto\\shell\\open\\command]</code></p>\n<p>Value Name: <code>(Default)</code></p>\n<p>Data Type: <code>REG_SZ</code> (String Value)</p>\n<p>Value Data: <code>Mail program command-line</code>.</p>\n<p>I'm not familiar with <code>Delphi 7</code>, but I'm sure there are some <em>registry editing libraries</em> there that you could use to modify this value.</p>\n<p>Some places list more than this <em>key</em>, others just this key, so you may need to test a little bit to find the proper one(s).</p>\n"
},
{
"answer_id": 1812,
"author": "Liron Yahdav",
"author_id": 62,
"author_profile": "https://Stackoverflow.com/users/62",
"pm_score": 5,
"selected": true,
"text": "<p><em>@Dillie-O: Your answer put me in the right direction (I should have expected it to just be a registry change) and I got this working. But I'm going to mark this as the answer because I'm going to put some additional information that I found while working on this.</em></p>\n<p>The solution to this question really doesn't depend on what programming language you're using, as long as there's some way to modify Windows registry settings.</p>\n<p>Finally, here's the answer:</p>\n<ul>\n<li>To associate a program with the mailto protocol for <strong>all users</strong> on a computer, change the HKEY_CLASSES_ROOT\\mailto\\shell\\open\\command Default value to:<br />\n"<em>Your program's executable</em>" "%1"</li>\n<li>To <a href=\"http://windowsxp.mvps.org/permail.htm\" rel=\"nofollow noreferrer\">associate a program with the mailto protocol for the <strong>current user</strong></a>, change the HKEY_CURRENT_USER\\Software\\Classes\\mailto\\shell\\open\\command Default value to:<br />\n"<em>Your program's executable</em>" "%1"</li>\n</ul>\n<p>The %1 will be replaced with the entire mailto URL. For example, given the link:</p>\n<pre><code><a href="mailto:user@example.com">Email me</a>\n</code></pre>\n<p>The following will be executed:<br />\n"<em>Your program's executable</em>" "mailto:user@example.com"</p>\n<p>Update (via comment by shellscape):<br />\nAs of Windows 8, this method no longer works as expected. Win8 enforces the following key: HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\URLAssociations\\MAILTO\\UserChoice for which the ProgID of the selected app is hashed and can't be forged. It's a royal PITA.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62/"
] | How do I make it so `mailto:` links will be registered with my program?
How would I then handle that event in my program?
Most of the solutions I found from a quick Google search are how to do this manually, but I need to do this automatically for users of my program if they click a button, such as "set as default email client".
#Edit:
Removed reference to Delphi, because the answer is independent of your language. | *@Dillie-O: Your answer put me in the right direction (I should have expected it to just be a registry change) and I got this working. But I'm going to mark this as the answer because I'm going to put some additional information that I found while working on this.*
The solution to this question really doesn't depend on what programming language you're using, as long as there's some way to modify Windows registry settings.
Finally, here's the answer:
* To associate a program with the mailto protocol for **all users** on a computer, change the HKEY\_CLASSES\_ROOT\mailto\shell\open\command Default value to:
"*Your program's executable*" "%1"
* To [associate a program with the mailto protocol for the **current user**](http://windowsxp.mvps.org/permail.htm), change the HKEY\_CURRENT\_USER\Software\Classes\mailto\shell\open\command Default value to:
"*Your program's executable*" "%1"
The %1 will be replaced with the entire mailto URL. For example, given the link:
```
<a href="mailto:user@example.com">Email me</a>
```
The following will be executed:
"*Your program's executable*" "mailto:user@example.com"
Update (via comment by shellscape):
As of Windows 8, this method no longer works as expected. Win8 enforces the following key: HKEY\_CURRENT\_USER\Software\Microsoft\Windows\Shell\Associations\URLAssociations\MAILTO\UserChoice for which the ProgID of the selected app is hashed and can't be forged. It's a royal PITA. |
234 | <p>MySQL has this incredibly useful yet proprietary <code>REPLACE INTO</code> SQL Command. </p>
<p>Can this easily be emulated in SQL Server 2005?</p>
<p>Starting a new Transaction, doing a <code>Select()</code> and then either <code>UPDATE</code> or <code>INSERT</code> and <code>COMMIT</code> is always a little bit of a pain, especially when doing it in the application and therefore always keeping 2 versions of the statement.</p>
<p>I wonder if there is an easy and <strong>universal</strong> way to implement such a function into SQL Server 2005?</p>
| [
{
"answer_id": 238,
"author": "Karl Seguin",
"author_id": 34,
"author_profile": "https://Stackoverflow.com/users/34",
"pm_score": 4,
"selected": false,
"text": "<p>The functionality you're looking for is traditionally called an UPSERT. Atleast knowing what it's called might help you find what you're looking for.</p>\n\n<p>I don't think SQL Server 2005 has any great ways of doing this. 2008 introduces the MERGE statement that can be used to accomplish this as shown in: <a href=\"http://www.databasejournal.com/features/mssql/article.php/3739131\" rel=\"noreferrer\">http://www.databasejournal.com/features/mssql/article.php/3739131</a> or <a href=\"http://blogs.conchango.com/davidportas/archive/2007/11/14/SQL-Server-2008-MERGE.aspx\" rel=\"noreferrer\">http://blogs.conchango.com/davidportas/archive/2007/11/14/SQL-Server-2008-MERGE.aspx</a></p>\n\n<p>Merge was available in the beta of 2005, but they removed it out in the final release.</p>\n"
},
{
"answer_id": 243,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 4,
"selected": false,
"text": "<p>What the upsert/merge is doing is something to the effect of...</p>\n\n<pre><code>IF EXISTS (SELECT * FROM [Table] WHERE Id = X)\n UPDATE [Table] SET...\nELSE\n INSERT INTO [Table]\n</code></pre>\n\n<p>So hopefully the combination of those articles and this pseudo code can get things moving.</p>\n"
},
{
"answer_id": 12202,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 7,
"selected": true,
"text": "<p>This is something that annoys me about MSSQL (<a href=\"http://bizvprog.blogspot.com/2008/04/annoying-fundamental-flaw-with-sql.html\" rel=\"noreferrer\">rant on my blog</a>). I wish MSSQL supported <code>upsert</code>. </p>\n\n<p>@Dillie-O's code is a good way in older SQL versions (+1 vote), but it still is basically two IO operations (the <code>exists</code> and then the <code>update</code> or <code>insert</code>)</p>\n\n<p>There's a slightly better way on <a href=\"https://stackoverflow.com/questions/13540/insert-update-stored-proc-on-sql-server\">this post</a>, basically:</p>\n\n<pre><code>--try an update\nupdate tablename \nset field1 = 'new value',\n field2 = 'different value',\n ...\nwhere idfield = 7\n\n--insert if failed\nif @@rowcount = 0 and @@error = 0\n insert into tablename \n ( idfield, field1, field2, ... )\n values ( 7, 'value one', 'another value', ... )\n</code></pre>\n\n<p>This reduces it to one IO operations if it's an update, or two if an insert. </p>\n\n<p>MS Sql2008 introduces <code>merge</code> from the SQL:2003 standard:</p>\n\n<pre><code>merge tablename as target\nusing (values ('new value', 'different value'))\n as source (field1, field2)\n on target.idfield = 7\nwhen matched then\n update\n set field1 = source.field1,\n field2 = source.field2,\n ...\nwhen not matched then\n insert ( idfield, field1, field2, ... )\n values ( 7, source.field1, source.field2, ... )\n</code></pre>\n\n<p>Now it's really just one IO operation, but awful code :-(</p>\n"
},
{
"answer_id": 112313,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 3,
"selected": false,
"text": "<p>I wrote a <a href=\"http://www.samsaffron.com/blog/archive/2007/04/04/14.aspx\" rel=\"nofollow noreferrer\">blog post</a> about this issue.</p>\n<p>The bottom line is that if you want cheap updates and want to be safe for concurrent usage, try:</p>\n<pre><code>update t\nset hitCount = hitCount + 1\nwhere pk = @id\n\nif @@rowcount < 1 \nbegin \n begin tran\n update t with (serializable)\n set hitCount = hitCount + 1\n where pk = @id\n if @@rowcount = 0\n begin\n insert t (pk, hitCount)\n values (@id,1)\n end\n commit tran\nend\n</code></pre>\n<p>This way you have 1 operation for updates and a max of 3 operations for inserts. So, if you are generally updating, this is a safe cheap option.</p>\n<p>I would also be very careful not to use anything that is unsafe for concurrent usage. It's really easy to get primary key violations or duplicate rows in production.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | MySQL has this incredibly useful yet proprietary `REPLACE INTO` SQL Command.
Can this easily be emulated in SQL Server 2005?
Starting a new Transaction, doing a `Select()` and then either `UPDATE` or `INSERT` and `COMMIT` is always a little bit of a pain, especially when doing it in the application and therefore always keeping 2 versions of the statement.
I wonder if there is an easy and **universal** way to implement such a function into SQL Server 2005? | This is something that annoys me about MSSQL ([rant on my blog](http://bizvprog.blogspot.com/2008/04/annoying-fundamental-flaw-with-sql.html)). I wish MSSQL supported `upsert`.
@Dillie-O's code is a good way in older SQL versions (+1 vote), but it still is basically two IO operations (the `exists` and then the `update` or `insert`)
There's a slightly better way on [this post](https://stackoverflow.com/questions/13540/insert-update-stored-proc-on-sql-server), basically:
```
--try an update
update tablename
set field1 = 'new value',
field2 = 'different value',
...
where idfield = 7
--insert if failed
if @@rowcount = 0 and @@error = 0
insert into tablename
( idfield, field1, field2, ... )
values ( 7, 'value one', 'another value', ... )
```
This reduces it to one IO operations if it's an update, or two if an insert.
MS Sql2008 introduces `merge` from the SQL:2003 standard:
```
merge tablename as target
using (values ('new value', 'different value'))
as source (field1, field2)
on target.idfield = 7
when matched then
update
set field1 = source.field1,
field2 = source.field2,
...
when not matched then
insert ( idfield, field1, field2, ... )
values ( 7, source.field1, source.field2, ... )
```
Now it's really just one IO operation, but awful code :-( |
260 | <p>I have a little game written in C#. It uses a database as back-end. It's
a <a href="http://en.wikipedia.org/wiki/Collectible_card_game" rel="noreferrer">trading card game</a>, and I wanted to implement the function of the cards as a script.</p>
<p>What I mean is that I essentially have an interface, <code>ICard</code>, which a card class implements (<code>public class Card056: ICard</code>) and which contains a function that is called by the game.</p>
<p>Now, to make the thing maintainable/moddable, I would like to have the class for each card as source code in the database and essentially compile it on first use. So when I have to add/change a card, I'll just add it to the database and tell my application to refresh, without needing any assembly deployment (especially since we would be talking about 1 assembly per card which means hundreds of assemblies).</p>
<p>Is that possible? Register a class from a source file and then instantiate it, etc.</p>
<pre><code>ICard Cards[current] = new MyGame.CardLibrary.Card056();
Cards[current].OnEnterPlay(ref currentGameState);
</code></pre>
<p>The language is C# but extra bonus if it's possible to write the script in any .NET language.</p>
| [
{
"answer_id": 269,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, I thought about that, but I soon figured out that another Domain-Specific-Language (DSL) would be a bit too much.</p>\n\n<p>Essentially, they need to interact with my gamestate in possibly unpredictable ways. For example, a card could have a rule \"When this cards enter play, all your undead minions gain +3 attack against flying enemies, except when the enemy is blessed\". As trading card games are turn based, the GameState Manager will fire OnStageX events and let the cards modify other cards or the GameState in whatever way the card needs.</p>\n\n<p>If I try to create a DSL, I have to implement a rather large feature set and possibly constantly update it, which shifts the maintenance work to another part without actually removing it.</p>\n\n<p>That's why I wanted to stay with a \"real\" .NET language to essentially be able to just fire the event and let the card manipulate the gamestate in whatever way (within the limits of the code access security).</p>\n"
},
{
"answer_id": 307,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"https://www.codeproject.com/Articles/8656/C-Script-The-Missing-Puzzle-Piece\" rel=\"nofollow noreferrer\">Oleg Shilo's C# Script solution (at The Code Project</a>) really is a great introduction to providing script abilities in your application.</p>\n\n<p>A different approach would be to consider a language that is specifically built for scripting, such as <a href=\"https://en.wikipedia.org/wiki/IronRuby\" rel=\"nofollow noreferrer\">IronRuby</a>, <a href=\"https://en.wikipedia.org/wiki/IronPython\" rel=\"nofollow noreferrer\">IronPython</a>, or <a href=\"https://en.wikipedia.org/wiki/Lua_%28programming_language%29\" rel=\"nofollow noreferrer\">Lua</a>.</p>\n\n<p>IronPython and IronRuby are both available today.</p>\n\n<p>For a guide to embedding IronPython read\n<a href=\"https://blogs.msdn.microsoft.com/jmstall/2005/09/01/how-to-embed-ironpython-script-support-in-your-existing-app-in-10-easy-steps/\" rel=\"nofollow noreferrer\">How to embed IronPython script support in your existing app in 10 easy steps</a>.</p>\n\n<p>Lua is a scripting language commonly used in games. There is a Lua compiler for .NET, available from CodePlex -- <a href=\"http://www.codeplex.com/Nua\" rel=\"nofollow noreferrer\">http://www.codeplex.com/Nua</a></p>\n\n<p>That codebase is a great read if you want to learn about building a compiler in .NET.</p>\n\n<p>A different angle altogether is to try <a href=\"https://en.wikipedia.org/wiki/PowerShell\" rel=\"nofollow noreferrer\">PowerShell</a>. There are numerous examples of embedding PowerShell into an application -- here's a thorough project on the topic: \n<a href=\"http://code.msdn.microsoft.com/PowerShellTunnel/Wiki/View.aspx?title=PowerShellTunnel%20Reference\" rel=\"nofollow noreferrer\" title=\"PowerShell Tunnel\">Powershell Tunnel</a></p>\n"
},
{
"answer_id": 344,
"author": "Eric Haskins",
"author_id": 100,
"author_profile": "https://Stackoverflow.com/users/100",
"pm_score": 3,
"selected": false,
"text": "<p>You might be able to use IronRuby for that. </p>\n\n<p>Otherwise I'd suggest you have a directory where you place precompiled assemblies. Then you could have a reference in the DB to the assembly and class, and use reflection to load the proper assemblies at runtime.</p>\n\n<p>If you really want to compile at run-time you could use the CodeDOM, then you could use reflection to load the dynamic assembly. <a href=\"https://learn.microsoft.com/dotnet/api/microsoft.csharp.csharpcodeprovider\" rel=\"nofollow noreferrer\">Microsoft documentation article which might help</a>.</p>\n"
},
{
"answer_id": 359,
"author": "Jesse Ezell",
"author_id": 119,
"author_profile": "https://Stackoverflow.com/users/119",
"pm_score": 3,
"selected": false,
"text": "<p>You could use any of the DLR languages, which provide a way to really easily host your own scripting platform. However, you don't have to use a scripting language for this. You could use C# and compile it with the C# code provider. As long as you load it in its own AppDomain, you can load and unload it to your heart's content.</p>\n"
},
{
"answer_id": 3637,
"author": "Nathan",
"author_id": 541,
"author_profile": "https://Stackoverflow.com/users/541",
"pm_score": 3,
"selected": false,
"text": "<p>If you don't want to use the DLR you can <a href=\"http://docs.codehaus.org/display/BOO/Boo+as+an+embedded+scripting+language\" rel=\"nofollow noreferrer\">use Boo (which has an interpreter)</a> or you could consider <a href=\"https://archive.codeplex.com/?p=scriptdotnet\" rel=\"nofollow noreferrer\">the Script.NET (S#) project on CodePlex</a>. With the Boo solution you can choose between compiled scripts or using the interpreter, and Boo makes a nice scripting language, has a flexible syntax and an extensible language via its open compiler architecture. Script.NET looks nice too, though, and you could easily extend that language as well as its an open source project and uses a very friendly Compiler Generator (<a href=\"https://github.com/IronyProject/\" rel=\"nofollow noreferrer\">Irony.net</a>).</p>\n"
},
{
"answer_id": 7217,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p>The main application that my division sells does something very similar to provide client customisations (which means that I can't post any source). We have a C# application that loads dynamic VB.NET scripts (although any .NET language could be easily supported - VB was chosen because the customisation team came from an ASP background).</p>\n\n<p>Using .NET's CodeDom we compile the scripts from the database, using the VB <code>CodeDomProvider</code> (annoyingly it defaults to .NET 2, if you want to support 3.5 features you need to pass a dictionary with \"CompilerVersion\" = \"v3.5\" to its constructor). Use the <code>CodeDomProvider.CompileAssemblyFromSource</code> method to compile it (you can pass settings to force it to compile in memory only.</p>\n\n<p>This would result in hundreds of assemblies in memory, but you could put all the dynamic classes' code together into a single assembly, and recompile the whole lot when any change. This has the advantage that you could add a flag to compile on disk with a <a href=\"http://en.wikipedia.org/wiki/Program_database\" rel=\"nofollow noreferrer\">PDB</a> for when you're testing, allowing you to debug through the dynamic code.</p>\n"
},
{
"answer_id": 79013,
"author": "harningt",
"author_id": 12713,
"author_profile": "https://Stackoverflow.com/users/12713",
"pm_score": 3,
"selected": false,
"text": "<p>I'd suggest using <a href=\"http://luaforge.net/projects/luainterface/\" rel=\"noreferrer\">LuaInterface</a> as it has fully implemented Lua where it appears that Nua is not complete and likely does not implement some very useful functionality (coroutines, etc).</p>\n\n<p>If you want to use some of the outside prepacked Lua modules, I'd suggest using something along the lines of 1.5.x as opposed to the 2.x series that builds fully managed code and cannot expose the necessary C API.</p>\n"
},
{
"answer_id": 4289753,
"author": "Eric Falsken",
"author_id": 192536,
"author_profile": "https://Stackoverflow.com/users/192536",
"pm_score": 2,
"selected": false,
"text": "<p>The next version of .NET (5.0?) has had a lot of talk about opening the \"compiler as a service\" which would make things like direct script evaluation possible.</p>\n"
},
{
"answer_id": 11527418,
"author": "Kat Lim Ruiz",
"author_id": 915865,
"author_profile": "https://Stackoverflow.com/users/915865",
"pm_score": 3,
"selected": false,
"text": "<p>I'm using LuaInterface1.3 + Lua 5.0 for a NET 1.1 application.</p>\n\n<p>The issue with Boo is that every time you parse/compile/eval your code on the fly, it creates a set of boo classes so you will get memory leaks.</p>\n\n<p>Lua in the other hand, does not do that, so it's very very stable and works wonderful (I can pass objects from C# to Lua and backwards).</p>\n\n<p>So far I haven't put it in PROD yet, but seems very promising.</p>\n\n<p><strong>I did have memory leaks issues in PROD using LuaInterface + Lua 5.0</strong>, therefore I used Lua 5.2 and linked directly into C# with DllImport. <strong>The memory leaks were inside the LuaInterface library.</strong></p>\n\n<p>Lua 5.2: from <a href=\"http://luabinaries.sourceforge.net\" rel=\"nofollow noreferrer\">http://luabinaries.sourceforge.net</a> and <a href=\"http://sourceforge.net/projects/luabinaries/files/5.2/Windows%20Libraries/Dynamic/lua-5.2_Win32_dll7_lib.zip/download\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/luabinaries/files/5.2/Windows%20Libraries/Dynamic/lua-5.2_Win32_dll7_lib.zip/download</a></p>\n\n<p>Once I did this, all my memory leaks were gone and the application was very stable.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | I have a little game written in C#. It uses a database as back-end. It's
a [trading card game](http://en.wikipedia.org/wiki/Collectible_card_game), and I wanted to implement the function of the cards as a script.
What I mean is that I essentially have an interface, `ICard`, which a card class implements (`public class Card056: ICard`) and which contains a function that is called by the game.
Now, to make the thing maintainable/moddable, I would like to have the class for each card as source code in the database and essentially compile it on first use. So when I have to add/change a card, I'll just add it to the database and tell my application to refresh, without needing any assembly deployment (especially since we would be talking about 1 assembly per card which means hundreds of assemblies).
Is that possible? Register a class from a source file and then instantiate it, etc.
```
ICard Cards[current] = new MyGame.CardLibrary.Card056();
Cards[current].OnEnterPlay(ref currentGameState);
```
The language is C# but extra bonus if it's possible to write the script in any .NET language. | [Oleg Shilo's C# Script solution (at The Code Project](https://www.codeproject.com/Articles/8656/C-Script-The-Missing-Puzzle-Piece)) really is a great introduction to providing script abilities in your application.
A different approach would be to consider a language that is specifically built for scripting, such as [IronRuby](https://en.wikipedia.org/wiki/IronRuby), [IronPython](https://en.wikipedia.org/wiki/IronPython), or [Lua](https://en.wikipedia.org/wiki/Lua_%28programming_language%29).
IronPython and IronRuby are both available today.
For a guide to embedding IronPython read
[How to embed IronPython script support in your existing app in 10 easy steps](https://blogs.msdn.microsoft.com/jmstall/2005/09/01/how-to-embed-ironpython-script-support-in-your-existing-app-in-10-easy-steps/).
Lua is a scripting language commonly used in games. There is a Lua compiler for .NET, available from CodePlex -- <http://www.codeplex.com/Nua>
That codebase is a great read if you want to learn about building a compiler in .NET.
A different angle altogether is to try [PowerShell](https://en.wikipedia.org/wiki/PowerShell). There are numerous examples of embedding PowerShell into an application -- here's a thorough project on the topic:
[Powershell Tunnel](http://code.msdn.microsoft.com/PowerShellTunnel/Wiki/View.aspx?title=PowerShellTunnel%20Reference "PowerShell Tunnel") |
263 | <p>I have been trying to implement Win32's <code>MessageBox</code> using GTK. The app uses SDL/OpenGL, so this isn't a GTK app.</p>
<p>I handle the initialization (<code>gtk_init</code>) sort of stuff inside the <code>MessageBox</code> function as follows:</p>
<pre><code>int MessageBox(HWND hwnd, const char* text, const char* caption, UINT type)
{
GtkWidget *window = NULL;
GtkWidget *dialog = NULL;
gtk_init(&gtkArgc, &gtkArgv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(delete_event), NULL);
g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy), NULL);
// gcallback calls gtk_main_quit()
gtk_init_add((GtkFunction)gcallback, NULL);
if (type & MB_YESNO) {
dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, text);
} else {
dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, text);
}
gtk_window_set_title(GTK_WINDOW(dialog), caption);
gint result = gtk_dialog_run(GTK_DIALOG(dialog));
gtk_main();
gtk_widget_destroy(dialog);
if (type & MB_YESNO) {
switch (result) {
default:
case GTK_RESPONSE_DELETE_EVENT:
case GTK_RESPONSE_NO:
return IDNO;
break;
case GTK_RESPONSE_YES:
return IDYES;
break;
}
}
return IDOK;
}
</code></pre>
<p>Now, I am by no means an experienced GTK programmer, and I realize that I'm probably doing something horribly wrong.</p>
<p>However, my problem is that the last dialog popped up with this function staying around until the process exits. Any ideas?</p>
| [
{
"answer_id": 537,
"author": "Joe Shaw",
"author_id": 156,
"author_profile": "https://Stackoverflow.com/users/156",
"pm_score": 3,
"selected": false,
"text": "<p>A few things:</p>\n\n<p>You are creating (and not using) an unnecessary toplevel window, named <code>window</code>. You can just delete these lines:</p>\n\n<pre><code>window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\ng_signal_connect(G_OBJECT(window), \"delete_event\", G_CALLBACK(delete_event), NULL);\ng_signal_connect(G_OBJECT(window), \"destroy\", G_CALLBACK(destroy), NULL);\n</code></pre>\n\n<p>Also, the flow doesn't seem quite right. <code>gtk_main()</code> starts the GTK main loop, which blocks until something exits it. <code>gtk_dialog_run()</code> also starts a main loop, but it exits as soon as one of the buttons is clicked.</p>\n\n<p>I think it might be enough for you to remove the <code>gtk_init_add()</code> and <code>gtk_main()</code> calls, and simply deal with the return value. Also the <code>gtk_widget_destroy()</code> call is unnecessary, as the dialog window is automatically destroyed when gtk_dialog_run() returns.</p>\n"
},
{
"answer_id": 607,
"author": "Joe Shaw",
"author_id": 156,
"author_profile": "https://Stackoverflow.com/users/156",
"pm_score": 5,
"selected": true,
"text": "<p>Hmm, ok. I'd suggest code like this, then:</p>\n<pre class=\"lang-c prettyprint-override\"><code>typedef struct {\n int type;\n int result;\n} DialogData;\n \nstatic gboolean\ndisplay_dialog(gpointer user_data)\n{\n DialogData *dialog_data = user_data;\n GtkWidget *dialog;\n \n if (dialog_data->type & MB_YESNO)\n dialog = gtk_message_dialog_new(...);\n else\n dialog = gtk_message_dialog_new(...);\n \n // Set title, etc.\n \n dialog_data->result = gtk_dialog_run(...);\n \n gtk_main_quit(); // Quits the main loop run in MessageBox()\n \n return FALSE;\n}\n \nint MessageBox(...)\n{\n DialogData dialog_data;\n \n dialog_data.type = type;\n \n gtk_idle_add(display_dialog, &dialog_data);\n \n gtk_main();\n \n // Do stuff based on dialog_data.result\n}\n</code></pre>\n<p>The struct is required because you need to pass around a couple pieces of data. The <code>gtk_idle_add()</code> call adds a method to be run when the main loop is running and idle, and the <code>FALSE</code> return value from the <code>display_dialog()</code> call means that it's only run once. After we get the result from the dialog, we quit the main loop. That'll cause the <code>gtk_main()</code> in your main <code>MessageBox()</code> method to return, and you'll be able to access the result from there.</p>\n"
},
{
"answer_id": 2959398,
"author": "Platypus",
"author_id": 356325,
"author_profile": "https://Stackoverflow.com/users/356325",
"pm_score": 3,
"selected": false,
"text": "<p>To manage a dialog box with GTK+, use a GtkDialog and <a href=\"http://library.gnome.org/devel/gtk/stable/GtkDialog.html#gtk-dialog-run\" rel=\"noreferrer\">gtk_dialog_run()</a> instead of managing a window and a main loop by yourself.</p>\n\n<p><strong>EDIT / ADDENDUM :</strong></p>\n\n<p>What I mean is \"just use\" : I don't understand why you create a windows you never use and a main loop which seems useless (at least from the piece of code you posted). You can write something as short as :</p>\n\n<pre><code>int MessageBox(HWND hwnd, const char* text, const char* caption, UINT type)\n{\n GtkWidget *dialog ;\n\n /* Instead of 0, use GTK_DIALOG_MODAL to get a modal dialog box */\n\n if (type & MB_YESNO)\n dialog = gtk_message_dialog_new(NULL, 0, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, text );\n else\n dialog = gtk_message_dialog_new(NULL, 0, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, text );\n\n\n gtk_window_set_title(GTK_WINDOW(dialog), caption);\n gint result = gtk_dialog_run(GTK_DIALOG(dialog));\n gtk_widget_destroy( GTK_WIDGET(dialog) );\n\n if (type & MB_YESNO)\n {\n switch (result)\n {\n default:\n case GTK_RESPONSE_DELETE_EVENT:\n case GTK_RESPONSE_NO:\n return IDNO;\n case GTK_RESPONSE_YES:\n return IDYES;\n }\n return IDOK;\n } \n}\n</code></pre>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | I have been trying to implement Win32's `MessageBox` using GTK. The app uses SDL/OpenGL, so this isn't a GTK app.
I handle the initialization (`gtk_init`) sort of stuff inside the `MessageBox` function as follows:
```
int MessageBox(HWND hwnd, const char* text, const char* caption, UINT type)
{
GtkWidget *window = NULL;
GtkWidget *dialog = NULL;
gtk_init(>kArgc, >kArgv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(delete_event), NULL);
g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy), NULL);
// gcallback calls gtk_main_quit()
gtk_init_add((GtkFunction)gcallback, NULL);
if (type & MB_YESNO) {
dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, text);
} else {
dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, text);
}
gtk_window_set_title(GTK_WINDOW(dialog), caption);
gint result = gtk_dialog_run(GTK_DIALOG(dialog));
gtk_main();
gtk_widget_destroy(dialog);
if (type & MB_YESNO) {
switch (result) {
default:
case GTK_RESPONSE_DELETE_EVENT:
case GTK_RESPONSE_NO:
return IDNO;
break;
case GTK_RESPONSE_YES:
return IDYES;
break;
}
}
return IDOK;
}
```
Now, I am by no means an experienced GTK programmer, and I realize that I'm probably doing something horribly wrong.
However, my problem is that the last dialog popped up with this function staying around until the process exits. Any ideas? | Hmm, ok. I'd suggest code like this, then:
```c
typedef struct {
int type;
int result;
} DialogData;
static gboolean
display_dialog(gpointer user_data)
{
DialogData *dialog_data = user_data;
GtkWidget *dialog;
if (dialog_data->type & MB_YESNO)
dialog = gtk_message_dialog_new(...);
else
dialog = gtk_message_dialog_new(...);
// Set title, etc.
dialog_data->result = gtk_dialog_run(...);
gtk_main_quit(); // Quits the main loop run in MessageBox()
return FALSE;
}
int MessageBox(...)
{
DialogData dialog_data;
dialog_data.type = type;
gtk_idle_add(display_dialog, &dialog_data);
gtk_main();
// Do stuff based on dialog_data.result
}
```
The struct is required because you need to pass around a couple pieces of data. The `gtk_idle_add()` call adds a method to be run when the main loop is running and idle, and the `FALSE` return value from the `display_dialog()` call means that it's only run once. After we get the result from the dialog, we quit the main loop. That'll cause the `gtk_main()` in your main `MessageBox()` method to return, and you'll be able to access the result from there. |
265 | <p>What are the best practices for checking in BIN directories in a collaborative development environment using SVN? Should project level references be excluded from checkin? Is it easier to just add all bin directories?</p>
<p>I develop a lot of DotNetNuke sites and it seems that in a multi-developer environment, it's always a huge task to get the environment setup correctly.</p>
<p>The ultimate goal (of course) is to have a new developer checkout the trunk from SVN, restore the DNN database and have it all just 'work'...</p>
| [
{
"answer_id": 266,
"author": "Karl Seguin",
"author_id": 34,
"author_profile": "https://Stackoverflow.com/users/34",
"pm_score": 5,
"selected": true,
"text": "<p>Any assemblies that are expected to be in the GAC should stay in the GAC. This includes System.web.dll or any other 3rd party dll that you'll deploy to the GAC in production. This means a new developer would have to install these assemblies.</p>\n\n<p>All other 3rd party assemblies should be references through a relative path. My typical structure is:</p>\n\n<pre><code>-Project\n--Project.sln\n--References\n---StructureMap.dll\n---NUnit.dll\n---System.Web.Mvc.dll\n--Project.Web\n---Project.Web.Proj\n---Project.Web.Proj files\n--Project\n---Project.Proj\n---Project.Proj files\n</code></pre>\n\n<p>Project.Web and Project reference the assemblies in the root/References folder relatively. These .dlls are checked into subversion.</p>\n\n<p>Aside from that, */bin */bin/* obj should be in your global ignore path.</p>\n\n<p>With this setup, all references to assemblies are either through the GAC (so should work across all computers), or relative to each project within your solution.</p>\n"
},
{
"answer_id": 268,
"author": "Peter Burns",
"author_id": 101,
"author_profile": "https://Stackoverflow.com/users/101",
"pm_score": 2,
"selected": false,
"text": "<p>Is this a .Net specific question?</p>\n\n<p>Generally the best practice is to not check in anything which is built automatically from files that are already in SCM. All of that is ideally created as part of your automatic build process.</p>\n\n<p>If the <code>bin</code> directory you're referring to contains third-party binaries, rather than a build of your project, ignore (downvote?) this advice.</p>\n"
},
{
"answer_id": 532,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 2,
"selected": false,
"text": "<p>Maven helps quite a lot with this problem when I'm coding java. We commit the pom.xml to the scs and the maven repository contains all our dependencies.\nFor me that seems like a nice way to do it.</p>\n"
},
{
"answer_id": 10428,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 1,
"selected": false,
"text": "<p>We follow the practice of using a vendor directory which contains all vendor specific headers and binaries. The goal is that anybody should be able to build the product just by checking it out and running some top level build script. </p>\n"
},
{
"answer_id": 56480,
"author": "LaptopHeaven",
"author_id": 1296,
"author_profile": "https://Stackoverflow.com/users/1296",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.codeplex.com/treesurgeon\" rel=\"nofollow noreferrer\">Tree Surgeon</a> is a great tool which creates an empty .NET development tree. It has been tweaked over years of use and implements lots of best practices.</p>\n"
}
] | 2008/08/01 | [
"https://Stackoverflow.com/questions/265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105/"
] | What are the best practices for checking in BIN directories in a collaborative development environment using SVN? Should project level references be excluded from checkin? Is it easier to just add all bin directories?
I develop a lot of DotNetNuke sites and it seems that in a multi-developer environment, it's always a huge task to get the environment setup correctly.
The ultimate goal (of course) is to have a new developer checkout the trunk from SVN, restore the DNN database and have it all just 'work'... | Any assemblies that are expected to be in the GAC should stay in the GAC. This includes System.web.dll or any other 3rd party dll that you'll deploy to the GAC in production. This means a new developer would have to install these assemblies.
All other 3rd party assemblies should be references through a relative path. My typical structure is:
```
-Project
--Project.sln
--References
---StructureMap.dll
---NUnit.dll
---System.Web.Mvc.dll
--Project.Web
---Project.Web.Proj
---Project.Web.Proj files
--Project
---Project.Proj
---Project.Proj files
```
Project.Web and Project reference the assemblies in the root/References folder relatively. These .dlls are checked into subversion.
Aside from that, \*/bin \*/bin/\* obj should be in your global ignore path.
With this setup, all references to assemblies are either through the GAC (so should work across all computers), or relative to each project within your solution. |
289 | <p>I often have to sort a dictionary (consisting of keys & values) by value. For example, I have a hash of words and respective frequencies that I want to order by frequency.</p>
<p>There is a <code>SortedList</code> which is good for a single value (say frequency), that I want to map back to the word.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/f7fta44c.aspx" rel="noreferrer">SortedDictionary</a> orders by key, not value. Some resort to a <a href="http://www.codeproject.com/KB/recipes/lookupcollection.aspx" rel="noreferrer">custom class</a>, but is there a cleaner way?</p>
| [
{
"answer_id": 291,
"author": "Kalid",
"author_id": 109,
"author_profile": "https://Stackoverflow.com/users/109",
"pm_score": 7,
"selected": false,
"text": "<p>Looking around, and using some C# 3.0 features we can do this:</p>\n\n<pre><code>foreach (KeyValuePair<string,int> item in keywordCounts.OrderBy(key=> key.Value))\n{ \n // do something with item.Key and item.Value\n}\n</code></pre>\n\n<p>This is the cleanest way I've seen and is similar to the Ruby way of handling hashes.</p>\n"
},
{
"answer_id": 292,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 6,
"selected": false,
"text": "<p>On a high level, you have no other choice than to walk through the whole Dictionary and look at each value.</p>\n\n<p>Maybe this helps:\n<a href=\"http://bytes.com/forum/thread563638.html\" rel=\"noreferrer\">http://bytes.com/forum/thread563638.html</a>\nCopy/Pasting from John Timney:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Dictionary<string, string> s = new Dictionary<string, string>();\ns.Add(\"1\", \"a Item\");\ns.Add(\"2\", \"c Item\");\ns.Add(\"3\", \"b Item\");\n\nList<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(s);\nmyList.Sort(\n delegate(KeyValuePair<string, string> firstPair,\n KeyValuePair<string, string> nextPair)\n {\n return firstPair.Value.CompareTo(nextPair.Value);\n }\n);\n</code></pre>\n"
},
{
"answer_id": 298,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 10,
"selected": true,
"text": "<p>Use:</p>\n\n<pre><code>using System.Linq.Enumerable;\n...\nList<KeyValuePair<string, string>> myList = aDictionary.ToList();\n\nmyList.Sort(\n delegate(KeyValuePair<string, string> pair1,\n KeyValuePair<string, string> pair2)\n {\n return pair1.Value.CompareTo(pair2.Value);\n }\n);\n</code></pre>\n\n<p>Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above).</p>\n\n<pre><code>var myList = aDictionary.ToList();\n\nmyList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));\n</code></pre>\n"
},
{
"answer_id": 1332,
"author": "caryden",
"author_id": 313,
"author_profile": "https://Stackoverflow.com/users/313",
"pm_score": 9,
"selected": false,
"text": "<p>Use LINQ:</p>\n\n<pre><code>Dictionary<string, int> myDict = new Dictionary<string, int>();\nmyDict.Add(\"one\", 1);\nmyDict.Add(\"four\", 4);\nmyDict.Add(\"two\", 2);\nmyDict.Add(\"three\", 3);\n\nvar sortedDict = from entry in myDict orderby entry.Value ascending select entry;\n</code></pre>\n\n<p>This would also allow for great flexibility in that you can select the top 10, 20 10%, etc. Or if you are using your word frequency index for <code>type-ahead</code>, you could also include <code>StartsWith</code> clause as well.</p>\n"
},
{
"answer_id": 382462,
"author": "Roger Willcocks",
"author_id": 11511,
"author_profile": "https://Stackoverflow.com/users/11511",
"pm_score": 5,
"selected": false,
"text": "<p>You'd never be able to sort a dictionary anyway. They are not actually ordered. The guarantees for a dictionary are that the key and value collections are iterable, and values can be retrieved by index or key, but there is no guarantee of any particular order. Hence you would need to get the name value pair into a list.</p>\n"
},
{
"answer_id": 2569558,
"author": "Alex Ruiz",
"author_id": 308018,
"author_profile": "https://Stackoverflow.com/users/308018",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way to get a sorted Dictionary is to use the built in <code>SortedDictionary</code> class:</p>\n<pre><code>//Sorts sections according to the key value stored on "sections" unsorted dictionary, which is passed as a constructor argument\nSystem.Collections.Generic.SortedDictionary<int, string> sortedSections = null;\nif (sections != null)\n{\n sortedSections = new SortedDictionary<int, string>(sections);\n}\n</code></pre>\n<p><code>sortedSections</code> will contain the sorted version of <code>sections</code></p>\n"
},
{
"answer_id": 2697521,
"author": "BSalita",
"author_id": 317797,
"author_profile": "https://Stackoverflow.com/users/317797",
"pm_score": 3,
"selected": false,
"text": "<p>Sorting a <code>SortedDictionary</code> list to bind into a <code>ListView</code> control using VB.NET:</p>\n\n<pre><code>Dim MyDictionary As SortedDictionary(Of String, MyDictionaryEntry)\n\nMyDictionaryListView.ItemsSource = MyDictionary.Values.OrderByDescending(Function(entry) entry.MyValue)\n\nPublic Class MyDictionaryEntry ' Need Property for GridViewColumn DisplayMemberBinding\n Public Property MyString As String\n Public Property MyValue As Integer\nEnd Class\n</code></pre>\n\n<p>XAML:</p>\n\n<pre><code><ListView Name=\"MyDictionaryListView\">\n <ListView.View>\n <GridView>\n <GridViewColumn DisplayMemberBinding=\"{Binding Path=MyString}\" Header=\"MyStringColumnName\"></GridViewColumn>\n <GridViewColumn DisplayMemberBinding=\"{Binding Path=MyValue}\" Header=\"MyValueColumnName\"></GridViewColumn>\n </GridView>\n </ListView.View>\n</ListView>\n</code></pre>\n"
},
{
"answer_id": 3148631,
"author": "mythz",
"author_id": 85785,
"author_profile": "https://Stackoverflow.com/users/85785",
"pm_score": 4,
"selected": false,
"text": "<p>Or for fun you could use some LINQ extension goodness:</p>\n\n<pre><code>var dictionary = new Dictionary<string, int> { { \"c\", 3 }, { \"a\", 1 }, { \"b\", 2 } };\ndictionary.OrderBy(x => x.Value)\n .ForEach(x => Console.WriteLine(\"{0}={1}\", x.Key,x.Value));\n</code></pre>\n"
},
{
"answer_id": 4157151,
"author": "sean",
"author_id": 82371,
"author_profile": "https://Stackoverflow.com/users/82371",
"pm_score": 8,
"selected": false,
"text": "<p>You could use:</p>\n<pre><code>var ordered = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);\n</code></pre>\n"
},
{
"answer_id": 6438343,
"author": "Matt Frear",
"author_id": 32598,
"author_profile": "https://Stackoverflow.com/users/32598",
"pm_score": 7,
"selected": false,
"text": "<p>You can sort a Dictionary by value and save it back to itself (so that when you foreach over it the values come out in order):</p>\n<pre><code>dict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);\n</code></pre>\n<p>Sure, it may not be correct, but it works. <a href=\"https://www.hyrumslaw.com/\" rel=\"noreferrer\">Hyrum's Law</a> means that this will very likely continue to work.</p>\n"
},
{
"answer_id": 11630804,
"author": "pawan Kumar",
"author_id": 1548685,
"author_profile": "https://Stackoverflow.com/users/1548685",
"pm_score": -1,
"selected": false,
"text": "<p>You can sort the Dictionary by value and get the result in dictionary using the code below:</p>\n\n<pre><code>Dictionary <<string, string>> ShareUserNewCopy = \n ShareUserCopy.OrderBy(x => x.Value).ToDictionary(pair => pair.Key,\n pair => pair.Value); \n</code></pre>\n"
},
{
"answer_id": 13854099,
"author": "Zar Shardan",
"author_id": 913845,
"author_profile": "https://Stackoverflow.com/users/913845",
"pm_score": 5,
"selected": false,
"text": "<p>You do not sort entries in the Dictionary. Dictionary class in .NET is implemented as a hashtable - this data structure is not sortable by definition.</p>\n\n<p>If you need to be able to iterate over your collection (by key) - you need to use SortedDictionary, which is implemented as a Binary Search Tree.</p>\n\n<p>In your case, however the source structure is irrelevant, because it is sorted by a different field. You would still need to sort it by frequency and put it in a new collection sorted by the relevant field (frequency). So in this collection the frequencies are keys and words are values. Since many words can have the same frequency (and you are going to use it as a key) you cannot use neither Dictionary nor SortedDictionary (they require unique keys). This leaves you with a SortedList.</p>\n\n<p>I don't understand why you insist on maintaining a link to the original item in your main/first dictionary. </p>\n\n<p>If the objects in your collection had a more complex structure (more fields) and you needed to be able to efficiently access/sort them using several different fields as keys - You would probably need a custom data structure that would consist of the main storage that supports O(1) insertion and removal (LinkedList) and several indexing structures - Dictionaries/SortedDictionaries/SortedLists. These indexes would use one of the fields from your complex class as a key and a pointer/reference to the LinkedListNode in the LinkedList as a value.</p>\n\n<p>You would need to coordinate insertions and removals to keep your indexes in sync with the main collection (LinkedList) and removals would be pretty expensive I'd think.\nThis is similar to how database indexes work - they are fantastic for lookups but they become a burden when you need to perform many insetions and deletions.</p>\n\n<p>All of the above is only justified if you are going to do some look-up heavy processing. If you only need to output them once sorted by frequency then you could just produce a list of (anonymous) tuples:</p>\n\n<pre><code>var dict = new SortedDictionary<string, int>();\n// ToDo: populate dict\n\nvar output = dict.OrderBy(e => e.Value).Select(e => new {frequency = e.Value, word = e.Key}).ToList();\n\nforeach (var entry in output)\n{\n Console.WriteLine(\"frequency:{0}, word: {1}\",entry.frequency,entry.word);\n}\n</code></pre>\n"
},
{
"answer_id": 23975034,
"author": "aggaton",
"author_id": 1575416,
"author_profile": "https://Stackoverflow.com/users/1575416",
"pm_score": -1,
"selected": false,
"text": "<p>Given you have a dictionary you can sort them directly on values using below one liner:</p>\n\n<pre><code>var x = (from c in dict orderby c.Value.Order ascending select c).ToDictionary(c => c.Key, c=>c.Value);\n</code></pre>\n"
},
{
"answer_id": 28275964,
"author": "Akshay Kapoor",
"author_id": 4519513,
"author_profile": "https://Stackoverflow.com/users/4519513",
"pm_score": 2,
"selected": false,
"text": "<p>Suppose we have a dictionary as:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Dictionary<int, int> dict = new Dictionary<int, int>();\ndict.Add(21,1041);\ndict.Add(213, 1021);\ndict.Add(45, 1081);\ndict.Add(54, 1091);\ndict.Add(3425, 1061);\ndict.Add(768, 1011);\n</code></pre>\n<p>You can use temporary dictionary to store values as:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Dictionary<int, int> dctTemp = new Dictionary<int, int>();\nforeach (KeyValuePair<int, int> pair in dict.OrderBy(key => key.Value))\n{\n dctTemp.Add(pair.Key, pair.Value);\n}\n</code></pre>\n"
},
{
"answer_id": 31514791,
"author": "mrfazolka",
"author_id": 3536395,
"author_profile": "https://Stackoverflow.com/users/3536395",
"pm_score": 4,
"selected": false,
"text": "<p>You could use:</p>\n<pre><code>Dictionary<string, string> dic= new Dictionary<string, string>();\nvar ordered = dic.OrderBy(x => x.Value);\nreturn ordered.ToDictionary(t => t.Key, t => t.Value);\n</code></pre>\n"
},
{
"answer_id": 35645695,
"author": "Qwertie",
"author_id": 22820,
"author_profile": "https://Stackoverflow.com/users/22820",
"pm_score": 3,
"selected": false,
"text": "<p>The other answers are good, if all you want is to have a \"temporary\" list sorted by Value. However, if you want to have a dictionary sorted by <code>Key</code> that <em>automatically synchronizes</em> with another dictionary that is sorted by <code>Value</code>, you could use the <a href=\"http://ecsharp.net/doc/code/classLoyc_1_1Collections_1_1Bijection.html\" rel=\"nofollow noreferrer\"><code>Bijection<K1, K2></code> class</a>.</p>\n\n<p><code>Bijection<K1, K2></code> allows you to initialize the collection with two existing dictionaries, so if you want one of them to be unsorted, and you want the other one to be sorted, you could create your bijection with code like</p>\n\n<pre><code>var dict = new Bijection<Key, Value>(new Dictionary<Key,Value>(), \n new SortedDictionary<Value,Key>());\n</code></pre>\n\n<p>You can use <code>dict</code> like any normal dictionary (it implements <code>IDictionary<K, V></code>), and then call <code>dict.Inverse</code> to get the \"inverse\" dictionary which is sorted by <code>Value</code>.</p>\n\n<p><code>Bijection<K1, K2></code> is part of <a href=\"http://core.loyc.net/\" rel=\"nofollow noreferrer\">Loyc.Collections.dll</a>, but if you want, you could simply copy the <a href=\"https://github.com/qwertie/Loyc/blob/master/Core/Loyc.Collections/Other/Bijection.cs\" rel=\"nofollow noreferrer\">source code</a> into your own project.</p>\n\n<p><strong>Note</strong>: In case there are multiple keys with the same value, you can't use <code>Bijection</code>, but you could manually synchronize between an ordinary <code>Dictionary<Key,Value></code> and a <a href=\"http://loyc.net/doc/code/classLoyc_1_1Collections_1_1BMultiMap_3_01K_00_01V_01_4.html\" rel=\"nofollow noreferrer\"><code>BMultiMap<Value,Key></code></a>.</p>\n"
},
{
"answer_id": 54885808,
"author": "Ashish Kamble",
"author_id": 6440372,
"author_profile": "https://Stackoverflow.com/users/6440372",
"pm_score": 3,
"selected": false,
"text": "<p>Actually in C#, dictionaries don't have sort() methods.\nAs you are more interested in sort by values,\nyou can't get values until you provide them key.\nIn short, you need to iterate through them using LINQ's <code>OrderBy()</code>,</p>\n<pre><code>var items = new Dictionary<string, int>();\nitems.Add("cat", 0);\nitems.Add("dog", 20);\nitems.Add("bear", 100);\nitems.Add("lion", 50);\n\n// Call OrderBy() method here on each item and provide them the IDs.\nforeach (var item in items.OrderBy(k => k.Key))\n{\n Console.WriteLine(item);// items are in sorted order\n}\n</code></pre>\n<p>You can do one trick:</p>\n<pre><code>var sortedDictByOrder = items.OrderBy(v => v.Value);\n</code></pre>\n<p>or:</p>\n<pre><code>var sortedKeys = from pair in dictName\n orderby pair.Value ascending\n select pair;\n</code></pre>\n<p>It also depends on what kind of values you are storing: single (like string, int) or multiple (like List, Array, user defined class).\nIf it's single you can make list of it and then apply sort.<br />\nIf it's user defined class, then that class must implement IComparable, <code>ClassName: IComparable<ClassName></code> and override <code>compareTo(ClassName c)</code> as they are more faster and more object oriented than LINQ.</p>\n"
},
{
"answer_id": 61875551,
"author": "Jaydeep Shil",
"author_id": 3428626,
"author_profile": "https://Stackoverflow.com/users/3428626",
"pm_score": 2,
"selected": false,
"text": "<p>Required namespace : <code>using System.Linq;</code></p>\n\n<pre><code>Dictionary<string, int> counts = new Dictionary<string, int>();\ncounts.Add(\"one\", 1);\ncounts.Add(\"four\", 4);\ncounts.Add(\"two\", 2);\ncounts.Add(\"three\", 3);\n</code></pre>\n\n<p>Order by desc :</p>\n\n<pre><code>foreach (KeyValuePair<string, int> kvp in counts.OrderByDescending(key => key.Value))\n{\n// some processing logic for each item if you want.\n}\n</code></pre>\n\n<p>Order by Asc :</p>\n\n<pre><code>foreach (KeyValuePair<string, int> kvp in counts.OrderBy(key => key.Value))\n{\n// some processing logic for each item if you want.\n}\n</code></pre>\n"
},
{
"answer_id": 64841771,
"author": "PeterK",
"author_id": 418332,
"author_profile": "https://Stackoverflow.com/users/418332",
"pm_score": 1,
"selected": false,
"text": "<p>Sort and print:</p>\n<pre><code>var items = from pair in players_Dic\n orderby pair.Value descending\n select pair;\n\n// Display results.\nforeach (KeyValuePair<string, int> pair in items)\n{\n Debug.Log(pair.Key + " - " + pair.Value);\n}\n</code></pre>\n<p>Change descending to acending to change sort order</p>\n"
},
{
"answer_id": 70512839,
"author": "Franz Kurt",
"author_id": 7327114,
"author_profile": "https://Stackoverflow.com/users/7327114",
"pm_score": 0,
"selected": false,
"text": "<p>A dictionary by definition is an unordered associative structure that contains only values and keys in a hashable way. In other words has not a previsible way to orderer a dictionary.</p>\n<p>For reference read this article from python language.</p>\n<p>Link\n<a href=\"https://docs.python.org/3/tutorial/datastructures.html#dictionaries\" rel=\"nofollow noreferrer\">python data structures</a></p>\n"
},
{
"answer_id": 72756303,
"author": "Vineet Agarwal",
"author_id": 7621734,
"author_profile": "https://Stackoverflow.com/users/7621734",
"pm_score": 0,
"selected": false,
"text": "<p>Best way:</p>\n<pre><code>var list = dict.Values.OrderByDescending(x => x).ToList();\nvar sortedData = dict.OrderBy(x => list.IndexOf(x.Value));\n</code></pre>\n"
}
] | 2008/08/02 | [
"https://Stackoverflow.com/questions/289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/109/"
] | I often have to sort a dictionary (consisting of keys & values) by value. For example, I have a hash of words and respective frequencies that I want to order by frequency.
There is a `SortedList` which is good for a single value (say frequency), that I want to map back to the word.
[SortedDictionary](http://msdn.microsoft.com/en-us/library/f7fta44c.aspx) orders by key, not value. Some resort to a [custom class](http://www.codeproject.com/KB/recipes/lookupcollection.aspx), but is there a cleaner way? | Use:
```
using System.Linq.Enumerable;
...
List<KeyValuePair<string, string>> myList = aDictionary.ToList();
myList.Sort(
delegate(KeyValuePair<string, string> pair1,
KeyValuePair<string, string> pair2)
{
return pair1.Value.CompareTo(pair2.Value);
}
);
```
Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above).
```
var myList = aDictionary.ToList();
myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
``` |
336 | <p>When is it appropriate to use an unsigned variable over a signed one? What about in a <code>for</code> loop?</p>
<p>I hear a lot of opinions about this and I wanted to see if there was anything resembling a consensus. </p>
<pre><code>for (unsigned int i = 0; i < someThing.length(); i++) {
SomeThing var = someThing.at(i);
// You get the idea.
}
</code></pre>
<p>I know Java doesn't have unsigned values, and that must have been a concious decision on <a href="https://en.wikipedia.org/wiki/Sun_Microsystems" rel="noreferrer">Sun Microsystems</a>' part. </p>
| [
{
"answer_id": 339,
"author": "saint_groceon",
"author_id": 59,
"author_profile": "https://Stackoverflow.com/users/59",
"pm_score": 7,
"selected": true,
"text": "<p>I was glad to find <a href=\"https://web.archive.org/web/20170323034837/http://coding.derkeiler.com/Archive/C_CPP/comp.lang.c/2004-02/1382.html\" rel=\"noreferrer\">a good conversation</a> on this subject, as I hadn't really given it much thought before.</p>\n<p>In summary, signed is a good general choice - even when you're dead sure all the numbers are positive - if you're going to do arithmetic on the variable (like in a typical for loop case).</p>\n<p>unsigned starts to make more sense when:</p>\n<ul>\n<li>You're going to do <strong>bitwise things</strong> like masks, or</li>\n<li>You're <strong>desperate</strong> to to take advantage of the sign bit <strong>for that extra positive range</strong> .</li>\n</ul>\n<p>Personally, I like signed because I don't trust myself to stay consistent and avoid mixing the two types (like the article warns against).</p>\n"
},
{
"answer_id": 347,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 3,
"selected": false,
"text": "<p>In your example above, when 'i' will always be positive and a higher range would be beneficial, unsigned would be useful. Like if you're using 'declare' statements, such as: </p>\n\n<pre><code>#declare BIT1 (unsigned int 1)\n#declare BIT32 (unsigned int reallybignumber)\n</code></pre>\n\n<p>Especially when these values will never change.</p>\n\n<p>However, if you're doing an accounting program where the people are irresponsible with their money and are constantly in the red, you will most definitely want to use 'signed'.</p>\n\n<p>I do agree with saint though that a good rule of thumb is to use signed, which C actually defaults to, so you're covered.</p>\n"
},
{
"answer_id": 354,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 3,
"selected": false,
"text": "<p><code>size_t</code> is often a good choice for this, or <code>size_type</code> if you're using an STL class.</p>\n"
},
{
"answer_id": 1226,
"author": "Josh",
"author_id": 257,
"author_profile": "https://Stackoverflow.com/users/257",
"pm_score": 3,
"selected": false,
"text": "<p>C and C++ compilers will generate a warning when you compare signed and unsigned types; in your example code, you couldn't make your loop variable unsigned and have the compiler generate code without warnings (assuming said warnings were turned on).</p>\n\n<p>Naturally, you're compiling with warnings turned all the way up, right?</p>\n\n<p>And, have you considered compiling with \"treat warnings as errors\" to take it that one step further?</p>\n\n<p>The downside with using signed numbers is that there's a temptation to overload them so that, for example, the values 0->n are the menu selection, and -1 means nothing's selected - rather than creating a class that has two variables, one to indicate if something is selected and another to store what that selection is. Before you know it, you're testing for negative one all over the place and the compiler is complaining about how you're wanting to compare the menu selection against the number of menu selections you have - but that's dangerous because they're different types. So don't do that.</p>\n"
},
{
"answer_id": 278817,
"author": "Keith Sirmons",
"author_id": 1048,
"author_profile": "https://Stackoverflow.com/users/1048",
"pm_score": 3,
"selected": false,
"text": "<p>I would think that if your business case dictates that a negative number is invalid, you would <em>want</em> to have an error shown or thrown. </p>\n\n<p>With that in mind, I only just recently found out about unsigned integers while working on a project processing data in a binary file and storing the data into a database. I was purposely \"corrupting\" the binary data, and ended up getting negative values instead of an expected error. I found that even though the value converted, the value was not valid for my business case.<br>\nMy program did not error, and I ended up getting wrong data into the database. It would have been better if I had used <code>uint</code> and had the program fail.</p>\n"
}
] | 2008/08/02 | [
"https://Stackoverflow.com/questions/336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | When is it appropriate to use an unsigned variable over a signed one? What about in a `for` loop?
I hear a lot of opinions about this and I wanted to see if there was anything resembling a consensus.
```
for (unsigned int i = 0; i < someThing.length(); i++) {
SomeThing var = someThing.at(i);
// You get the idea.
}
```
I know Java doesn't have unsigned values, and that must have been a concious decision on [Sun Microsystems](https://en.wikipedia.org/wiki/Sun_Microsystems)' part. | I was glad to find [a good conversation](https://web.archive.org/web/20170323034837/http://coding.derkeiler.com/Archive/C_CPP/comp.lang.c/2004-02/1382.html) on this subject, as I hadn't really given it much thought before.
In summary, signed is a good general choice - even when you're dead sure all the numbers are positive - if you're going to do arithmetic on the variable (like in a typical for loop case).
unsigned starts to make more sense when:
* You're going to do **bitwise things** like masks, or
* You're **desperate** to to take advantage of the sign bit **for that extra positive range** .
Personally, I like signed because I don't trust myself to stay consistent and avoid mixing the two types (like the article warns against). |
361 | <p>How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.</p>
<p>Any language would work, but it should be portable.</p>
| [
{
"answer_id": 362,
"author": "alumb",
"author_id": 80,
"author_profile": "https://Stackoverflow.com/users/80",
"pm_score": 7,
"selected": true,
"text": "<p>There are several ways to do this. Common methods use recursion, memoization, or dynamic programming. The basic idea is that you produce a list of all strings of length 1, then in each iteration, for all strings produced in the last iteration, add that string concatenated with each character in the string individually. (the variable index in the code below keeps track of the start of the last and the next iteration)</p>\n\n<p>Some pseudocode:</p>\n\n<pre><code>list = originalString.split('')\nindex = (0,0)\nlist = [\"\"]\nfor iteration n in 1 to y:\n index = (index[1], len(list))\n for string s in list.subset(index[0] to end):\n for character c in originalString:\n list.add(s + c)\n</code></pre>\n\n<p>you'd then need to remove all strings less than x in length, they'll be the first (x-1) * len(originalString) entries in the list.</p>\n"
},
{
"answer_id": 364,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 3,
"selected": false,
"text": "<p>I just whipped this up quick in Ruby:</p>\n\n<pre><code>def perms(x, y, possible_characters)\n all = [\"\"]\n current_array = all.clone\n 1.upto(y) { |iteration|\n next_array = []\n current_array.each { |string|\n possible_characters.each { |c|\n value = string + c\n next_array.insert next_array.length, value\n all.insert all.length, value\n }\n }\n current_array = next_array\n }\n all.delete_if { |string| string.length < x }\nend\n</code></pre>\n\n<p>You might look into language API for built in permutation type functions, and you might be able to write more optimized code, but if the numbers are all that high, I'm not sure there is much of a way around having a lot of results.</p>\n\n<p>Anyways, the idea behind the code is start with string of length 0, then keep track of all the strings of length Z where Z is the current size in the iteration. Then, go through each string and append each character onto each string. Finally at the end, remove any that were below the x threshold and return the result.</p>\n\n<p>I didn't test it with potentially meaningless input (null character list, weird values of x and y, etc).</p>\n"
},
{
"answer_id": 388,
"author": "Brian Willis",
"author_id": 118,
"author_profile": "https://Stackoverflow.com/users/118",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure why you would want to do this in the first place. The resulting set for any moderately large values of x and y will be huge, and will grow exponentially as x and/or y get bigger. </p>\n\n<p>Lets say your set of possible characters is the 26 lowercase letters of the alphabet, and you ask your application to generate all permutations where length = 5. Assuming you don't run out of memory you'll get 11,881,376 (i.e. 26 to the power of 5) strings back. Bump that length up to 6, and you'll get 308,915,776 strings back. These numbers get painfully large, very quickly.</p>\n\n<p>Here's a solution I put together in Java. You'll need to provide two runtime arguments (corresponding to x and y). Have fun.</p>\n\n<pre><code>public class GeneratePermutations {\n public static void main(String[] args) {\n int lower = Integer.parseInt(args[0]);\n int upper = Integer.parseInt(args[1]);\n\n if (upper < lower || upper == 0 || lower == 0) {\n System.exit(0);\n }\n\n for (int length = lower; length <= upper; length++) {\n generate(length, \"\");\n }\n }\n\n private static void generate(int length, String partial) {\n if (length <= 0) {\n System.out.println(partial);\n } else {\n for (char c = 'a'; c <= 'z'; c++) {\n generate(length - 1, partial + c);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1910,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 5,
"selected": false,
"text": "<p>You are going to get a lot of strings, that's for sure...</p>\n\n<p><img src=\"https://www.codecogs.com/eq.latex?%5Csum_%7Bi=x%7D%5Ey%20%7B%20%5Cfrac%7Br!%7D%7B%7B(r-i)%7D!%7D%20%7D\" alt=\"\\sum_{i=x}^y{\\frac{r!}{{(r-i)}!}}\"><br>\nWhere x and y is how you define them and r is the number of characters we are selecting from --if I am understanding you correctly. You should definitely generate these as needed and not get sloppy and say, generate a powerset and then filter the length of strings.</p>\n\n<p>The following definitely isn't the best way to generate these, but it's an interesting aside, none-the-less.</p>\n\n<p>Knuth (volume 4, fascicle 2, 7.2.1.3) tells us that (s,t)-combination is equivalent to s+1 things taken t at a time with repetition -- an (s,t)-combination is notation used by Knuth that is equal to <img src=\"https://www.codecogs.com/eq.latex?%7Bt%20%5Cchoose%20%7Bs+t%7D%7D\" alt=\"{t \\choose {s+t}\">. We can figure this out by first generating each (s,t)-combination in binary form (so, of length (s+t)) and counting the number of 0's to the left of each 1.</p>\n\n<p>10001000011101 --> becomes the permutation: {0, 3, 4, 4, 4, 1}</p>\n"
},
{
"answer_id": 64961,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In ruby:</p>\n\n<pre><code>str = \"a\"\n100_000_000.times {puts str.next!}\n</code></pre>\n\n<p>It is quite fast, but it is going to take some time =). Of course, you can start at \"aaaaaaaa\" if the short strings aren't interesting to you.</p>\n\n<p>I might have misinterpreted the actual question though - in one of the posts it sounded as if you just needed a bruteforce library of strings, but in the main question it sounds like you need to permutate a particular string.</p>\n\n<p>Your problem is somewhat similar to this one: <a href=\"http://beust.com/weblog/archives/000491.html\" rel=\"nofollow noreferrer\">http://beust.com/weblog/archives/000491.html</a> (list all integers in which none of the digits repeat themselves, which resulted in a whole lot of languages solving it, with the ocaml guy using permutations, and some java guy using yet another solution).</p>\n"
},
{
"answer_id": 69559,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>This is a translation of Mike's Ruby version, into Common Lisp:</p>\n\n<pre><code>(defun perms (x y original-string)\n (loop with all = (list \"\")\n with current-array = (list \"\")\n for iteration from 1 to y\n do (loop with next-array = nil\n for string in current-array\n do (loop for c across original-string\n for value = (concatenate 'string string (string c))\n do (push value next-array)\n (push value all))\n (setf current-array (reverse next-array)))\n finally (return (nreverse (delete-if #'(lambda (el) (< (length el) x)) all)))))\n</code></pre>\n\n<p>And another version, slightly shorter and using more loop facility features:</p>\n\n<pre><code>(defun perms (x y original-string)\n (loop repeat y\n collect (loop for string in (or (car (last sets)) (list \"\"))\n append (loop for c across original-string\n collect (concatenate 'string string (string c)))) into sets\n finally (return (loop for set in sets\n append (loop for el in set when (>= (length el) x) collect el)))))\n</code></pre>\n"
},
{
"answer_id": 69612,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "<p>Though this doesn't answer your question exactly, here's one way to generate every permutation of the letters from a number of strings of the same length: eg, if your words were \"coffee\", \"joomla\" and \"moodle\", you can expect output like \"coodle\", \"joodee\", \"joffle\", etc.</p>\n\n<p>Basically, the number of combinations is the (number of words) to the power of (number of letters per word). So, choose a random number between 0 and the number of combinations - 1, convert that number to base (number of words), then use each digit of that number as the indicator for which word to take the next letter from.</p>\n\n<p>eg: in the above example. 3 words, 6 letters = 729 combinations. Choose a random number: 465. Convert to base 3: 122020. Take the first letter from word 1, 2nd from word 2, 3rd from word 2, 4th from word 0... and you get... \"joofle\".</p>\n\n<p>If you wanted all the permutations, just loop from 0 to 728. Of course, if you're just choosing one random value, a much <strike>simpler</strike> less-confusing way would be to loop over the letters. This method lets you avoid recursion, should you want all the permutations, plus it makes you look like you know Maths<sup>(tm)</sup>!</p>\n\n<p>If the number of combinations is excessive, you can break it up into a series of smaller words and concatenate them at the end.</p>\n"
},
{
"answer_id": 147211,
"author": "Sarp Centel",
"author_id": 16622,
"author_profile": "https://Stackoverflow.com/users/16622",
"pm_score": 3,
"selected": false,
"text": "<p>Recursive solution in C++ </p>\n\n<pre><code>int main (int argc, char * const argv[]) {\n string s = \"sarp\";\n bool used [4];\n permute(0, \"\", used, s);\n}\n\nvoid permute(int level, string permuted, bool used [], string &original) {\n int length = original.length();\n\n if(level == length) { // permutation complete, display\n cout << permuted << endl;\n } else {\n for(int i=0; i<length; i++) { // try to add an unused character\n if(!used[i]) {\n used[i] = true;\n permute(level+1, original[i] + permuted, used, original); // find the permutations starting with this string\n used[i] = false;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 217209,
"author": "Crackerjack",
"author_id": 13556,
"author_profile": "https://Stackoverflow.com/users/13556",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a simple word C# recursive solution:</p>\n\n<p><strong>Method:</strong></p>\n\n<pre><code>public ArrayList CalculateWordPermutations(string[] letters, ArrayList words, int index)\n {\n bool finished = true;\n ArrayList newWords = new ArrayList();\n if (words.Count == 0)\n {\n foreach (string letter in letters)\n {\n words.Add(letter);\n }\n }\n\n for(int j=index; j<words.Count; j++)\n {\n string word = (string)words[j];\n for(int i =0; i<letters.Length; i++)\n {\n if(!word.Contains(letters[i]))\n {\n finished = false;\n string newWord = (string)word.Clone();\n newWord += letters[i];\n newWords.Add(newWord);\n }\n }\n }\n\n foreach (string newWord in newWords)\n { \n words.Add(newWord);\n }\n\n if(finished == false)\n {\n CalculateWordPermutations(letters, words, words.Count - newWords.Count);\n }\n return words;\n }\n</code></pre>\n\n<p><strong>Calling:</strong></p>\n\n<pre><code>string[] letters = new string[]{\"a\",\"b\",\"c\"};\nArrayList words = CalculateWordPermutations(letters, new ArrayList(), 0);\n</code></pre>\n"
},
{
"answer_id": 291127,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 4,
"selected": false,
"text": "<p>You might look at \"<a href=\"http://applied-math.org/subset.pdf\" rel=\"noreferrer\">Efficiently Enumerating the Subsets of a Set</a>\", which describes an algorithm to do part of what you want - quickly generate all subsets of N characters from length x to y. It contains an implementation in C. </p>\n\n<p>For each subset, you'd still have to generate all the permutations. For instance if you wanted 3 characters from \"abcde\", this algorithm would give you \"abc\",\"abd\", \"abe\"...\nbut you'd have to permute each one to get \"acb\", \"bac\", \"bca\", etc.</p>\n"
},
{
"answer_id": 550628,
"author": "Chris Lutz",
"author_id": 60777,
"author_profile": "https://Stackoverflow.com/users/60777",
"pm_score": 3,
"selected": false,
"text": "<p>In Perl, if you want to restrict yourself to the lowercase alphabet, you can do this:</p>\n\n<pre><code>my @result = (\"a\" .. \"zzzz\");\n</code></pre>\n\n<p>This gives all possible strings between 1 and 4 characters using lowercase characters. For uppercase, change <code>\"a\"</code> to <code>\"A\"</code> and <code>\"zzzz\"</code> to <code>\"ZZZZ\"</code>.</p>\n\n<p>For mixed-case it gets much harder, and probably not doable with one of Perl's builtin operators like that.</p>\n"
},
{
"answer_id": 2575419,
"author": "Lazer",
"author_id": 113124,
"author_profile": "https://Stackoverflow.com/users/113124",
"pm_score": 4,
"selected": false,
"text": "<p>Some working Java code based on <a href=\"https://stackoverflow.com/questions/361/generate-list-of-all-possible-permutations-of-a-string/147211#147211\">Sarp's answer</a>:</p>\n\n<pre><code>public class permute {\n\n static void permute(int level, String permuted,\n boolean used[], String original) {\n int length = original.length();\n if (level == length) {\n System.out.println(permuted);\n } else {\n for (int i = 0; i < length; i++) {\n if (!used[i]) {\n used[i] = true;\n permute(level + 1, permuted + original.charAt(i),\n used, original);\n used[i] = false;\n }\n }\n }\n }\n\n public static void main(String[] args) {\n String s = \"hello\";\n boolean used[] = {false, false, false, false, false};\n permute(0, \"\", used, s);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3178268,
"author": "Prakhar Gupta",
"author_id": 383513,
"author_profile": "https://Stackoverflow.com/users/383513",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a simple solution in C#.</p>\n\n<p>It generates only the distinct permutations of a given string.</p>\n\n<pre><code> static public IEnumerable<string> permute(string word)\n {\n if (word.Length > 1)\n {\n\n char character = word[0];\n foreach (string subPermute in permute(word.Substring(1)))\n {\n\n for (int index = 0; index <= subPermute.Length; index++)\n {\n string pre = subPermute.Substring(0, index);\n string post = subPermute.Substring(index);\n\n if (post.Contains(character))\n continue; \n\n yield return pre + character + post;\n }\n\n }\n }\n else\n {\n yield return word;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 4010695,
"author": "Swapneel Patil",
"author_id": 251769,
"author_profile": "https://Stackoverflow.com/users/251769",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import java.util.*;\n\npublic class all_subsets {\n public static void main(String[] args) {\n String a = \"abcd\";\n for(String s: all_perm(a)) {\n System.out.println(s);\n }\n }\n\n public static Set<String> concat(String c, Set<String> lst) {\n HashSet<String> ret_set = new HashSet<String>();\n for(String s: lst) {\n ret_set.add(c+s);\n }\n return ret_set;\n }\n\n public static HashSet<String> all_perm(String a) {\n HashSet<String> set = new HashSet<String>();\n if(a.length() == 1) {\n set.add(a);\n } else {\n for(int i=0; i<a.length(); i++) {\n set.addAll(concat(a.charAt(i)+\"\", all_perm(a.substring(0, i)+a.substring(i+1, a.length()))));\n }\n }\n return set;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4134431,
"author": "rocksportrocker",
"author_id": 233813,
"author_profile": "https://Stackoverflow.com/users/233813",
"pm_score": 4,
"selected": false,
"text": "<p>Non recursive solution according to Knuth, Python example: </p>\n\n<pre><code>def nextPermutation(perm):\n k0 = None\n for i in range(len(perm)-1):\n if perm[i]<perm[i+1]:\n k0=i\n if k0 == None:\n return None\n\n l0 = k0+1\n for i in range(k0+1, len(perm)):\n if perm[k0] < perm[i]:\n l0 = i\n\n perm[k0], perm[l0] = perm[l0], perm[k0]\n perm[k0+1:] = reversed(perm[k0+1:])\n return perm\n\nperm=list(\"12345\")\nwhile perm:\n print perm\n perm = nextPermutation(perm)\n</code></pre>\n"
},
{
"answer_id": 4927100,
"author": "Peyman",
"author_id": 556778,
"author_profile": "https://Stackoverflow.com/users/556778",
"pm_score": 3,
"selected": false,
"text": "<p>... and here is the C version:</p>\n\n<pre><code>void permute(const char *s, char *out, int *used, int len, int lev)\n{\n if (len == lev) {\n out[lev] = '\\0';\n puts(out);\n return;\n }\n\n int i;\n for (i = 0; i < len; ++i) {\n if (! used[i])\n continue;\n\n used[i] = 1;\n out[lev] = s[i];\n permute(s, out, used, len, lev + 1);\n used[i] = 0;\n }\n return;\n}\n</code></pre>\n"
},
{
"answer_id": 5082432,
"author": "raj",
"author_id": 628891,
"author_profile": "https://Stackoverflow.com/users/628891",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>permute (ABC) -> A.perm(BC) -> A.perm[B.perm(C)] -> A.perm[(<strong>*B</strong><em>C), (C</em><strong>B*</strong>)] -> [(<strong>*A</strong><em>BC), (B</em><strong>A</strong><em>C), (BC</em><strong>A*</strong>), (<strong>*A</strong><em>CB), (C</em><strong>A</strong><em>B), (CB</em><strong>A*</strong>)]\n To remove duplicates when inserting each alphabet check to see if previous string ends with the same alphabet (why? -exercise)</p>\n</blockquote>\n\n<pre><code>public static void main(String[] args) {\n\n for (String str : permStr(\"ABBB\")){\n System.out.println(str);\n }\n}\n\nstatic Vector<String> permStr(String str){\n\n if (str.length() == 1){\n Vector<String> ret = new Vector<String>();\n ret.add(str);\n return ret;\n }\n\n char start = str.charAt(0);\n Vector<String> endStrs = permStr(str.substring(1));\n Vector<String> newEndStrs = new Vector<String>();\n for (String endStr : endStrs){\n for (int j = 0; j <= endStr.length(); j++){\n if (endStr.substring(0, j).endsWith(String.valueOf(start)))\n break;\n newEndStrs.add(endStr.substring(0, j) + String.valueOf(start) + endStr.substring(j));\n }\n }\n return newEndStrs;\n}\n</code></pre>\n\n<p>Prints all permutations sans duplicates</p>\n"
},
{
"answer_id": 6140144,
"author": "Pedro",
"author_id": 482019,
"author_profile": "https://Stackoverflow.com/users/482019",
"pm_score": 2,
"selected": false,
"text": "<p>This code in python, when called with <code>allowed_characters</code> set to <code>[0,1]</code> and 4 character max, would generate 2^4 results:</p>\n\n<p><code>['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']</code></p>\n\n<pre><code>def generate_permutations(chars = 4) :\n\n#modify if in need!\n allowed_chars = [\n '0',\n '1',\n ]\n\n status = []\n for tmp in range(chars) :\n status.append(0)\n\n last_char = len(allowed_chars)\n\n rows = []\n for x in xrange(last_char ** chars) :\n rows.append(\"\")\n for y in range(chars - 1 , -1, -1) :\n key = status[y]\n rows[x] = allowed_chars[key] + rows[x]\n\n for pos in range(chars - 1, -1, -1) :\n if(status[pos] == last_char - 1) :\n status[pos] = 0\n else :\n status[pos] += 1\n break;\n\n return rows\n\nimport sys\n\n\nprint generate_permutations()\n</code></pre>\n\n<p>Hope this is of use to you. Works with any character, not only numbers</p>\n"
},
{
"answer_id": 6922856,
"author": "orion elenzil",
"author_id": 230851,
"author_profile": "https://Stackoverflow.com/users/230851",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a non-recursive version I came up with, in javascript.\nIt's not based on Knuth's non-recursive one above, although it has some similarities in element swapping.\nI've verified its correctness for input arrays of up to 8 elements.</p>\n\n<p>A quick optimization would be pre-flighting the <code>out</code> array and avoiding <code>push()</code>.</p>\n\n<p>The basic idea is:</p>\n\n<ol>\n<li><p>Given a single source array, generate a first new set of arrays which swap the first element with each subsequent element in turn, each time leaving the other elements unperturbed.\neg: given 1234, generate 1234, 2134, 3214, 4231.</p></li>\n<li><p>Use each array from the previous pass as the seed for a new pass,\nbut instead of swapping the first element, swap the second element with each subsequent element. Also, this time, don't include the original array in the output.</p></li>\n<li><p>Repeat step 2 until done.</p></li>\n</ol>\n\n<p>Here is the code sample:</p>\n\n<pre><code>function oxe_perm(src, depth, index)\n{\n var perm = src.slice(); // duplicates src.\n perm = perm.split(\"\");\n perm[depth] = src[index];\n perm[index] = src[depth];\n perm = perm.join(\"\");\n return perm;\n}\n\nfunction oxe_permutations(src)\n{\n out = new Array();\n\n out.push(src);\n\n for (depth = 0; depth < src.length; depth++) {\n var numInPreviousPass = out.length;\n for (var m = 0; m < numInPreviousPass; ++m) {\n for (var n = depth + 1; n < src.length; ++n) {\n out.push(oxe_perm(out[m], depth, n));\n }\n }\n }\n\n return out;\n}\n</code></pre>\n"
},
{
"answer_id": 7625511,
"author": "Anonymous Coward",
"author_id": 975258,
"author_profile": "https://Stackoverflow.com/users/975258",
"pm_score": 2,
"selected": false,
"text": "<p>I needed this today, and although the answers already given pointed me in the right direction, they weren't quite what I wanted.</p>\n\n<p>Here's an implementation using Heap's method. The length of the array must be at least 3 and for practical considerations not be bigger than 10 or so, depending on what you want to do, patience and clock speed.</p>\n\n<p>Before you enter your loop, initialise <code>Perm(1 To N)</code> with the first permutation, <code>Stack(3 To N)</code> with zeroes*, and <code>Level</code> with <code>2</code>**. At the end of the loop call <code>NextPerm</code>, which will return false when we're done.</p>\n\n<p>* VB will do that for you.</p>\n\n<p>** You can change NextPerm a little to make this unnecessary, but it's clearer like this.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Option Explicit\n\nFunction NextPerm(Perm() As Long, Stack() As Long, Level As Long) As Boolean\nDim N As Long\nIf Level = 2 Then\n Swap Perm(1), Perm(2)\n Level = 3\nElse\n While Stack(Level) = Level - 1\n Stack(Level) = 0\n If Level = UBound(Stack) Then Exit Function\n Level = Level + 1\n Wend\n Stack(Level) = Stack(Level) + 1\n If Level And 1 Then N = 1 Else N = Stack(Level)\n Swap Perm(N), Perm(Level)\n Level = 2\nEnd If\nNextPerm = True\nEnd Function\n\nSub Swap(A As Long, B As Long)\nA = A Xor B\nB = A Xor B\nA = A Xor B\nEnd Sub\n\n'This is just for testing.\nPrivate Sub Form_Paint()\nConst Max = 8\nDim A(1 To Max) As Long, I As Long\nDim S(3 To Max) As Long, J As Long\nDim Test As New Collection, T As String\nFor I = 1 To UBound(A)\n A(I) = I\nNext\nCls\nScaleLeft = 0\nJ = 2\nDo\n If CurrentY + TextHeight(\"0\") > ScaleHeight Then\n ScaleLeft = ScaleLeft - TextWidth(\" 0 \") * (UBound(A) + 1)\n CurrentY = 0\n CurrentX = 0\n End If\n T = vbNullString\n For I = 1 To UBound(A)\n Print A(I);\n T = T & Hex(A(I))\n Next\n Print\n Test.Add Null, T\nLoop While NextPerm(A, S, J)\nJ = 1\nFor I = 2 To UBound(A)\n J = J * I\nNext\nIf J <> Test.Count Then Stop\nEnd Sub\n</code></pre>\n\n<p>Other methods are described by various authors. Knuth describes two, one gives lexical order, but is complex and slow, the other is known as the method of plain changes. Jie Gao and Dianjun Wang also wrote an interesting paper.</p>\n"
},
{
"answer_id": 8808091,
"author": "Unnykrishnan S",
"author_id": 1141488,
"author_profile": "https://Stackoverflow.com/users/1141488",
"pm_score": 5,
"selected": false,
"text": "<p>It's better to use backtracking</p>\n\n\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n#include <string.h>\n\nvoid swap(char *a, char *b) {\n char temp;\n temp = *a;\n *a = *b;\n *b = temp;\n}\n\nvoid print(char *a, int i, int n) {\n int j;\n if(i == n) {\n printf(\"%s\\n\", a);\n } else {\n for(j = i; j <= n; j++) {\n swap(a + i, a + j);\n print(a, i + 1, n);\n swap(a + i, a + j);\n }\n }\n}\n\nint main(void) {\n char a[100];\n gets(a);\n print(a, 0, strlen(a) - 1);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 10238654,
"author": "Kem Mason",
"author_id": 398582,
"author_profile": "https://Stackoverflow.com/users/398582",
"pm_score": 3,
"selected": false,
"text": "<p>Ruby answer that works:</p>\n\n<pre><code>class String\n def each_char_with_index\n 0.upto(size - 1) do |index|\n yield(self[index..index], index)\n end\n end\n def remove_char_at(index)\n return self[1..-1] if index == 0\n self[0..(index-1)] + self[(index+1)..-1]\n end\nend\n\ndef permute(str, prefix = '')\n if str.size == 0\n puts prefix\n return\n end\n str.each_char_with_index do |char, index|\n permute(str.remove_char_at(index), prefix + char)\n end\nend\n\n# example\n# permute(\"abc\")\n</code></pre>\n"
},
{
"answer_id": 11672570,
"author": "wliao",
"author_id": 150607,
"author_profile": "https://Stackoverflow.com/users/150607",
"pm_score": 0,
"selected": false,
"text": "<p>c# iterative:</p>\n\n<pre><code>public List<string> Permutations(char[] chars)\n {\n List<string> words = new List<string>();\n words.Add(chars[0].ToString());\n for (int i = 1; i < chars.Length; ++i)\n {\n int currLen = words.Count;\n for (int j = 0; j < currLen; ++j)\n {\n var w = words[j];\n for (int k = 0; k <= w.Length; ++k)\n {\n var nstr = w.Insert(k, chars[i].ToString());\n if (k == 0)\n words[j] = nstr;\n else\n words.Add(nstr);\n }\n }\n }\n return words;\n }\n</code></pre>\n"
},
{
"answer_id": 17182840,
"author": "Ramy",
"author_id": 796477,
"author_profile": "https://Stackoverflow.com/users/796477",
"pm_score": 3,
"selected": false,
"text": "<p>The following Java recursion prints all permutations of a given string:</p>\n\n<pre><code>//call it as permut(\"\",str);\n\npublic void permut(String str1,String str2){\n if(str2.length() != 0){\n char ch = str2.charAt(0);\n for(int i = 0; i <= str1.length();i++)\n permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),\n str2.substring(1,str2.length()));\n }else{\n System.out.println(str1);\n }\n}\n</code></pre>\n\n<p>Following is the updated version of above \"permut\" method which makes n! (n factorial) less recursive calls compared to the above method</p>\n\n<pre><code>//call it as permut(\"\",str);\n\npublic void permut(String str1,String str2){\n if(str2.length() > 1){\n char ch = str2.charAt(0);\n for(int i = 0; i <= str1.length();i++)\n permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),\n str2.substring(1,str2.length()));\n }else{\n char ch = str2.charAt(0);\n for(int i = 0; i <= str1.length();i++)\n System.out.println(str1.substring(0,i) + ch + str1.substring(i,str1.length()),\n str2.substring(1,str2.length()));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 17480974,
"author": "Winster",
"author_id": 1440435,
"author_profile": "https://Stackoverflow.com/users/1440435",
"pm_score": 0,
"selected": false,
"text": "<p>A recursive solution in python. The good thing about this code is that it exports a dictionary, with keys as strings and all possible permutations as values. All possible string lengths are included, so in effect, you are creating a superset.</p>\n\n<p>If you only require the final permutations, you can delete other keys from the dictionary.</p>\n\n<p>In this code, the dictionary of permutations is global.</p>\n\n<p>At the base case, I store the value as both possibilities in a list. <code>perms['ab'] = ['ab','ba']</code>.</p>\n\n<p>For higher string lengths, the function refers to lower string lengths and incorporates the previously calculated permutations.</p>\n\n<p>The function does two things:</p>\n\n<ul>\n<li>calls itself with a smaller string</li>\n<li>returns a list of permutations of a particular string if already available. If returned to itself, these will be used to append to the character and create newer permutations.</li>\n</ul>\n\n<p>Expensive for memory. </p>\n\n<pre><code>perms = {}\ndef perm(input_string):\n global perms\n if input_string in perms:\n return perms[input_string] # This will send a list of all permutations\n elif len(input_string) == 2:\n perms[input_string] = [input_string, input_string[-1] + input_string [-2]]\n return perms[input_string]\n else:\n perms[input_string] = []\n for index in range(0, len(input_string)):\n new_string = input_string[0:index] + input_string[index +1:]\n perm(new_string)\n for entries in perms[new_string]:\n perms[input_string].append(input_string[index] + entries)\n return perms[input_string]\n</code></pre>\n"
},
{
"answer_id": 18387484,
"author": "abkds",
"author_id": 2537745,
"author_profile": "https://Stackoverflow.com/users/2537745",
"pm_score": 0,
"selected": false,
"text": "<pre><code>def gen( x,y,list): #to generate all strings inserting y at different positions\nlist = []\nlist.append( y+x )\nfor i in range( len(x) ):\n list.append( func(x,0,i) + y + func(x,i+1,len(x)-1) )\nreturn list \n\ndef func( x,i,j ): #returns x[i..j]\nz = '' \nfor i in range(i,j+1):\n z = z+x[i]\nreturn z \n\ndef perm( x , length , list ): #perm function\nif length == 1 : # base case\n list.append( x[len(x)-1] )\n return list \nelse:\n lists = perm( x , length-1 ,list )\n lists_temp = lists #temporarily storing the list \n lists = []\n for i in range( len(lists_temp) ) :\n list_temp = gen(lists_temp[i],x[length-2],lists)\n lists += list_temp \n return lists\n</code></pre>\n"
},
{
"answer_id": 19461362,
"author": "Neo",
"author_id": 2263483,
"author_profile": "https://Stackoverflow.com/users/2263483",
"pm_score": 0,
"selected": false,
"text": "<p>Recursive Solution with driver <code>main()</code> method.</p>\n\n<pre><code>public class AllPermutationsOfString {\npublic static void stringPermutations(String newstring, String remaining) {\n if(remaining.length()==0)\n System.out.println(newstring);\n\n for(int i=0; i<remaining.length(); i++) {\n String newRemaining = remaining.replaceFirst(remaining.charAt(i)+\"\", \"\");\n stringPermutations(newstring+remaining.charAt(i), newRemaining);\n }\n}\n\npublic static void main(String[] args) {\n String string = \"abc\";\n AllPermutationsOfString.stringPermutations(\"\", string); \n}\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 20993674,
"author": "gd1",
"author_id": 671092,
"author_profile": "https://Stackoverflow.com/users/671092",
"pm_score": 4,
"selected": false,
"text": "<p>There are a lot of good answers here. I also suggest a very simple recursive solution in C++.</p>\n\n<pre><code>#include <string>\n#include <iostream>\n\ntemplate<typename Consume>\nvoid permutations(std::string s, Consume consume, std::size_t start = 0) {\n if (start == s.length()) consume(s);\n for (std::size_t i = start; i < s.length(); i++) {\n std::swap(s[start], s[i]);\n permutations(s, consume, start + 1);\n }\n}\n\nint main(void) {\n std::string s = \"abcd\";\n permutations(s, [](std::string s) {\n std::cout << s << std::endl;\n });\n}\n</code></pre>\n\n<p><strong>Note</strong>: strings with repeated characters will not produce unique permutations.</p>\n"
},
{
"answer_id": 21298759,
"author": "Paté",
"author_id": 474321,
"author_profile": "https://Stackoverflow.com/users/474321",
"pm_score": 0,
"selected": false,
"text": "<pre><code>def permutation(str)\n posibilities = []\n str.split('').each do |char|\n if posibilities.size == 0\n posibilities[0] = char.downcase\n posibilities[1] = char.upcase\n else\n posibilities_count = posibilities.length\n posibilities = posibilities + posibilities\n posibilities_count.times do |i|\n posibilities[i] += char.downcase\n posibilities[i+posibilities_count] += char.upcase\n end\n end\n end\n posibilities\nend\n</code></pre>\n\n<p>Here is my take on a non recursive version</p>\n"
},
{
"answer_id": 21765529,
"author": "Nipun Talukdar",
"author_id": 1898070,
"author_profile": "https://Stackoverflow.com/users/1898070",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a link that describes how to print permutations of a string. \n<a href=\"http://nipun-linuxtips.blogspot.in/2012/11/print-all-permutations-of-characters-in.html\" rel=\"nofollow\">http://nipun-linuxtips.blogspot.in/2012/11/print-all-permutations-of-characters-in.html</a></p>\n"
},
{
"answer_id": 24720609,
"author": "Abdul Fatir",
"author_id": 2605733,
"author_profile": "https://Stackoverflow.com/users/2605733",
"pm_score": 0,
"selected": false,
"text": "<p>The pythonic solution: </p>\n\n<pre><code>from itertools import permutations\ns = 'ABCDEF'\np = [''.join(x) for x in permutations(s)]\n</code></pre>\n"
},
{
"answer_id": 31086857,
"author": "Adilli Adil",
"author_id": 2172507,
"author_profile": "https://Stackoverflow.com/users/2172507",
"pm_score": 0,
"selected": false,
"text": "<p>Well here is an elegant, non-recursive, O(n!) solution:</p>\n\n<pre><code>public static StringBuilder[] permutations(String s) {\n if (s.length() == 0)\n return null;\n int length = fact(s.length());\n StringBuilder[] sb = new StringBuilder[length];\n for (int i = 0; i < length; i++) {\n sb[i] = new StringBuilder();\n }\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n int times = length / (i + 1);\n for (int j = 0; j < times; j++) {\n for (int k = 0; k < length / times; k++) {\n sb[j * length / times + k].insert(k, ch);\n }\n }\n }\n return sb;\n }\n</code></pre>\n"
},
{
"answer_id": 37639997,
"author": "Achilles Ram Nakirekanti",
"author_id": 3052383,
"author_profile": "https://Stackoverflow.com/users/3052383",
"pm_score": 0,
"selected": false,
"text": "<p>code written for java language :</p>\n\n<p>package namo.algorithms;</p>\n\n<p>import java.util.Scanner;</p>\n\n<p>public class Permuations { </p>\n\n<pre><code>public static int totalPermutationsCount = 0;\n public static void main(String[] args) {\n\n Scanner sc = new Scanner(System.in);\n System.out.println(\"input string : \");\n String inputString = sc.nextLine();\n System.out.println(\"given input String ==> \"+inputString+ \" :: length is = \"+inputString.length());\n findPermuationsOfString(-1, inputString);\n System.out.println(\"**************************************\");\n System.out.println(\"total permutation strings ==> \"+totalPermutationsCount);\n }\n\n\n public static void findPermuationsOfString(int fixedIndex, String inputString) {\n int currentIndex = fixedIndex +1;\n\n for (int i = currentIndex; i < inputString.length(); i++) {\n //swap elements and call the findPermuationsOfString()\n\n char[] carr = inputString.toCharArray();\n char tmp = carr[currentIndex];\n carr[currentIndex] = carr[i];\n carr[i] = tmp;\n inputString = new String(carr);\n\n //System.out.println(\"chat At : current String ==> \"+inputString.charAt(currentIndex));\n if(currentIndex == inputString.length()-1) {\n totalPermutationsCount++;\n System.out.println(\"permuation string ==> \"+inputString);\n } else {\n //System.out.println(\"in else block>>>>\");\n findPermuationsOfString(currentIndex, inputString);\n char[] rarr = inputString.toCharArray();\n char rtmp = carr[i];\n carr[i] = carr[currentIndex];\n carr[currentIndex] = rtmp;\n inputString = new String(carr);\n }\n }\n }\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 42061222,
"author": "Naresh Dhiman",
"author_id": 2130204,
"author_profile": "https://Stackoverflow.com/users/2130204",
"pm_score": -1,
"selected": false,
"text": "<p>The possible string permutations can be computed using recursive function. Below is one of the possible solution.</p>\n\n<pre><code>public static String insertCharAt(String s, int index, char c) {\n StringBuffer sb = new StringBuffer(s);\n StringBuffer sbb = sb.insert(index, c);\n return sbb.toString();\n}\n\npublic static ArrayList<String> getPerm(String s, int index) {\n ArrayList<String> perm = new ArrayList<String>();\n\n if (index == s.length()-1) {\n perm.add(String.valueOf(s.charAt(index)));\n return perm;\n }\n\n ArrayList<String> p = getPerm(s, index+1);\n char c = s.charAt(index);\n\n for(String pp : p) {\n for (int idx=0; idx<pp.length()+1; idx++) {\n String ss = insertCharAt(pp, idx, c);\n perm.add(ss);\n }\n }\n\n return perm; \n}\n\npublic static void testGetPerm(String s) {\n ArrayList<String> perm = getPerm(s,0);\n System.out.println(s+\" --> total permutation are :: \"+perm.size());\n System.out.println(perm.toString());\n}\n</code></pre>\n"
},
{
"answer_id": 63979467,
"author": "mourya venkat",
"author_id": 7522482,
"author_profile": "https://Stackoverflow.com/users/7522482",
"pm_score": 1,
"selected": false,
"text": "<p>Recursive Approach</p>\n<pre><code>func StringPermutations(inputStr string) (permutations []string) {\n for i := 0; i < len(inputStr); i++ {\n inputStr = inputStr[1:] + inputStr[0:1]\n if len(inputStr) <= 2 {\n permutations = append(permutations, inputStr)\n continue\n }\n leftPermutations := StringPermutations(inputStr[0 : len(inputStr)-1])\n for _, leftPermutation := range leftPermutations {\n permutations = append(permutations, leftPermutation+inputStr[len(inputStr)-1:])\n }\n }\n return\n}\n</code></pre>\n"
},
{
"answer_id": 66228704,
"author": "Bhaskar13",
"author_id": 11930483,
"author_profile": "https://Stackoverflow.com/users/11930483",
"pm_score": 2,
"selected": false,
"text": "<p>Many of the previous answers used backtracking. This is the <strong>asymptotically optimal way O(n*n!) of generating permutations</strong> after initial sorting</p>\n<pre><code>class Permutation {\n\n /* runtime -O(n) for generating nextPermutaion\n * and O(n*n!) for generating all n! permutations with increasing sorted array as start\n * return true, if there exists next lexicographical sequence\n * e.g [a,b,c],3-> true, modifies array to [a,c,b]\n * e.g [c,b,a],3-> false, as it is largest lexicographic possible */\n public static boolean nextPermutation(char[] seq, int len) {\n // 1\n if (len <= 1)\n return false;// no more perm\n // 2: Find last j such that seq[j] <= seq[j+1]. Terminate if no such j exists\n int j = len - 2;\n while (j >= 0 && seq[j] >= seq[j + 1]) {\n --j;\n }\n if (j == -1)\n return false;// no more perm\n // 3: Find last l such that seq[j] <= seq[l], then exchange elements j and l\n int l = len - 1;\n while (seq[j] >= seq[l]) {\n --l;\n }\n swap(seq, j, l);\n // 4: Reverse elements j+1 ... count-1:\n reverseSubArray(seq, j + 1, len - 1);\n // return seq, add store next perm\n\n return true;\n }\n private static void swap(char[] a, int i, int j) {\n char temp = a[i];\n a[i] = a[j];\n a[j] = temp;\n }\n\n private static void reverseSubArray(char[] a, int lo, int hi) {\n while (lo < hi) {\n swap(a, lo, hi);\n ++lo;\n --hi;\n }\n }\n public static void main(String[] args) {\n String str = "abcdefg";\n char[] array = str.toCharArray();\n Arrays.sort(array);\n int cnt=0;\n do {\n System.out.println(new String(array));\n cnt++;\n }while(nextPermutation(array, array.length));\n System.out.println(cnt);//5040=7!\n }\n //if we use "bab"-> "abb", "bab", "bba", 3(#permutations)\n}\n</code></pre>\n"
}
] | 2008/08/02 | [
"https://Stackoverflow.com/questions/361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.
Any language would work, but it should be portable. | There are several ways to do this. Common methods use recursion, memoization, or dynamic programming. The basic idea is that you produce a list of all strings of length 1, then in each iteration, for all strings produced in the last iteration, add that string concatenated with each character in the string individually. (the variable index in the code below keeps track of the start of the last and the next iteration)
Some pseudocode:
```
list = originalString.split('')
index = (0,0)
list = [""]
for iteration n in 1 to y:
index = (index[1], len(list))
for string s in list.subset(index[0] to end):
for character c in originalString:
list.add(s + c)
```
you'd then need to remove all strings less than x in length, they'll be the first (x-1) \* len(originalString) entries in the list. |
402 | <p>Please note that this question is from 2008 and now is of only historic interest.</p>
<hr>
<p>What's the best way to create an iPhone application that runs in landscape mode from the start, regardless of the position of the device?</p>
<p>Both programmatically and using the Interface Builder.</p>
| [
{
"answer_id": 36884,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": 5,
"selected": false,
"text": "<p>From the Apple Dev Site:</p>\n\n<blockquote>\n <p>To start your application in landscape\n mode so that the status bar is in the\n appropriate position immediately, edit\n your Info.plist file to add the\n UIInterfaceOrientation key with the\n appropriate value\n (UIInterfaceOrientationLandscapeRight\n or\n UIInterfaceOrientationLandscapeLeft),\n as shown in Listing 2.</p>\n \n <p>Listing 2: Starting your application\n in landscape mode</p>\n\n<pre><code><key>UIInterfaceOrientation</key>\n<string>UIInterfaceOrientationLandscapeRight</string>\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 36899,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 3,
"selected": false,
"text": "<p>sasb's and michaelpryor's answer appears to be correct, but if it's not working for you, try this alternative:</p>\n\n<pre><code>- (void)applicationDidFinishLaunchingUIApplication *)application {\n application.statusBarOrientation = UIInterfaceOrientationLandscapeRight;\n}\n</code></pre>\n\n<p>Or this one:</p>\n\n<pre><code>[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];\n</code></pre>\n\n<p>Or this one:</p>\n\n<pre><code>[application setStatusBarOrientation: UIInterfaceOrientationLandscapeRight animated:NO];\n</code></pre>\n\n<p>You may also have to call <code>window makeKeyAndVisible;</code> first.</p>\n\n<p>A few links: <a href=\"http://www.iphonedevsdk.com/forum/iphone-sdk-development/1664-developing-landscape-mode.html\" rel=\"nofollow noreferrer\">Developing in landscape mode</a>, <a href=\"http://discussions.apple.com/thread.jspa?threadID=1454154&tstart=135\" rel=\"nofollow noreferrer\">iPhone SDK: How to force Landscape mode only?</a></p>\n\n<p>@Robert: please refer to <a href=\"https://stackoverflow.com/questions/23482/the-iphone-sdk-nda-and-stack-overflow\">The iPhone SDK, NDA, and Stack Overflow</a>.</p>\n"
},
{
"answer_id": 44876,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The latest iPhone OS Programming Guide has a full section on this, with sample code. I am sure this is a recent addition, so maybe you missed it. It explains all the conditions you have to comply with; basically...</p>\n\n<ul>\n<li>set the Info.plist properties (this changes the position of the status bar, but not the view)</li>\n<li>rotate your view manually around its center, on either your UIViewController viewDidLoad: method or your applicationDidFinishLaunching: method or implement auto rotation (\"Autoresizing behaviors\", page 124)</li>\n</ul>\n\n<p>Look for \"Launching in Landscape Mode\", page 102.</p>\n"
},
{
"answer_id": 1773197,
"author": "samvermette",
"author_id": 87158,
"author_profile": "https://Stackoverflow.com/users/87158",
"pm_score": 3,
"selected": false,
"text": "<p>First I set in info.plist</p>\n\n<pre><code><key>UIInterfaceOrientation</key>\n<string>UIInterfaceOrientationLandscapeRight</string>\n</code></pre>\n\n<p>then I put this code in applicationDidFinishLaunching:</p>\n\n<pre><code>CGAffineTransform rotate = CGAffineTransformMakeRotation(1.57079633);\n[window setTransform:rotate];\n\nCGRect contentRect = CGRectMake(0, 0, 480, 320); \nwindow.bounds = contentRect; \n[window setCenter:CGPointMake(160.0f, 240.0f)]; \n</code></pre>\n\n<p>This way I can work on the view in Interface Builder in landscape mode.</p>\n"
},
{
"answer_id": 2530953,
"author": "Fattie",
"author_id": 294884,
"author_profile": "https://Stackoverflow.com/users/294884",
"pm_score": 7,
"selected": true,
"text": "<h1>Historic answer only. Spectacularly out of date.</h1>\n<p>Please note that this answer is now hugely out of date/</p>\n<p>This answer is <strong>only a historical curiosity</strong>.</p>\n<hr />\n<p>Exciting news! As discovered by Andrew below, this problem has been fixed by Apple in 4.0+.</p>\n<p>It would appear it is NO longer necessary to force the size of the view on every view, and the specific serious problem of landscape "only working the first time" has been resolved.</p>\n<p>As of April 2011, it is not possible to test or even build anything below 4.0, so the question is purely a historic curiosity. It's incredible how much trouble it caused developers for so long!</p>\n<hr />\n<p>Here is the original discussion and solution. This is utterly irrelevant now, as these systems are not even operable.</p>\n<hr />\n<p>It is EXTREMELY DIFFICULT to make this work fully -- there are at least three problems/bugs at play.</p>\n<p>try this .. <a href=\"http://www.iphonedevsdk.com/forum/iphone-sdk-development/7366-interface-builder-landscape-design.html#post186977\" rel=\"noreferrer\">interface builder landscape design</a></p>\n<p>Note in particular that where it says <em>"and you need to use shouldAutorotateToInterfaceOrientation properly everywhere"</em> it means everywhere, all your fullscreen views.</p>\n<p>Hope it helps in this nightmare!</p>\n<p>An important reminder of the ADDITIONAL well-known problem at hand here: if you are trying to swap between <em><strong>MORE THAN ONE</strong></em> view (all landscape), <em><strong>IT SIMPLY DOES NOT WORK</strong></em>. It is essential to remember this or you will waste days on the problem. It is literally NOT POSSIBLE. It is the biggest open, known, bug on the iOS platform. There is literally no way to make the hardware make the second view you load, be landscape. The annoying but simple workaround, and what you must do, is have a trivial master UIViewController that does nothing but sit there and let you swap between your views.</p>\n<p>In other words, in iOS because of a major know bug:</p>\n<pre><code>[window addSubview:happyThing.view];\n[window makeKeyAndVisible];\n</code></pre>\n<p><em><strong>You can do that only once</strong></em>. Later, if you try to remove happyThing.view, and instead put in there newThing.view, IT DOES NOT WORK - AND THAT'S THAT. The machine will never rotate the view to landscape. There is no trick fix, even Apple cannot make it work. The workaround you must adopt is having an overall UIViewController that simply sits there and just holds your various views (happyThing, newThing, etc). Hope it helps!</p>\n"
},
{
"answer_id": 2787997,
"author": "IlDan",
"author_id": 103529,
"author_profile": "https://Stackoverflow.com/users/103529",
"pm_score": 5,
"selected": false,
"text": "<p><em>Summary and integration from all the posts, after testing it myself; check the update for 4.x, 5.x below.</em></p>\n\n<p>As of 3.2 you cannot change the orientation of a running application from code.</p>\n\n<p>But you can start an application with a fixed orientation, although doing so this is not straightforward. </p>\n\n<p>Try with this recipe:</p>\n\n<ol>\n<li>set your orientation to <code>UISupportedInterfaceOrientations</code> in the <code>Info.plist</code> file</li>\n<li>in your window define a 480x320 \"base view controller\". Every other view will be added as a subview to its view.</li>\n<li>in all view controllers set up the <code>shouldAutorotateToInterfaceOrientation:</code> method (to return the same value you defined in the plist, of course)</li>\n<li><p>in all view controllers set a background view with </p>\n\n<p><code>self.view.frame = CGRectMake(0, 0, 480, 320)</code> </p>\n\n<p>in the <code>viewDidLoad</code> method.</p></li>\n</ol>\n\n<p><strong>Update (iOS 4.x, 5.x)</strong>: the Apple iOS App Programming Guide has a \"Launching in Landscape Mode\" paragraph in the \"Advanced App Tricks\" chapter.</p>\n\n<p>References:</p>\n\n<ul>\n<li><a href=\"http://www.iphonedevsdk.com/forum/iphone-sdk-development/7366-interface-builder-landscape-design.html#post186977\" rel=\"noreferrer\">interface builder landscape design</a></li>\n<li><a href=\"http://www.iphonedevsdk.com/forum/iphone-sdk-development/7366-interface-builder-landscape-design.html#post190014\" rel=\"noreferrer\">interface builder landscape design-1</a></li>\n</ul>\n"
},
{
"answer_id": 4290617,
"author": "Arlen Anderson",
"author_id": 247151,
"author_profile": "https://Stackoverflow.com/users/247151",
"pm_score": 3,
"selected": false,
"text": "<p>I'm surprised no one has come up with this answer yet:</p>\n\n<p>In all my tests when a dismissing a modal view controller the parent view controller's preferred orientation set in <code>shouldAutorotateToInterfaceOrientation</code> is honored even when part of a UINavigationController. So the solution to this is simple:</p>\n\n<p>Create a dummy UIViewController with a UIImageView for a background. Set the image to the default.png image your app uses on startup.</p>\n\n<p>When <code>viewWillAppear</code> gets called in your root view controller, just present the dummy view controller without animation.</p>\n\n<p>when <code>viewDidAppear</code> gets called in your dummy view controller, dismiss the view controller with a nice cross dissolve animation.</p>\n\n<p>Not only does this work, but it looks good! BTW, just for clarification i do the root view controller's <code>viewWillAppear</code> like this:</p>\n\n<pre><code>- (void)viewWillAppear:(BOOL)animated\n{\n if ( dummy != nil ) {\n [dummy setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];\n [self presentModalViewController:dummy animated:NO];\n [dummy release];\n dummy = nil;\n }\n...\n}\n</code></pre>\n"
},
{
"answer_id": 5209365,
"author": "nicc",
"author_id": 499901,
"author_profile": "https://Stackoverflow.com/users/499901",
"pm_score": 2,
"selected": false,
"text": "<p>See this answer: <a href=\"https://stackoverflow.com/questions/2647786/landscape-mode-only-for-iphone-or-ipad/2647807#2647807\">Landscape Mode ONLY for iPhone or iPad</a></p>\n\n<ol>\n<li>add orientation to plist</li>\n<li>shouldAutorotateToInterfaceOrientation = YES in all files</li>\n</ol>\n\n<p>Although if you're using mixed modes, you might be better off with </p>\n\n<pre><code>[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];\n</code></pre>\n"
}
] | 2008/08/02 | [
"https://Stackoverflow.com/questions/402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136/"
] | Please note that this question is from 2008 and now is of only historic interest.
---
What's the best way to create an iPhone application that runs in landscape mode from the start, regardless of the position of the device?
Both programmatically and using the Interface Builder. | Historic answer only. Spectacularly out of date.
================================================
Please note that this answer is now hugely out of date/
This answer is **only a historical curiosity**.
---
Exciting news! As discovered by Andrew below, this problem has been fixed by Apple in 4.0+.
It would appear it is NO longer necessary to force the size of the view on every view, and the specific serious problem of landscape "only working the first time" has been resolved.
As of April 2011, it is not possible to test or even build anything below 4.0, so the question is purely a historic curiosity. It's incredible how much trouble it caused developers for so long!
---
Here is the original discussion and solution. This is utterly irrelevant now, as these systems are not even operable.
---
It is EXTREMELY DIFFICULT to make this work fully -- there are at least three problems/bugs at play.
try this .. [interface builder landscape design](http://www.iphonedevsdk.com/forum/iphone-sdk-development/7366-interface-builder-landscape-design.html#post186977)
Note in particular that where it says *"and you need to use shouldAutorotateToInterfaceOrientation properly everywhere"* it means everywhere, all your fullscreen views.
Hope it helps in this nightmare!
An important reminder of the ADDITIONAL well-known problem at hand here: if you are trying to swap between ***MORE THAN ONE*** view (all landscape), ***IT SIMPLY DOES NOT WORK***. It is essential to remember this or you will waste days on the problem. It is literally NOT POSSIBLE. It is the biggest open, known, bug on the iOS platform. There is literally no way to make the hardware make the second view you load, be landscape. The annoying but simple workaround, and what you must do, is have a trivial master UIViewController that does nothing but sit there and let you swap between your views.
In other words, in iOS because of a major know bug:
```
[window addSubview:happyThing.view];
[window makeKeyAndVisible];
```
***You can do that only once***. Later, if you try to remove happyThing.view, and instead put in there newThing.view, IT DOES NOT WORK - AND THAT'S THAT. The machine will never rotate the view to landscape. There is no trick fix, even Apple cannot make it work. The workaround you must adopt is having an overall UIViewController that simply sits there and just holds your various views (happyThing, newThing, etc). Hope it helps! |
438 | <p>My Rails-app has a sign in box with a "remember me" checkbox. Users who check that box should remain logged in even after closing their browser. I'm keeping track of whether users are logged in by storing their id in the user's session. </p>
<p>But sessions are implemented in Rails as session cookies, which are not persistent. I can <em>make</em> them persistent:</p>
<pre><code>class ApplicationController < ActionController::Base
before_filter :update_session_expiration_date
private
def update_session_expiration_date
options = ActionController::Base.session_options
unless options[:session_expires]
options[:session_expires] = 1.year.from_now
end
end
end
</code></pre>
<p>But that seems like a hack, which is surprising for such common functionality. Is there any better way?</p>
<p><strong>Edit</strong></p>
<p>Gareth's answer is pretty good, but I would still like an answer from someone familiar with Rails 2 (because of it's unique <code>CookieSessionStore</code>).</p>
| [
{
"answer_id": 483,
"author": "Gareth Simpson",
"author_id": 147,
"author_profile": "https://Stackoverflow.com/users/147",
"pm_score": 5,
"selected": false,
"text": "<p>You should almost certainly not be extending the session cookie to be long lived.</p>\n\n<p>Although not dealing specifically with rails <a href=\"http://fishbowl.pastiche.org/2004/01/19/persistent_login_cookie_best_practice\" rel=\"noreferrer\">this article</a> goes to some length to explain 'remember me' best practices.</p>\n\n<p>In summary though you should:</p>\n\n<ul>\n<li>Add an extra column to the user table to accept a large random value</li>\n<li>Set a long lived cookie on the client which combines the user id and the random value</li>\n<li>When a new session starts, check for the existence of the id/value cookie and authenticate the new user if they match.</li>\n</ul>\n\n<p>The author also recommends invalidating the random value and resetting the cookie at every login. Personally I don't like that as you then can't stay logged into a site on two computers. I would tend to make sure my password changing function also reset the random value thus locking out sessions on other machines. </p>\n\n<p>As a final note, the advice he gives on making certain functions (password change/email change etc) unavailable to auto authenticated sessions is well worth following but rarely seen in the real world.</p>\n"
},
{
"answer_id": 4025,
"author": "Jarin Udom",
"author_id": 574,
"author_profile": "https://Stackoverflow.com/users/574",
"pm_score": 3,
"selected": false,
"text": "<p>The restful_authentication plugin has a good implementation of this: </p>\n\n<p><a href=\"http://agilewebdevelopment.com/plugins/restful_authentication\" rel=\"noreferrer\">http://agilewebdevelopment.com/plugins/restful_authentication</a></p>\n"
},
{
"answer_id": 38481,
"author": "Teflon Ted",
"author_id": 4061,
"author_profile": "https://Stackoverflow.com/users/4061",
"pm_score": 3,
"selected": false,
"text": "<p>Note that you don't want to persist their session, just their identity. You'll create a fresh session for them when they return to your site. Generally you just assign a GUID to the user, write that to their cookie, then use it to look them up when they come back. Don't use their login name or user ID for the token as it could easily be guessed and allow crafty visitors to hijack other users' accounts.</p>\n"
},
{
"answer_id": 77397,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 5,
"selected": true,
"text": "<p>I have spent a while thinking about this and came to some conclusions. Rails session cookies are tamper-proof by default, so you really don't have to worry about a cookie being modified on the client end.</p>\n\n<p>Here is what I've done:</p>\n\n<ul>\n<li>Session cookie is set to be long-lived (6 months or so)</li>\n<li>Inside the session store\n\n<ul>\n<li>An 'expires on' date that is set to login + 24 hours</li>\n<li>user id</li>\n<li>Authenticated = true so I can allow for anonymous user sesssions (not dangerous because of the cookie tamper protection)</li>\n</ul></li>\n<li>I add a before_filter in the Application Controller that checks the 'expires on' part of the session.</li>\n</ul>\n\n<p>When the user checks the \"Remember Me\" box, I just set the session[:expireson] date to be login + 2 weeks. No one can steal the cookie and stay logged in forever or masquerade as another user because the rails session cookie is tamper-proof.</p>\n"
},
{
"answer_id": 83714,
"author": "Mattew",
"author_id": 14787,
"author_profile": "https://Stackoverflow.com/users/14787",
"pm_score": 4,
"selected": false,
"text": "<p>I would suggest that you either take a look at the RESTful_Authentication plug in, which has an implementation of this, or just switch your implementation to use the RESTful Authentication_plugin. There is a good explanation about how to use this plug in at Railscasts:</p>\n\n<p><a href=\"http://railscasts.com/episodes/67-restful-authentication\" rel=\"noreferrer\">railscasts #67 restful_authentication</a></p>\n\n<p>Here is a link to the plugin itself</p>\n\n<p><a href=\"http://rubygems.org/gems/restful_authentication\" rel=\"noreferrer\">restful_authentication</a></p>\n"
},
{
"answer_id": 107677,
"author": "Allan L.",
"author_id": 19527,
"author_profile": "https://Stackoverflow.com/users/19527",
"pm_score": 2,
"selected": false,
"text": "<p>This worked like a charm for me:</p>\n\n<p><a href=\"http://squarewheel.wordpress.com/2007/11/03/session-cookie-expiration-time-in-rails/\" rel=\"nofollow noreferrer\">http://squarewheel.wordpress.com/2007/11/03/session-cookie-expiration-time-in-rails/</a></p>\n\n<p>Now my CookieStore sessions expire after two weeks, whereby the user must submit their login credentials again in order to be persistently logged-in for another two weeks.</p>\n\n<p>Bascially, it's as simple as:</p>\n\n<ol>\n<li>including one file in vendor/plugins directory</li>\n<li>set session expiry value in application controller using just one line</li>\n</ol>\n"
},
{
"answer_id": 4703796,
"author": "Ved",
"author_id": 389197,
"author_profile": "https://Stackoverflow.com/users/389197",
"pm_score": 2,
"selected": false,
"text": "<p>I would go for Devise for a brilliant authentication solution for rails.</p>\n"
}
] | 2008/08/02 | [
"https://Stackoverflow.com/questions/438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136/"
] | My Rails-app has a sign in box with a "remember me" checkbox. Users who check that box should remain logged in even after closing their browser. I'm keeping track of whether users are logged in by storing their id in the user's session.
But sessions are implemented in Rails as session cookies, which are not persistent. I can *make* them persistent:
```
class ApplicationController < ActionController::Base
before_filter :update_session_expiration_date
private
def update_session_expiration_date
options = ActionController::Base.session_options
unless options[:session_expires]
options[:session_expires] = 1.year.from_now
end
end
end
```
But that seems like a hack, which is surprising for such common functionality. Is there any better way?
**Edit**
Gareth's answer is pretty good, but I would still like an answer from someone familiar with Rails 2 (because of it's unique `CookieSessionStore`). | I have spent a while thinking about this and came to some conclusions. Rails session cookies are tamper-proof by default, so you really don't have to worry about a cookie being modified on the client end.
Here is what I've done:
* Session cookie is set to be long-lived (6 months or so)
* Inside the session store
+ An 'expires on' date that is set to login + 24 hours
+ user id
+ Authenticated = true so I can allow for anonymous user sesssions (not dangerous because of the cookie tamper protection)
* I add a before\_filter in the Application Controller that checks the 'expires on' part of the session.
When the user checks the "Remember Me" box, I just set the session[:expireson] date to be login + 2 weeks. No one can steal the cookie and stay logged in forever or masquerade as another user because the rails session cookie is tamper-proof. |
482 | <p>Assume you are doing something like the following</p>
<pre><code>List<string> myitems = new List<string>
{
"Item 1",
"Item 2",
"Item 3"
};
ComboBox box = new ComboBox();
box.DataSource = myitems;
ComboBox box2 = new ComboBox();
box2.DataSource = myitems
</code></pre>
<p>So now we have 2 combo boxes bound to that array, and everything works fine. But when you change the value of one combo box, it changes BOTH combo boxes to the one you just selected.</p>
<p>Now, I know that Arrays are always passed by reference (learned that when i learned C :D), but why on earth would the combo boxes change together? I don't believe the combo box control is modifying the collection at all. </p>
<p>As a workaround, don't this would achieve the functionality that is expected/desired</p>
<pre><code>ComboBox box = new ComboBox();
box.DataSource = myitems.ToArray();
</code></pre>
| [
{
"answer_id": 509,
"author": "Robert Höglund",
"author_id": 143,
"author_profile": "https://Stackoverflow.com/users/143",
"pm_score": 6,
"selected": true,
"text": "<p>This has to do with how data bindings are set up in the dotnet framework, especially the <code>BindingContext</code>. On a high level it means that if you haven't specified otherwise each form and all the controls of the form share the same <code>BindingContext</code>. When you are setting the <code>DataSource</code> property the <code>ComboBox</code> will use the <code>BindingContext</code> to get a <code>ConcurrenyMangager</code> that wraps the list. The <code>ConcurrenyManager</code> keeps track of such things as the current selected position in the list. </p>\n\n<p>When you set the <code>DataSource</code> of the second <code>ComboBox</code> it will use the same <code>BindingContext</code> (the forms) which will yield a reference to the same <code>ConcurrencyManager</code> as above used to set up the data bindings.</p>\n\n<p>To get a more detailed explanation see <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.bindingcontext\" rel=\"nofollow noreferrer\">BindingContext</a>.</p>\n"
},
{
"answer_id": 20142,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 5,
"selected": false,
"text": "<p>A better workaround (depending on the size of the datasource) is to declare two <code>BindingSource</code> objects (new as of 2.00) bind the collection to those and then bind those to the comboboxes.</p>\n\n<p>I enclose a complete example.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication2\n{\n public partial class Form1 : Form\n {\n private BindingSource source1 = new BindingSource();\n private BindingSource source2 = new BindingSource();\n\n public Form1()\n {\n InitializeComponent();\n Load += new EventHandler(Form1Load);\n }\n\n void Form1Load(object sender, EventArgs e)\n {\n List<string> myitems = new List<string>\n {\n \"Item 1\",\n \"Item 2\",\n \"Item 3\"\n };\n\n ComboBox box = new ComboBox();\n box.Bounds = new Rectangle(10, 10, 100, 50);\n source1.DataSource = myitems;\n box.DataSource = source1;\n\n ComboBox box2 = new ComboBox();\n box2.Bounds = new Rectangle(10, 80, 100, 50);\n source2.DataSource = myitems;\n box2.DataSource = source2;\n\n Controls.Add(box);\n Controls.Add(box2);\n }\n }\n}\n</code></pre>\n\n<p>If you want to confuse yourself even more then try always declaring bindings in the constructor. That can result in some <em>really</em> curious bugs, hence I always bind in the Load event.</p>\n"
}
] | 2008/08/02 | [
"https://Stackoverflow.com/questions/482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77/"
] | Assume you are doing something like the following
```
List<string> myitems = new List<string>
{
"Item 1",
"Item 2",
"Item 3"
};
ComboBox box = new ComboBox();
box.DataSource = myitems;
ComboBox box2 = new ComboBox();
box2.DataSource = myitems
```
So now we have 2 combo boxes bound to that array, and everything works fine. But when you change the value of one combo box, it changes BOTH combo boxes to the one you just selected.
Now, I know that Arrays are always passed by reference (learned that when i learned C :D), but why on earth would the combo boxes change together? I don't believe the combo box control is modifying the collection at all.
As a workaround, don't this would achieve the functionality that is expected/desired
```
ComboBox box = new ComboBox();
box.DataSource = myitems.ToArray();
``` | This has to do with how data bindings are set up in the dotnet framework, especially the `BindingContext`. On a high level it means that if you haven't specified otherwise each form and all the controls of the form share the same `BindingContext`. When you are setting the `DataSource` property the `ComboBox` will use the `BindingContext` to get a `ConcurrenyMangager` that wraps the list. The `ConcurrenyManager` keeps track of such things as the current selected position in the list.
When you set the `DataSource` of the second `ComboBox` it will use the same `BindingContext` (the forms) which will yield a reference to the same `ConcurrencyManager` as above used to set up the data bindings.
To get a more detailed explanation see [BindingContext](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.bindingcontext). |
502 | <p>I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF.</p>
<p>On the Mac I am spawning <a href="http://web.archive.org/web/20090309234215/http://developer.apple.com:80/documentation/Darwin/Reference/ManPages/man1/sips.1.html" rel="noreferrer">sips</a>. Is there something similarly simple I can do on Windows?</p>
| [
{
"answer_id": 536,
"author": "Federico Builes",
"author_id": 161,
"author_profile": "https://Stackoverflow.com/users/161",
"pm_score": 4,
"selected": false,
"text": "<p>You can use ImageMagick's convert utility for this, see some examples in <a href=\"https://web.archive.org/web/20120413111338/http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html\" rel=\"noreferrer\">http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html</a>\n:</p>\n\n<blockquote>\n<pre><code>Convert taxes.pdf taxes.jpg \n</code></pre>\n \n <p>Will convert a two page PDF file into [2] jpeg files: taxes.jpg.0,\n taxes.jpg.1</p>\n \n <p>I can also convert these JPEGS to a thumbnail as follows:</p>\n\n<pre><code>convert -size 120x120 taxes.jpg.0 -geometry 120x120 +profile '*' thumbnail.jpg\n</code></pre>\n \n <p>I can even convert the PDF directly to a jpeg thumbnail as follows:</p>\n\n<pre><code>convert -size 120x120 taxes.pdf -geometry 120x120 +profile '*' thumbnail.jpg\n</code></pre>\n \n <p>This will result in a thumbnail.jpg.0 and thumbnail.jpg.1 for the two\n pages.</p>\n</blockquote>\n"
},
{
"answer_id": 7073,
"author": "Dominic Cooney",
"author_id": 878,
"author_profile": "https://Stackoverflow.com/users/878",
"pm_score": 3,
"selected": false,
"text": "<p>Is the PC likely to have Acrobat installed? I think Acrobat installs a shell extension so previews of the first page of a PDF document appear in Windows Explorer's thumbnail view. You can get thumbnails yourself via the IExtractImage COM API, which you'll need to wrap. <a href=\"http://www.vbaccelerator.com/home/net/code/libraries/shell_projects/Thumbnail_Extraction/article.asp\" rel=\"noreferrer\">VBAccelerator has an example in C#</a> that you could port to Python.</p>\n"
},
{
"answer_id": 7090,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 6,
"selected": true,
"text": "<p>ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the <code>ps:alpha</code> delegate in ImageMagick, just adjusted to use JPEG as output):</p>\n\n<pre><code>gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \\\n-dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \\\n-sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72x72 \\\n-sOutputFile=$OUTPUT -f$INPUT\n</code></pre>\n\n<p>where <code>$OUTPUT</code> and <code>$INPUT</code> are the output and input filenames. Adjust the <code>72x72</code> to whatever resolution you need. (Obviously, strip out the backslashes if you're writing out the whole command as one line.)</p>\n\n<p>This is good for two reasons:</p>\n\n<ol>\n<li>You don't need to have ImageMagick installed anymore. Not that I have anything against ImageMagick (I love it to bits), but I believe in simple solutions.</li>\n<li>ImageMagick does a two-step conversion. First PDF->PPM, then PPM->JPEG. This way, the conversion is one-step.</li>\n</ol>\n\n<p>Other things to consider: with the files I've tested, PNG compresses better than JPEG. If you want to use PNG, change the <code>-sDEVICE=jpeg</code> to <code>-sDEVICE=png16m</code>.</p>\n"
}
] | 2008/08/02 | [
"https://Stackoverflow.com/questions/502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147/"
] | I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF.
On the Mac I am spawning [sips](http://web.archive.org/web/20090309234215/http://developer.apple.com:80/documentation/Darwin/Reference/ManPages/man1/sips.1.html). Is there something similarly simple I can do on Windows? | ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the `ps:alpha` delegate in ImageMagick, just adjusted to use JPEG as output):
```
gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \
-dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \
-sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72x72 \
-sOutputFile=$OUTPUT -f$INPUT
```
where `$OUTPUT` and `$INPUT` are the output and input filenames. Adjust the `72x72` to whatever resolution you need. (Obviously, strip out the backslashes if you're writing out the whole command as one line.)
This is good for two reasons:
1. You don't need to have ImageMagick installed anymore. Not that I have anything against ImageMagick (I love it to bits), but I believe in simple solutions.
2. ImageMagick does a two-step conversion. First PDF->PPM, then PPM->JPEG. This way, the conversion is one-step.
Other things to consider: with the files I've tested, PNG compresses better than JPEG. If you want to use PNG, change the `-sDEVICE=jpeg` to `-sDEVICE=png16m`. |
561 | <p>I would like to test a function with a tuple from a set of fringe cases and normal values. For example, while testing a function which returns <code>true</code> whenever given three lengths that form a valid triangle, I would have specific cases, negative / small / large numbers, values close-to being overflowed, etc.; what is more, main aim is to generate combinations of these values, <em>with</em> or <em>without</em> repetition, in order to get a set of test data.</p>
<pre><code>(inf,0,-1), (5,10,1000), (10,5,5), (0,-1,5), (1000,inf,inf),
...
</code></pre>
<blockquote>
<p><em>As a note: I actually know the answer to this, but it might be helpful for others, and a challenge for people here! --will post my answer later on.</em></p>
</blockquote>
| [
{
"answer_id": 589,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "<p>Interesting question!</p>\n\n<p>I would do this by picking combinations, something like the following in python. The hardest part is probably first pass verification, i.e. <code>if f(1,2,3) returns true</code>, is that a correct result? Once you have verified that, then this is a good basis for regression testing.</p>\n\n<p>Probably it's a good idea to make a set of test cases that you know will be all true (e.g. 3,4,5 for this triangle case), and a set of test cases that you know will be all false (e.g. 0,1,inf). Then you can more easily verify the tests are correct.</p>\n\n<pre>\n# xpermutations from http://code.activestate.com/recipes/190465\nfrom xpermutations import *\n\nlengths=[-1,0,1,5,10,0,1000,'inf']\nfor c in xselections(lengths,3): # or xuniqueselections\n print c\n</pre>\n\n<pre>\n(-1,-1,-1);\n(-1,-1,0);\n(-1,-1,1);\n(-1,-1,5);\n(-1,-1,10);\n(-1,-1,0);\n(-1,-1,1000);\n(-1,-1,inf);\n(-1,0,-1);\n(-1,0,0);\n...\n</pre>\n"
},
{
"answer_id": 794,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 5,
"selected": true,
"text": "<p>Absolutely, especially dealing with lots of these permutations/combinations I can definitely see that the first pass would be an issue.</p>\n\n<p>Interesting implementation in python, though I wrote a nice one in C and Ocaml based on \"Algorithm 515\" (see below). He wrote his in Fortran as it was common back then for all the \"Algorithm XX\" papers, well, that assembly or c. I had to re-write it and make some small improvements to work with arrays not ranges of numbers. This one does random access, I'm still working on getting some nice implementations of the ones mentioned in Knuth 4th volume fascicle 2. I'll an explanation of how this works to the reader. Though if someone is curious, I wouldn't object to writing something up.</p>\n\n<pre><code>/** [combination c n p x]\n * get the [x]th lexicographically ordered set of [p] elements in [n]\n * output is in [c], and should be sizeof(int)*[p] */\nvoid combination(int* c,int n,int p, int x){\n int i,r,k = 0;\n for(i=0;i<p-1;i++){\n c[i] = (i != 0) ? c[i-1] : 0;\n do {\n c[i]++;\n r = choose(n-c[i],p-(i+1));\n k = k + r;\n } while(k < x);\n k = k - r;\n }\n c[p-1] = c[p-2] + x - k;\n}\n</code></pre>\n\n<p>~\"Algorithm 515: Generation of a Vector from the Lexicographical Index\"; Buckles, B. P., and Lybanon, M. ACM Transactions on Mathematical Software, Vol. 3, No. 2, June 1977.</p>\n"
},
{
"answer_id": 13123,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>I think you can do this with the <a href=\"http://blog.donnfelker.com/2008/04/01/NUnit247AndTheRowTestAttributeWithExample.aspx\" rel=\"nofollow noreferrer\">Row Test Attribute</a> (available in MbUnit and later versions of NUnit) where you could specify several sets to populate one unit test.</p>\n"
},
{
"answer_id": 79583,
"author": "not-bob",
"author_id": 14770,
"author_profile": "https://Stackoverflow.com/users/14770",
"pm_score": 0,
"selected": false,
"text": "<p>While it's possible to create lots of test data and see what happens, it's more efficient to try to minimize the data being used.</p>\n\n<p>From a typical QA perspective, you would want to identify different classifications of inputs. Produce a set of input values for each classification and determine the appropriate outputs. </p>\n\n<p>Here's a sample of classes of input values</p>\n\n<ul>\n<li>valid triangles with small numbers such as (1 billion, 2, billion, 2 billion)</li>\n<li>valid triangles with large numbers such as (0.000001, 0.00002, 0.00003)</li>\n<li>valid obtuse triangles that are 'almost'flat such as (10, 10, 19.9999)</li>\n<li>valid acute triangles that are 'almost' flat such as (10, 10, 0000001)</li>\n<li>invalid triangles with at least one negative value</li>\n<li>invalid triangles where the sum of two sides equals the third</li>\n<li>invalid triangles where the sum of two sides is greater than the third</li>\n<li>input values that are non-numeric</li>\n</ul>\n\n<p>...</p>\n\n<p>Once you are satisfied with the list of input classifications for this function, then you can create the actual test data. Likely, it would be helpful to test all permutations of each item. (e.g. (2,3,4), (2,4,3), (3,2,4), (3,4,2), (4,2,3), (4,3,2)) Typically, you'll find there are some classifications you missed (such as the concept of inf as an input parameter).</p>\n\n<p>Random data for some period of time may be helpful as well, that can find strange bugs in the code, but is generally not productive.</p>\n\n<p>More likely, this function is being used in some specific context where additional rules are applied.(e.g. only integer values or values must be in 0.01 increments, etc.) These add to the list of classifications of input parameters.</p>\n"
},
{
"answer_id": 170010,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 2,
"selected": false,
"text": "<p>With the brand new Python 2.6, you have a standard solution with the itertools module that returns the Cartesian product of iterables :</p>\n\n<pre><code>import itertools\n\nprint list(itertools.product([1,2,3], [4,5,6]))\n [(1, 4), (1, 5), (1, 6),\n (2, 4), (2, 5), (2, 6),\n (3, 4), (3, 5), (3, 6)]\n</code></pre>\n\n<p>You can provide a \"repeat\" argument to perform the product with an iterable and itself:</p>\n\n<pre><code>print list(itertools.product([1,2], repeat=3))\n[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),\n(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]\n</code></pre>\n\n<p>You can also tweak something with combinations as well :</p>\n\n<pre><code>print list(itertools.combinations('123', 2))\n[('1', '2'), ('1', '3'), ('2', '3')]\n</code></pre>\n\n<p>And if order matters, there are permutations :</p>\n\n<pre><code>print list(itertools.permutations([1,2,3,4], 2))\n[(1, 2), (1, 3), (1, 4),\n (2, 1), (2, 3), (2, 4),\n (3, 1), (3, 2), (3, 4),\n (4, 1), (4, 2), (4, 3)]\n</code></pre>\n\n<p>Of course all that cool stuff don't exactly do the same thing, but you can use them in a way or another to solve you problem. </p>\n\n<p>Just remember that you can convert a tuple or a list to a set and vice versa using list(), tuple() and set().</p>\n"
}
] | 2008/08/02 | [
"https://Stackoverflow.com/questions/561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157/"
] | I would like to test a function with a tuple from a set of fringe cases and normal values. For example, while testing a function which returns `true` whenever given three lengths that form a valid triangle, I would have specific cases, negative / small / large numbers, values close-to being overflowed, etc.; what is more, main aim is to generate combinations of these values, *with* or *without* repetition, in order to get a set of test data.
```
(inf,0,-1), (5,10,1000), (10,5,5), (0,-1,5), (1000,inf,inf),
...
```
>
> *As a note: I actually know the answer to this, but it might be helpful for others, and a challenge for people here! --will post my answer later on.*
>
>
> | Absolutely, especially dealing with lots of these permutations/combinations I can definitely see that the first pass would be an issue.
Interesting implementation in python, though I wrote a nice one in C and Ocaml based on "Algorithm 515" (see below). He wrote his in Fortran as it was common back then for all the "Algorithm XX" papers, well, that assembly or c. I had to re-write it and make some small improvements to work with arrays not ranges of numbers. This one does random access, I'm still working on getting some nice implementations of the ones mentioned in Knuth 4th volume fascicle 2. I'll an explanation of how this works to the reader. Though if someone is curious, I wouldn't object to writing something up.
```
/** [combination c n p x]
* get the [x]th lexicographically ordered set of [p] elements in [n]
* output is in [c], and should be sizeof(int)*[p] */
void combination(int* c,int n,int p, int x){
int i,r,k = 0;
for(i=0;i<p-1;i++){
c[i] = (i != 0) ? c[i-1] : 0;
do {
c[i]++;
r = choose(n-c[i],p-(i+1));
k = k + r;
} while(k < x);
k = k - r;
}
c[p-1] = c[p-2] + x - k;
}
```
~"Algorithm 515: Generation of a Vector from the Lexicographical Index"; Buckles, B. P., and Lybanon, M. ACM Transactions on Mathematical Software, Vol. 3, No. 2, June 1977. |
594 | <p>There are several ways to iterate over a result set. What are the tradeoff of each?</p>
| [
{
"answer_id": 595,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 7,
"selected": true,
"text": "<p>The canonical way is to use the built-in cursor iterator.</p>\n\n<pre><code>curs.execute('select * from people')\nfor row in curs:\n print row\n</code></pre>\n\n<hr>\n\n<p>You can use <code>fetchall()</code> to get all rows at once.</p>\n\n<pre><code>for row in curs.fetchall():\n print row\n</code></pre>\n\n<p>It can be convenient to use this to create a Python list containing the values returned:</p>\n\n<pre><code>curs.execute('select first_name from people')\nnames = [row[0] for row in curs.fetchall()]\n</code></pre>\n\n<p>This can be useful for smaller result sets, but can have bad side effects if the result set is large.</p>\n\n<ul>\n<li><p>You have to wait for the entire result set to be returned to\nyour client process.</p></li>\n<li><p>You may eat up a lot of memory in your client to hold\nthe built-up list.</p></li>\n<li><p>It may take a while for Python to construct and deconstruct the\nlist which you are going to immediately discard anyways.</p></li>\n</ul>\n\n<hr>\n\n<p>If you know there's a single row being returned in the result set you can call <code>fetchone()</code> to get the single row.</p>\n\n<pre><code>curs.execute('select max(x) from t')\nmaxValue = curs.fetchone()[0]\n</code></pre>\n\n<hr>\n\n<p>Finally, you can loop over the result set fetching one row at a time. In general, there's no particular advantage in doing this over using the iterator.</p>\n\n<pre><code>row = curs.fetchone()\nwhile row:\n print row\n row = curs.fetchone()\n</code></pre>\n"
},
{
"answer_id": 25213,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 3,
"selected": false,
"text": "<p>There's also the way <code>psyco-pg</code> seems to do it... From what I gather, it seems to create dictionary-like row-proxies to map key lookup into the memory block returned by the query. In that case, fetching the whole answer and working with a similar proxy-factory over the rows seems like useful idea. Come to think of it though, it feels more like Lua than Python.</p>\n\n<p>Also, this should be applicable to all <a href=\"http://www.python.org/dev/peps/pep-0249/\" rel=\"noreferrer\">PEP-249 DBAPI2.0</a> interfaces, not just Oracle, or did you mean just <em>fastest</em> using <em>Oracle</em>?</p>\n"
},
{
"answer_id": 125140,
"author": "Aurelio Martin Massoni",
"author_id": 20037,
"author_profile": "https://Stackoverflow.com/users/20037",
"pm_score": 5,
"selected": false,
"text": "<p>My preferred way is the cursor iterator, but setting first the arraysize property of the cursor. </p>\n\n<pre><code>curs.execute('select * from people')\ncurs.arraysize = 256\nfor row in curs:\n print row\n</code></pre>\n\n<p>In this example, cx_Oracle will fetch rows from Oracle 256 rows at a time, reducing the number of network round trips that need to be performed</p>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | There are several ways to iterate over a result set. What are the tradeoff of each? | The canonical way is to use the built-in cursor iterator.
```
curs.execute('select * from people')
for row in curs:
print row
```
---
You can use `fetchall()` to get all rows at once.
```
for row in curs.fetchall():
print row
```
It can be convenient to use this to create a Python list containing the values returned:
```
curs.execute('select first_name from people')
names = [row[0] for row in curs.fetchall()]
```
This can be useful for smaller result sets, but can have bad side effects if the result set is large.
* You have to wait for the entire result set to be returned to
your client process.
* You may eat up a lot of memory in your client to hold
the built-up list.
* It may take a while for Python to construct and deconstruct the
list which you are going to immediately discard anyways.
---
If you know there's a single row being returned in the result set you can call `fetchone()` to get the single row.
```
curs.execute('select max(x) from t')
maxValue = curs.fetchone()[0]
```
---
Finally, you can loop over the result set fetching one row at a time. In general, there's no particular advantage in doing this over using the iterator.
```
row = curs.fetchone()
while row:
print row
row = curs.fetchone()
``` |
626 | <p>In Ruby 1.8, there are subtle differences between proc/lambda on the one hand, and <code>Proc.new</code> on the other. </p>
<ul>
<li>What are those differences?</li>
<li>Can you give guidelines on how to decide which one to choose?</li>
<li>In Ruby 1.9, proc and lambda are different. What's the deal?</li>
</ul>
| [
{
"answer_id": 629,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 5,
"selected": false,
"text": "<p>I found <a href=\"http://raulparolari.com/Ruby2/lambda_Proc\" rel=\"noreferrer\">this page</a> which shows what the difference between <code>Proc.new</code> and <code>lambda</code> are. According to the page, the only difference is that a lambda is strict about the number of arguments it accepts, whereas <code>Proc.new</code> converts missing arguments to <code>nil</code>. Here is an example IRB session illustrating the difference:</p>\n\n<pre>irb(main):001:0> l = lambda { |x, y| x + y }\n=> #<Proc:0x00007fc605ec0748@(irb):1>\nirb(main):002:0> p = Proc.new { |x, y| x + y }\n=> #<Proc:0x00007fc605ea8698@(irb):2>\nirb(main):003:0> l.call \"hello\", \"world\"\n=> \"helloworld\"\nirb(main):004:0> p.call \"hello\", \"world\"\n=> \"helloworld\"\nirb(main):005:0> l.call \"hello\"\nArgumentError: wrong number of arguments (1 for 2)\n from (irb):1\n from (irb):5:in `call'\n from (irb):5\n from :0\nirb(main):006:0> p.call \"hello\"\nTypeError: can't convert nil into String\n from (irb):2:in `+'\n from (irb):2\n from (irb):6:in `call'\n from (irb):6\n from :0</pre>\n\n<p>The page also recommends using lambda unless you specifically want the error tolerant behavior. I agree with this sentiment. Using a lambda seems a tad more concise, and with such an insignificant difference, it seems the better choice in the average situation.</p>\n\n<p>As for Ruby 1.9, sorry, I haven't looked into 1.9 yet, but I don't imagine they would change it all that much (don't take my word for it though, it seems you have heard of some changes, so I am probably wrong there).</p>\n"
},
{
"answer_id": 723,
"author": "Joey deVilla",
"author_id": 216,
"author_profile": "https://Stackoverflow.com/users/216",
"pm_score": 10,
"selected": true,
"text": "<p>Another important but subtle difference between procs created with <code>lambda</code> and procs created with <code>Proc.new</code> is how they handle the <code>return</code> statement:</p>\n\n<ul>\n<li>In a <code>lambda</code>-created proc, the <code>return</code> statement returns only from the proc itself</li>\n<li>In a <code>Proc.new</code>-created proc, the <code>return</code> statement is a little more surprising: it returns control not just from the proc, <strong>but also from the method enclosing the proc!</strong></li>\n</ul>\n\n<p>Here's <code>lambda</code>-created proc's <code>return</code> in action. It behaves in a way that you probably expect:</p>\n\n<pre><code>def whowouldwin\n\n mylambda = lambda {return \"Freddy\"}\n mylambda.call\n\n # mylambda gets called and returns \"Freddy\", and execution\n # continues on the next line\n\n return \"Jason\"\n\nend\n\n\nwhowouldwin\n#=> \"Jason\"\n</code></pre>\n\n<p>Now here's a <code>Proc.new</code>-created proc's <code>return</code> doing the same thing. You're about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise:</p>\n\n<pre><code>def whowouldwin2\n\n myproc = Proc.new {return \"Freddy\"}\n myproc.call\n\n # myproc gets called and returns \"Freddy\", \n # but also returns control from whowhouldwin2!\n # The line below *never* gets executed.\n\n return \"Jason\"\n\nend\n\n\nwhowouldwin2 \n#=> \"Freddy\"\n</code></pre>\n\n<p>Thanks to this surprising behavior (as well as less typing), I tend to favor using <code>lambda</code> over <code>Proc.new</code> when making procs.</p>\n"
},
{
"answer_id": 7484,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<p>The difference in behaviour with <code>return</code> is IMHO the most important difference between the 2. I also prefer lambda because it's less typing than Proc.new :-)</p>\n"
},
{
"answer_id": 32329,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://innig.net/software/ruby/closures-in-ruby.html\" rel=\"nofollow noreferrer\">Closures in Ruby</a> is a good overview for how blocks, lambda and proc work in Ruby, with Ruby. </p>\n"
},
{
"answer_id": 48054,
"author": "Peeja",
"author_id": 4937,
"author_profile": "https://Stackoverflow.com/users/4937",
"pm_score": 2,
"selected": false,
"text": "<p>To elaborate on Accordion Guy's response:</p>\n\n<p>Notice that <code>Proc.new</code> creates a proc out by being passed a block. I believe that <code>lambda {...}</code> is parsed as a sort of literal, rather than a method call which passes a block. <code>return</code>ing from inside a block attached to a method call will return from the method, not the block, and the <code>Proc.new</code> case is an example of this at play.</p>\n\n<p>(This is 1.8. I don't know how this translates to 1.9.)</p>\n"
},
{
"answer_id": 55491,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Proc is older, but the semantics of return are highly counterintuitive to me (at least when I was learning the language) because:</p>\n\n<ol>\n<li>If you are using proc, you are most likely using some kind of functional paradigm. </li>\n<li>Proc can return out of the enclosing scope (see previous responses), which is a goto basically, and highly non-functional in nature.</li>\n</ol>\n\n<p>Lambda is functionally safer and easier to reason about - I always use it instead of proc.</p>\n"
},
{
"answer_id": 303428,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 4,
"selected": false,
"text": "<p>I can't say much about the subtle differences. However, I can point out that Ruby 1.9 now allows optional parameters for lambdas and blocks.</p>\n\n<p>Here's the new syntax for the stabby lambdas under 1.9:</p>\n\n<pre><code>stabby = ->(msg='inside the stabby lambda') { puts msg }\n</code></pre>\n\n<p>Ruby 1.8 didn't have that syntax. Neither did the conventional way of declaring blocks/lambdas support optional args:</p>\n\n<pre><code># under 1.8\nl = lambda { |msg = 'inside the stabby lambda'| puts msg }\nSyntaxError: compile error\n(irb):1: syntax error, unexpected '=', expecting tCOLON2 or '[' or '.'\nl = lambda { |msg = 'inside the stabby lambda'| puts msg }\n</code></pre>\n\n<p>Ruby 1.9, however, supports optional arguments even with the old syntax:</p>\n\n<pre><code>l = lambda { |msg = 'inside the regular lambda'| puts msg }\n#=> #<Proc:0x0e5dbc@(irb):1 (lambda)>\nl.call\n#=> inside the regular lambda\nl.call('jeez')\n#=> jeez\n</code></pre>\n\n<p>If you wanna build Ruby1.9 for Leopard or Linux, check out <a href=\"http://programblings.com/2008/11/18/installing-ruby-19preview1-on-os-x-leopard/\" rel=\"noreferrer\">this article</a> (shameless self promotion).</p>\n"
},
{
"answer_id": 352857,
"author": "krusty.ar",
"author_id": 43981,
"author_profile": "https://Stackoverflow.com/users/43981",
"pm_score": 4,
"selected": false,
"text": "<p>A good way to see it is that lambdas are executed in their own scope (as if it was a method call), while Procs may be viewed as executed inline with the calling method, at least that's a good way of deciding wich one to use in each case.</p>\n"
},
{
"answer_id": 1043390,
"author": "Dave Rapin",
"author_id": 34210,
"author_profile": "https://Stackoverflow.com/users/34210",
"pm_score": 3,
"selected": false,
"text": "<p>I didn't notice any comments on the third method in the queston, \"proc\" which is deprecated, but handled differently in 1.8 and 1.9.</p>\n\n<p>Here's a fairly verbose example that makes it easy to see the differences between the three similar calls:</p>\n\n<pre><code>def meth1\n puts \"method start\"\n\n pr = lambda { return }\n pr.call\n\n puts \"method end\" \nend\n\ndef meth2\n puts \"method start\"\n\n pr = Proc.new { return }\n pr.call\n\n puts \"method end\" \nend\n\ndef meth3\n puts \"method start\"\n\n pr = proc { return }\n pr.call\n\n puts \"method end\" \nend\n\nputs \"Using lambda\"\nmeth1\nputs \"--------\"\nputs \"using Proc.new\"\nmeth2\nputs \"--------\"\nputs \"using proc\"\nmeth3\n</code></pre>\n"
},
{
"answer_id": 1515670,
"author": "Peter Wagenet",
"author_id": 181916,
"author_profile": "https://Stackoverflow.com/users/181916",
"pm_score": 7,
"selected": false,
"text": "<p>To provide further clarification:</p>\n\n<p>Joey says that the return behavior of <code>Proc.new</code> is surprising. However when you consider that Proc.new behaves like a block this is not surprising as that is exactly how blocks behave. lambas on the other hand behave more like methods.</p>\n\n<p>This actually explains why Procs are flexible when it comes to arity (number of arguments) whereas lambdas are not. Blocks don't require all their arguments to be provided but methods do (unless a default is provided). While providing lambda argument default is not an option in Ruby 1.8, it is now supported in Ruby 1.9 with the alternative lambda syntax (as noted by webmat):</p>\n\n<pre><code>concat = ->(a, b=2){ \"#{a}#{b}\" }\nconcat.call(4,5) # => \"45\"\nconcat.call(1) # => \"12\"\n</code></pre>\n\n<p>And Michiel de Mare (the OP) is incorrect about the Procs and lambda behaving the same with arity in Ruby 1.9. I have verified that they still maintain the behavior from 1.8 as specified above.</p>\n\n<p><code>break</code> statements don't actually make much sense in either Procs or lambdas. In Procs, the break would return you from Proc.new which has already been completed. And it doesn't make any sense to break from a lambda since it's essentially a method, and you would never break from the top level of a method.</p>\n\n<p><code>next</code>, <code>redo</code>, and <code>raise</code> behave the same in both Procs and lambdas. Whereas <code>retry</code> is not allowed in either and will raise an exception.</p>\n\n<p>And finally, the <code>proc</code> method should never be used as it is inconsistent and has unexpected behavior. In Ruby 1.8 it actually returns a lambda! In Ruby 1.9 this has been fixed and it returns a Proc. If you want to create a Proc, stick with <code>Proc.new</code>.</p>\n\n<p>For more information, I highly recommend O'Reilly's <em>The Ruby Programming Language</em> which is my source for most of this information.</p>\n"
},
{
"answer_id": 7678836,
"author": "Evan Moran",
"author_id": 47593,
"author_profile": "https://Stackoverflow.com/users/47593",
"pm_score": 4,
"selected": false,
"text": "<p>Short answer: What matters is what <code>return</code> does: lambda returns out of itself, and proc returns out of itself AND the function that called it. </p>\n\n<p>What is less clear is why you want to use each. lambda is what we expect things should do in a functional programming sense. It is basically an anonymous method with the current scope automatically bound. Of the two, lambda is the one you should probably be using.</p>\n\n<p>Proc, on the other hand, is really useful for implementing the language itself. For example you can implement \"if\" statements or \"for\" loops with them. Any return found in the proc will return out of the method that called it, not the just the \"if\" statement. This is how languages work, how \"if\" statements work, so my guess is Ruby uses this under the covers and they just exposed it because it seemed powerful.</p>\n\n<p>You would only really need this if you are creating new language constructs like loops, if-else constructs, etc.</p>\n"
},
{
"answer_id": 26635646,
"author": "weakish",
"author_id": 222893,
"author_profile": "https://Stackoverflow.com/users/222893",
"pm_score": 3,
"selected": false,
"text": "<p>lambda works as expected, like in other languages.</p>\n\n<p>The wired <code>Proc.new</code> is surprising and confusing.</p>\n\n<p>The <code>return</code> statement in proc created by <code>Proc.new</code> will not only return control just from itself, but <em>also from the method enclosing it</em>.</p>\n\n<pre><code>def some_method\n myproc = Proc.new {return \"End.\"}\n myproc.call\n\n # Any code below will not get executed!\n # ...\nend\n</code></pre>\n\n<p>You can argue that <code>Proc.new</code> inserts code into the enclosing method, just like block.\nBut <code>Proc.new</code> creates an object, while block are <em>part of</em> an object.</p>\n\n<p>And there is another difference between lambda and <code>Proc.new</code>, which is their handling of (wrong) arguments.\nlambda complains about it, while <code>Proc.new</code> ignores extra arguments or considers the absence of arguments as nil.</p>\n\n<pre><code>irb(main):021:0> l = -> (x) { x.to_s }\n=> #<Proc:0x8b63750@(irb):21 (lambda)>\nirb(main):022:0> p = Proc.new { |x| x.to_s}\n=> #<Proc:0x8b59494@(irb):22>\nirb(main):025:0> l.call\nArgumentError: wrong number of arguments (0 for 1)\n from (irb):21:in `block in irb_binding'\n from (irb):25:in `call'\n from (irb):25\n from /usr/bin/irb:11:in `<main>'\nirb(main):026:0> p.call\n=> \"\"\nirb(main):049:0> l.call 1, 2\nArgumentError: wrong number of arguments (2 for 1)\n from (irb):47:in `block in irb_binding'\n from (irb):49:in `call'\n from (irb):49\n from /usr/bin/irb:11:in `<main>'\nirb(main):050:0> p.call 1, 2\n=> \"1\"\n</code></pre>\n\n<p>BTW, <code>proc</code> in Ruby 1.8 creates a lambda, while in Ruby 1.9+ behaves like <code>Proc.new</code>, which is really confusing.</p>\n"
},
{
"answer_id": 29920634,
"author": "Aleksei Matiushkin",
"author_id": 2035262,
"author_profile": "https://Stackoverflow.com/users/2035262",
"pm_score": 2,
"selected": false,
"text": "<p>I am a bit late on this, but there is one great but little known thing about <code>Proc.new</code> not mentioned in comments at all. As by <a href=\"http://ruby-doc.org/core-2.2.1/Proc.html#method-c-new\" rel=\"nofollow\">documentation</a>:</p>\n\n<blockquote>\n <p><code>Proc::new</code> may be called without a block only within a method with an attached block, in which case that <strong>block is converted to the <code>Proc</code></strong> object.</p>\n</blockquote>\n\n<p>That said, <code>Proc.new</code> lets to chain yielding methods:</p>\n\n<pre><code>def m1\n yield 'Finally!' if block_given?\nend\n\ndef m2\n m1 &Proc.new\nend\n\nm2 { |e| puts e } \n#⇒ Finally!\n</code></pre>\n"
},
{
"answer_id": 53316814,
"author": "ComDubh",
"author_id": 1445986,
"author_profile": "https://Stackoverflow.com/users/1445986",
"pm_score": 2,
"selected": false,
"text": "<p>It's worth emphasizing that <code>return</code> in a proc returns from the lexically enclosing method, i.e. <em>the method where the proc was created</em>, <strong>not</strong> the method that called the proc. This is a consequence of the closure property of procs. So the following code outputs nothing:</p>\n\n<pre><code>def foo\n proc = Proc.new{return}\n foobar(proc)\n puts 'foo'\nend\n\ndef foobar(proc)\n proc.call\n puts 'foobar'\nend\n\nfoo\n</code></pre>\n\n<p>Although the proc executes in <code>foobar</code>, it was created in <code>foo</code> and so the <code>return</code> exits <code>foo</code>, not just <code>foobar</code>. As Charles Caldwell wrote above, it has a GOTO feel to it. In my opinion, <code>return</code> is fine in a block that is executed in its lexical context, but is much less intuitive when used in a proc that is executed in a different context.</p>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136/"
] | In Ruby 1.8, there are subtle differences between proc/lambda on the one hand, and `Proc.new` on the other.
* What are those differences?
* Can you give guidelines on how to decide which one to choose?
* In Ruby 1.9, proc and lambda are different. What's the deal? | Another important but subtle difference between procs created with `lambda` and procs created with `Proc.new` is how they handle the `return` statement:
* In a `lambda`-created proc, the `return` statement returns only from the proc itself
* In a `Proc.new`-created proc, the `return` statement is a little more surprising: it returns control not just from the proc, **but also from the method enclosing the proc!**
Here's `lambda`-created proc's `return` in action. It behaves in a way that you probably expect:
```
def whowouldwin
mylambda = lambda {return "Freddy"}
mylambda.call
# mylambda gets called and returns "Freddy", and execution
# continues on the next line
return "Jason"
end
whowouldwin
#=> "Jason"
```
Now here's a `Proc.new`-created proc's `return` doing the same thing. You're about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise:
```
def whowouldwin2
myproc = Proc.new {return "Freddy"}
myproc.call
# myproc gets called and returns "Freddy",
# but also returns control from whowhouldwin2!
# The line below *never* gets executed.
return "Jason"
end
whowouldwin2
#=> "Freddy"
```
Thanks to this surprising behavior (as well as less typing), I tend to favor using `lambda` over `Proc.new` when making procs. |
650 | <p>I would like the version property of my application to be incremented for each build but I'm not sure on how to enable this functionality in Visual Studio (2005/2008). I have tried to specify the AssemblyVersion as 1.0.* but it doesn't get me exactly what I want. </p>
<p>I'm also using a settings file and in earlier attempts when the assembly version changed my settings got reset to the default since the application looked for the settings file in another directory. </p>
<p>I would like to be able to display a version number in the form of 1.1.38 so when a user finds a problem I can log the version they are using as well as tell them to upgrade if they have an old release.</p>
<p>A short explanation of how the versioning works would also be appreciated. When does the build and revision number get incremented?</p>
| [
{
"answer_id": 655,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 8,
"selected": true,
"text": "<p>With the \"Built in\" stuff, you can't, as using 1.0.* or 1.0.0.* will replace the revision and build numbers with a coded date/timestamp, which is usually also a good way. </p>\n\n<p>For more info, see the <a href=\"http://msdn2.microsoft.com/en-us/library/c405shex(vs.80).aspx\" rel=\"noreferrer\">Assembly Linker</a> Documentation in the /v tag.</p>\n\n<p>As for automatically incrementing numbers, use the AssemblyInfo Task:</p>\n\n<p><a href=\"http://code.msdn.microsoft.com/AssemblyInfoTaskvers\" rel=\"noreferrer\">AssemblyInfo Task</a></p>\n\n<p>This can be configured to automatically increment the build number.</p>\n\n<p>There are 2 Gotchas:</p>\n\n<ol>\n<li>Each of the 4 numbers in the Version string is limited to 65535. This is a Windows Limitation and unlikely to get fixed.\n\n<ul>\n<li><a href=\"http://blogs.msdn.com/msbuild/archive/2007/01/03/why-are-build-numbers-limited-to-65535.aspx\" rel=\"noreferrer\">Why are build numbers limited to 65535?</a></li>\n</ul></li>\n<li>Using with with Subversion requires a small change:\n\n<ul>\n<li><a href=\"http://www.andrewconnell.com/blog/archive/2006/08/29/4078.aspx\" rel=\"noreferrer\">Using MSBuild to generate assembly version info at build time (including SubVersion fix)</a></li>\n</ul></li>\n</ol>\n\n<p>Retrieving the Version number is then quite easy:</p>\n\n<pre><code>Version v = Assembly.GetExecutingAssembly().GetName().Version;\nstring About = string.Format(CultureInfo.InvariantCulture, @\"YourApp Version {0}.{1}.{2} (r{3})\", v.Major, v.Minor, v.Build, v.Revision);\n</code></pre>\n\n<hr>\n\n<p>And, to clarify: In .net or at least in C#, the build is actually the THIRD number, not the fourth one as some people (for example Delphi Developers who are used to Major.Minor.Release.Build) might expect.</p>\n\n<p>In .net, it's Major.Minor.Build.Revision.</p>\n"
},
{
"answer_id": 787,
"author": "engtech",
"author_id": 175,
"author_profile": "https://Stackoverflow.com/users/175",
"pm_score": 3,
"selected": false,
"text": "<p>What source control system are you using? </p>\n\n<p>Almost all of them have some form of $ Id $ tag that gets expanded when the file is checked in.</p>\n\n<p>I usually use some form of hackery to display this as the version number.</p>\n\n<p>The other alternative is use to use the date as the build number: 080803-1448</p>\n"
},
{
"answer_id": 1550,
"author": "caryden",
"author_id": 313,
"author_profile": "https://Stackoverflow.com/users/313",
"pm_score": 1,
"selected": false,
"text": "<p>Some time ago I wrote a quick and dirty exe that would update the version #'s in an assemblyinfo.{cs/vb} - I also have used rxfind.exe (a simple and powerful regex-based search replace tool) to do the update from a command line as part of the build process. A couple of other helpfule hints:</p>\n\n<ol>\n<li>separate the assemblyinfo into product parts (company name, version, etc.) and assembly specific parts (assembly name etc.). See <a href=\"http://blog.darrenstokes.com/2007/12/17/ease-versioning-multiple-assemblies-by-splitting-up-assemblyinfo/\" rel=\"nofollow noreferrer\">here</a></li>\n<li>Also - i use subversion, so I found it helpful to set the build number to subversion revision number thereby making it really easy to always get back to the codebase that generated the assembly (e.g. 1.4.100.1502 was built from revision 1502).</li>\n</ol>\n"
},
{
"answer_id": 155067,
"author": "Solracnapod",
"author_id": 8900,
"author_profile": "https://Stackoverflow.com/users/8900",
"pm_score": 4,
"selected": false,
"text": "<p>VS.NET defaults the Assembly version to 1.0.* and uses the following logic when auto-incrementing: it sets the build part to the number of days since January 1st, 2000, and sets the revision part to the number of seconds since midnight, local time, divided by two. See this <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.assemblyversionattribute.aspx\" rel=\"noreferrer\">MSDN article</a>.</p>\n\n<p>Assembly version is located in an assemblyinfo.vb or assemblyinfo.cs file. From the file: </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>' Version information for an assembly consists of the following four values:\n'\n' Major Version\n' Minor Version \n' Build Number\n' Revision\n'\n' You can specify all the values or you can default the Build and Revision Numbers \n' by using the '*' as shown below:\n' <Assembly: AssemblyVersion(\"1.0.*\")> \n\n<Assembly: AssemblyVersion(\"1.0.0.0\")> \n<Assembly: AssemblyFileVersion(\"1.0.0.0\")> \n</code></pre>\n"
},
{
"answer_id": 2352703,
"author": "user283258",
"author_id": 283258,
"author_profile": "https://Stackoverflow.com/users/283258",
"pm_score": 0,
"selected": false,
"text": "<p>If you want an auto incrementing number that updates each time a compilation is done, you can use <a href=\"http://testdox.wordpress.com/versionupdater/\" rel=\"nofollow noreferrer\">VersionUpdater</a> from a pre-build event. Your pre-build event can check the build configuration if you prefer so that the version number will only increment for a Release build (for example).</p>\n"
},
{
"answer_id": 15211000,
"author": "user8128167",
"author_id": 351154,
"author_profile": "https://Stackoverflow.com/users/351154",
"pm_score": 4,
"selected": false,
"text": "<p>I have found that it works well to simply display the date of the last build using the following wherever a product version is needed:</p>\n\n<pre><code>System.IO.File.GetLastWriteTime(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString(\"yyyy.MM.dd.HH.mm.ss\")\n</code></pre>\n\n<p>Rather than attempting to get the version from something like the following:</p>\n\n<pre><code>System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();\nobject[] attributes = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyFileVersionAttribute), false);\nobject attribute = null;\n\nif (attributes.Length > 0)\n{\n attribute = attributes[0] as System.Reflection.AssemblyFileVersionAttribute;\n}\n</code></pre>\n"
},
{
"answer_id": 43894925,
"author": "Nacho Coll",
"author_id": 7975865,
"author_profile": "https://Stackoverflow.com/users/7975865",
"pm_score": 3,
"selected": false,
"text": "<p><em>[Visual Studio 2017, <strong>.csproj</strong> properties]</em></p>\n\n<p>To automatically update your PackageVersion/Version/AssemblyVersion property (or any other property), first, create a new <code>Microsoft.Build.Utilities.Task</code> class that will get your current build number and send back the updated number (I recommend to create a separate project just for that class).</p>\n\n<p>I manually update the major.minor numbers, but let MSBuild to automatically update the build number (1.1.<strong>1</strong>, 1.1.<strong>2</strong>, 1.1.<strong>3</strong>, etc. :)</p>\n\n<pre><code>using Microsoft.Build.Framework;\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class RefreshVersion : Microsoft.Build.Utilities.Task\n{\n [Output]\n public string NewVersionString { get; set; }\n public string CurrentVersionString { get; set; } \n\n public override bool Execute()\n { \n Version currentVersion = new Version(CurrentVersionString ?? \"1.0.0\");\n\n DateTime d = DateTime.Now;\n NewVersionString = new Version(currentVersion.Major, \n currentVersion.Minor, currentVersion.Build+1).ToString();\n return true;\n }\n\n}\n</code></pre>\n\n<p>Then call your recently created Task on MSBuild process adding the next code on your .csproj file:</p>\n\n<pre><code><Project Sdk=\"Microsoft.NET.Sdk\"> \n...\n<UsingTask TaskName=\"RefreshVersion\" AssemblyFile=\"$(MSBuildThisFileFullPath)\\..\\..\\<dll path>\\BuildTasks.dll\" />\n<Target Name=\"RefreshVersionBuildTask\" BeforeTargets=\"Pack\" Condition=\"'$(Configuration)|$(Platform)'=='Release|AnyCPU'\">\n <RefreshVersion CurrentVersionString=\"$(PackageVersion)\">\n <Output TaskParameter=\"NewVersionString\" PropertyName=\"NewVersionString\" /> \n </RefreshVersion>\n <Message Text=\"Updating package version number to $(NewVersionString)...\" Importance=\"high\" />\n <XmlPoke XmlInputPath=\"$(MSBuildProjectDirectory)\\mustache.website.sdk.dotNET.csproj\" Query=\"/Project/PropertyGroup/PackageVersion\" Value=\"$(NewVersionString)\" />\n</Target>\n...\n<PropertyGroup>\n ..\n <PackageVersion>1.1.4</PackageVersion>\n ..\n</code></pre>\n\n<p>When picking Visual Studio Pack project option (just change to <code>BeforeTargets=\"Build\"</code> for executing the task before Build) the RefreshVersion code will be triggered to calculate the new version number, and <code>XmlPoke</code> task will update your .csproj property accordingly (yes, it will modify the file).</p>\n\n<p>When working with NuGet libraries, I also send the package to NuGet repository by just adding the next build task to the previous example.</p>\n\n<pre><code><Message Text=\"Uploading package to NuGet...\" Importance=\"high\" />\n<Exec WorkingDirectory=\"$(MSBuildProjectDirectory)\\bin\\release\" Command=\"c:\\nuget\\nuget push *.nupkg -Source https://www.nuget.org/api/v2/package\" IgnoreExitCode=\"true\" />\n</code></pre>\n\n<p><code>c:\\nuget\\nuget</code> is where I have the NuGet client (remember to save your NuGet API key by calling <code>nuget SetApiKey <my-api-key></code> or to include the key on the NuGet push call).</p>\n\n<p>Just in case it helps someone ^_^.</p>\n"
},
{
"answer_id": 67165881,
"author": "GrahamS",
"author_id": 79591,
"author_profile": "https://Stackoverflow.com/users/79591",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a handcranked alternative option: This is a quick-and-dirty PowerShell snippet I wrote that gets called from a pre-build step on our Jenkins build system.</p>\n<p>It sets the last digit of the <code>AssemblyVersion</code> and <code>AssemblyFileVersion</code> to the value of the <code>BUILD_NUMBER</code> environment variable which is automatically set by the build system.</p>\n<pre class=\"lang-powershell prettyprint-override\"><code>if (Test-Path env:BUILD_NUMBER) {\n Write-Host "Updating AssemblyVersion to $env:BUILD_NUMBER"\n\n # Get the AssemblyInfo.cs\n $assemblyInfo = Get-Content -Path .\\MyShinyApplication\\Properties\\AssemblyInfo.cs\n\n # Replace last digit of AssemblyVersion\n $assemblyInfo = $assemblyInfo -replace \n "^\\[assembly: AssemblyVersion\\(`"([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.[0-9]+`"\\)]", \n ('[assembly: AssemblyVersion("$1.$2.$3.' + $env:BUILD_NUMBER + '")]')\n Write-Host ($assemblyInfo -match '^\\[assembly: AssemblyVersion')\n \n # Replace last digit of AssemblyFileVersion\n $assemblyInfo = $assemblyInfo -replace \n "^\\[assembly: AssemblyFileVersion\\(`"([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.[0-9]+`"\\)]", \n ('[assembly: AssemblyFileVersion("$1.$2.$3.' + $env:BUILD_NUMBER + '")]')\n Write-Host ($assemblyInfo -match '^\\[assembly: AssemblyFileVersion')\n \n $assemblyInfo | Set-Content -Path .\\MyShinyApplication\\Properties\\AssemblyInfo.cs -Encoding UTF8\n} else {\n Write-Warning "BUILD_NUMBER is not set."\n}\n</code></pre>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143/"
] | I would like the version property of my application to be incremented for each build but I'm not sure on how to enable this functionality in Visual Studio (2005/2008). I have tried to specify the AssemblyVersion as 1.0.\* but it doesn't get me exactly what I want.
I'm also using a settings file and in earlier attempts when the assembly version changed my settings got reset to the default since the application looked for the settings file in another directory.
I would like to be able to display a version number in the form of 1.1.38 so when a user finds a problem I can log the version they are using as well as tell them to upgrade if they have an old release.
A short explanation of how the versioning works would also be appreciated. When does the build and revision number get incremented? | With the "Built in" stuff, you can't, as using 1.0.\* or 1.0.0.\* will replace the revision and build numbers with a coded date/timestamp, which is usually also a good way.
For more info, see the [Assembly Linker](http://msdn2.microsoft.com/en-us/library/c405shex(vs.80).aspx) Documentation in the /v tag.
As for automatically incrementing numbers, use the AssemblyInfo Task:
[AssemblyInfo Task](http://code.msdn.microsoft.com/AssemblyInfoTaskvers)
This can be configured to automatically increment the build number.
There are 2 Gotchas:
1. Each of the 4 numbers in the Version string is limited to 65535. This is a Windows Limitation and unlikely to get fixed.
* [Why are build numbers limited to 65535?](http://blogs.msdn.com/msbuild/archive/2007/01/03/why-are-build-numbers-limited-to-65535.aspx)
2. Using with with Subversion requires a small change:
* [Using MSBuild to generate assembly version info at build time (including SubVersion fix)](http://www.andrewconnell.com/blog/archive/2006/08/29/4078.aspx)
Retrieving the Version number is then quite easy:
```
Version v = Assembly.GetExecutingAssembly().GetName().Version;
string About = string.Format(CultureInfo.InvariantCulture, @"YourApp Version {0}.{1}.{2} (r{3})", v.Major, v.Minor, v.Build, v.Revision);
```
---
And, to clarify: In .net or at least in C#, the build is actually the THIRD number, not the fourth one as some people (for example Delphi Developers who are used to Major.Minor.Release.Build) might expect.
In .net, it's Major.Minor.Build.Revision. |
683 | <p>I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,</p>
<pre><code>foo in iter_attr(array of python objects, attribute name)</code></pre>
<p>I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers</p>
| [
{
"answer_id": 701,
"author": "saalon",
"author_id": 111,
"author_profile": "https://Stackoverflow.com/users/111",
"pm_score": 3,
"selected": false,
"text": "<p>No, you were not dreaming. Python has a pretty excellent list comprehension system that lets you manipulate lists pretty elegantly, and depending on exactly what you want to accomplish, this can be done a couple of ways. In essence, what you're doing is saying \"For item in list if criteria.matches\", and from that you can just iterate through the results or dump the results into a new list.</p>\n\n<p>I'm going to crib an example from <a href=\"http://diveintopython.net/functional_programming/filtering_lists.html\" rel=\"noreferrer\">Dive Into Python</a> here, because it's pretty elegant and they're smarter than I am. Here they're getting a list of files in a directory, then filtering the list for all files that match a regular expression criteria.</p>\n\n<blockquote>\n<pre><code> files = os.listdir(path) \n test = re.compile(\"test\\.py$\", re.IGNORECASE) \n files = [f for f in files if test.search(f)]\n</code></pre>\n</blockquote>\n\n<p>You could do this without regular expressions, for your example, for anything where your expression at the end returns true for a match. There are other options like using the filter() function, but if I were going to choose, I'd go with this.</p>\n\n<p>Eric Sipple</p>\n"
},
{
"answer_id": 735,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 0,
"selected": false,
"text": "<p>I think:</p>\n\n<pre><code>#!/bin/python\nbar in dict(Foo)\n</code></pre>\n\n<p>Is what you are thinking of. When trying to see if a certain key exists within a dictionary in python (python's version of a hash table) there are two ways to check. First is the <strong><code>has_key()</code></strong> method attached to the dictionary and second is the example given above. It will return a boolean value.</p>\n\n<p>That should answer your question.</p>\n\n<p>And now a little off topic to tie this in to the <em>list comprehension</em> answer previously given (for a bit more clarity). <em>List Comprehensions</em> construct a list from a basic <em>for loop</em> with modifiers. As an example (to clarify slightly), a way to use the <code>in dict</code> language construct in a <em>list comprehension</em>:</p>\n\n<p>Say you have a two dimensional dictionary <strong><code>foo</code></strong> and you only want the second dimension dictionaries which contain the key <strong><code>bar</code></strong>. A relatively straightforward way to do so would be to use a <em>list comprehension</em> with a conditional as follows:</p>\n\n<pre><code>#!/bin/python\nbaz = dict([(key, value) for key, value in foo if bar in value])\n</code></pre>\n\n<p>Note the <strong><code>if bar in value</code></strong> at the end of the statement**, this is a modifying clause which tells the <em>list comprehension</em> to only keep those key-value pairs which meet the conditional.** In this case <strong><code>baz</code></strong> is a new dictionary which contains only the dictionaries from foo which contain bar (Hopefully I didn't miss anything in that code example... you may have to take a look at the list comprehension documentation found in <a href=\"http://docs.python.org/tut/node7.html#SECTION007140000000000000000\" rel=\"nofollow noreferrer\">docs.python.org tutorials</a> and at <a href=\"http://www.secnetix.de/olli/Python/list_comprehensions.hawk\" rel=\"nofollow noreferrer\">secnetix.de</a>, both sites are good references if you have questions in the future.).</p>\n"
},
{
"answer_id": 745,
"author": "Matt",
"author_id": 154,
"author_profile": "https://Stackoverflow.com/users/154",
"pm_score": 4,
"selected": false,
"text": "<p>Are you looking to get a list of objects that have a certain attribute? If so, a <a href=\"http://docs.python.org/tut/node7.html#SECTION007140000000000000000\" rel=\"noreferrer\">list comprehension</a> is the right way to do this.</p>\n\n<pre><code>result = [obj for obj in listOfObjs if hasattr(obj, 'attributeName')]\n</code></pre>\n"
},
{
"answer_id": 750,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 3,
"selected": false,
"text": "<p>What I was thinking of can be achieved using list comprehensions, but I thought that there was a function that did this in a slightly neater way.</p>\n\n<p>i.e. 'bar' is a list of objects, all of which have the attribute 'id'</p>\n\n<p>The mythical functional way:</p>\n\n<pre><code>foo = 12\nfoo in iter_attr(bar, 'id')</code></pre>\n\n<p>The list comprehension way:</p>\n\n<pre><code>foo = 12\nfoo in [obj.id for obj in bar]</code></pre>\n\n<p>In retrospect the list comprehension way is pretty neat anyway.</p>\n"
},
{
"answer_id": 31126,
"author": "dwestbrook",
"author_id": 3119,
"author_profile": "https://Stackoverflow.com/users/3119",
"pm_score": 3,
"selected": false,
"text": "<p>you could always write one yourself:</p>\n\n<pre><code>def iterattr(iterator, attributename):\n for obj in iterator:\n yield getattr(obj, attributename)\n</code></pre>\n\n<p>will work with anything that iterates, be it a tuple, list, or whatever.</p>\n\n<p>I love python, it makes stuff like this very simple and no more of a hassle than neccessary, and in use stuff like this is hugely elegant.</p>\n"
},
{
"answer_id": 31188,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 2,
"selected": false,
"text": "<p>If you plan on searching anything of remotely decent size, your best bet is going to be to use a dictionary or a set. Otherwise, you basically have to iterate through every element of the iterator until you get to the one you want.</p>\n\n<p>If this isn't necessarily performance sensitive code, then the list comprehension way should work. But note that it is fairly inefficient because it goes over every element of the iterator and then goes BACK over it again until it finds what it wants.</p>\n\n<p>Remember, python has one of the most efficient hashing algorithms around. Use it to your advantage.</p>\n"
},
{
"answer_id": 57833,
"author": "Will Harris",
"author_id": 4702,
"author_profile": "https://Stackoverflow.com/users/4702",
"pm_score": 7,
"selected": true,
"text": "<p>Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before <code>in</code> could start its search.</p>\n\n<p>The temporary list can be avoiding by using a generator expression:</p>\n\n<pre><code>foo = 12\nfoo in (obj.id for obj in bar)\n</code></pre>\n\n<p>Now, as long as <code>obj.id == 12</code> near the start of <code>bar</code>, the search will be fast, even if <code>bar</code> is infinitely long.</p>\n\n<p>As @Matt suggested, it's a good idea to use <code>hasattr</code> if any of the objects in <code>bar</code> can be missing an <code>id</code> attribute:</p>\n\n<pre><code>foo = 12\nfoo in (obj.id for obj in bar if hasattr(obj, 'id'))\n</code></pre>\n"
},
{
"answer_id": 4905822,
"author": "shang",
"author_id": 572606,
"author_profile": "https://Stackoverflow.com/users/572606",
"pm_score": 3,
"selected": false,
"text": "<p>The function you are thinking of is probably <code>operator.attrgettter</code>. For example, to get a list that contains the value of each object's \"id\" attribute:</p>\n\n<pre><code>import operator\nids = map(operator.attrgetter(\"id\"), bar)</code></pre>\n\n<p>If you want to check whether the list contains an object with an id == 12, then a neat and efficient (i.e. doesn't iterate the whole list unnecessarily) way to do it is:</p>\n\n<pre><code>any(obj.id == 12 for obj in bar)</code></pre>\n\n<p>If you want to use 'in' with attrgetter, while still retaining lazy iteration of the list:</p>\n\n<p><pre><code>import operator,itertools\nfoo = 12\nfoo in itertools.imap(operator.attrgetter(\"id\"), bar)\n</pre></code></p>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199/"
] | I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,
```
foo in iter_attr(array of python objects, attribute name)
```
I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers | Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before `in` could start its search.
The temporary list can be avoiding by using a generator expression:
```
foo = 12
foo in (obj.id for obj in bar)
```
Now, as long as `obj.id == 12` near the start of `bar`, the search will be fast, even if `bar` is infinitely long.
As @Matt suggested, it's a good idea to use `hasattr` if any of the objects in `bar` can be missing an `id` attribute:
```
foo = 12
foo in (obj.id for obj in bar if hasattr(obj, 'id'))
``` |
746 | <p>How do I format a string to <a href="http://www.grammar-monster.com/lessons/capital_letters_title_case.htm" rel="noreferrer">title case</a>?</p>
| [
{
"answer_id": 747,
"author": "tags2k",
"author_id": 192,
"author_profile": "https://Stackoverflow.com/users/192",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a simple static method to do this in C#:</p>\n\n<pre><code>public static string ToTitleCaseInvariant(string targetString)\n{\n return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(targetString);\n}\n</code></pre>\n"
},
{
"answer_id": 749,
"author": "cmcculloh",
"author_id": 58,
"author_profile": "https://Stackoverflow.com/users/58",
"pm_score": 3,
"selected": false,
"text": "<p>In what language?</p>\n\n<p>In PHP it is:</p>\n\n<p><a href=\"http://php.net/manual/en/function.ucwords.php\" rel=\"nofollow noreferrer\">ucwords()</a></p>\n\n<p>example:</p>\n\n<pre><code>$HelloWorld = ucwords('hello world');\n</code></pre>\n"
},
{
"answer_id": 751,
"author": "Rudd Zwolinski",
"author_id": 219,
"author_profile": "https://Stackoverflow.com/users/219",
"pm_score": -1,
"selected": false,
"text": "<p>Without using a ready-made function, a super-simple low-level algorithm to convert a string to title case:</p>\n\n<p><pre><code>\nconvert first character to uppercase.\nfor each character in string,\n if the previous character is whitespace,\n convert character to uppercase.\n</pre></code></p>\n\n<p>This asssumes the \"convert character to uppercase\" will do that correctly regardless of whether or not the character is case-sensitive (e.g., '+').</p>\n"
},
{
"answer_id": 754,
"author": "Lehane",
"author_id": 142,
"author_profile": "https://Stackoverflow.com/users/142",
"pm_score": 3,
"selected": false,
"text": "<p>If the language you are using has a supported method/function then just use that (as in the C# <code>ToTitleCase</code> method)</p>\n\n<p>If it does not, then you will want to do something like the following: </p>\n\n<ol>\n<li>Read in the string </li>\n<li>Take the first word </li>\n<li>Capitalize the first letter of that word <sup>1</sup></li>\n<li>Go forward and find the next word </li>\n<li>Go to 3 if not at the end of the string, otherwise exit </li>\n</ol>\n\n<p><sup>1</sup> To capitalize it in, say, C - use the <a href=\"http://www.asciitable.com\" rel=\"nofollow noreferrer\">ascii codes</a> to find the integer value of the char and subtract 32 from it.</p>\n\n<p>There would need to be much more error checking in the code (ensuring valid letters etc.), and the \"Capitalize\" function will need to impose some sort of \"title-case scheme\" on the letters to check for words that do not need to be capatilised ('and', 'but' etc. <a href=\"http://answers.google.com/answers/threadview?id=349913\" rel=\"nofollow noreferrer\">Here</a> is a good scheme)</p>\n"
},
{
"answer_id": 771,
"author": "engtech",
"author_id": 175,
"author_profile": "https://Stackoverflow.com/users/175",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a Perl solution <a href=\"http://daringfireball.net/2008/05/title_case\" rel=\"noreferrer\">http://daringfireball.net/2008/05/title_case</a></p>\n\n<p>Here's a Ruby solution <a href=\"http://frankschmitt.org/projects/title-case\" rel=\"noreferrer\">http://frankschmitt.org/projects/title-case</a></p>\n\n<p>Here's a Ruby one-liner solution: <a href=\"http://snippets.dzone.com/posts/show/4702\" rel=\"noreferrer\">http://snippets.dzone.com/posts/show/4702</a></p>\n\n<pre><code>'some string here'.gsub(/\\b\\w/){$&.upcase}\n</code></pre>\n\n<p>What the one-liner is doing is using a regular expression substitution of the first character of each word with the uppercase version of it.</p>\n"
},
{
"answer_id": 795,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 4,
"selected": false,
"text": "<p>I would be wary of automatically upcasing all whitespace-preceded-words in scenarios where I would run the risk of attracting the fury of nitpickers.</p>\n\n<p>I would at least consider implementing a dictionary for exception cases like articles and conjunctions. Behold: </p>\n\n<blockquote>\n <p>\"Beauty and the Beast\"</p>\n</blockquote>\n\n<p>And when it comes to proper nouns, the thing gets much uglier.</p>\n"
},
{
"answer_id": 1595,
"author": "Bill",
"author_id": 102,
"author_profile": "https://Stackoverflow.com/users/102",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>To capatilise it in, say, C - use the ascii codes (<a href=\"http://www.asciitable.com/\" rel=\"noreferrer\">http://www.asciitable.com/</a>) to find the integer value of the char and subtract 32 from it.</p>\n</blockquote>\n\n<p>This is a poor solution if you ever plan to accept characters beyond a-z and A-Z.</p>\n\n<p>For instance: ASCII 134: å, ASCII 143: Å.<br>\nUsing arithmetic gets you: ASCII 102: f</p>\n\n<p>Use library calls, don't assume you can use integer arithmetic on your characters to get back something useful. Unicode is <a href=\"http://www.joelonsoftware.com/articles/Unicode.html\" rel=\"noreferrer\">tricky</a>.</p>\n"
},
{
"answer_id": 71282,
"author": "robbiebow",
"author_id": 11782,
"author_profile": "https://Stackoverflow.com/users/11782",
"pm_score": -1,
"selected": false,
"text": "<p>With perl you could do this:</p>\n\n<pre><code>my $tc_string = join ' ', map { ucfirst($\\_) } split /\\s+/, $string;\n</code></pre>\n"
},
{
"answer_id": 151018,
"author": "Randal Schwartz",
"author_id": 22483,
"author_profile": "https://Stackoverflow.com/users/22483",
"pm_score": 3,
"selected": false,
"text": "<p>In Perl:</p>\n\n<pre><code>$string =~ s/(\\w+)/\\u\\L$1/g;\n</code></pre>\n\n<p>That's even in the FAQ.</p>\n"
},
{
"answer_id": 151181,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Here you have a C++ version. It's got a set of non uppercaseable words like prononuns and prepositions. However, I would not recommend automating this process if you are to deal with important texts.</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <vector>\n#include <cctype>\n#include <set>\n\nusing namespace std;\n\ntypedef vector<pair<string, int> > subDivision;\nset<string> nonUpperCaseAble;\n\nsubDivision split(string & cadena, string delim = \" \"){\n subDivision retorno;\n int pos, inic = 0;\n while((pos = cadena.find_first_of(delim, inic)) != cadena.npos){\n if(pos-inic > 0){\n retorno.push_back(make_pair(cadena.substr(inic, pos-inic), inic));\n }\n inic = pos+1;\n }\n if(inic != cadena.length()){\n retorno.push_back(make_pair(cadena.substr(inic, cadena.length() - inic), inic));\n }\n return retorno;\n}\n\nstring firstUpper (string & pal){\n pal[0] = toupper(pal[0]);\n return pal;\n}\n\nint main()\n{\n nonUpperCaseAble.insert(\"the\");\n nonUpperCaseAble.insert(\"of\");\n nonUpperCaseAble.insert(\"in\");\n // ...\n\n string linea, resultado;\n cout << \"Type the line you want to convert: \" << endl;\n getline(cin, linea);\n\n subDivision trozos = split(linea);\n for(int i = 0; i < trozos.size(); i++){\n if(trozos[i].second == 0)\n {\n resultado += firstUpper(trozos[i].first);\n }\n else if (linea[trozos[i].second-1] == ' ')\n {\n if(nonUpperCaseAble.find(trozos[i].first) == nonUpperCaseAble.end())\n {\n resultado += \" \" + firstUpper(trozos[i].first);\n }else{\n resultado += \" \" + trozos[i].first;\n }\n }\n else\n {\n resultado += trozos[i].first;\n } \n }\n\n cout << resultado << endl;\n getchar();\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 1861303,
"author": "user226515",
"author_id": 226515,
"author_profile": "https://Stackoverflow.com/users/226515",
"pm_score": 1,
"selected": false,
"text": "<p>I think using the CultureInfo is not always reliable, this the simple and handy way to manipulate string manually:</p>\n<pre><code>string sourceName = txtTextBox.Text.ToLower();\nstring destinationName = sourceName[0].ToUpper();\n\nfor (int i = 0; i < (sourceName.Length - 1); i++) {\n if (sourceName[i + 1] == "") {\n destinationName += sourceName[i + 1];\n }\n else {\n destinationName += sourceName[i + 1];\n }\n}\ntxtTextBox.Text = desinationName;\n</code></pre>\n"
},
{
"answer_id": 3003034,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 1,
"selected": false,
"text": "<p>There is a built-in formula <code>PROPER(n)</code> in Excel.</p>\n\n<p>Was quite pleased to see I didn't have to write it myself!</p>\n"
},
{
"answer_id": 3003038,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 2,
"selected": false,
"text": "<p><code>http://titlecase.com/</code> has an <a href=\"http://titlecase.com\" rel=\"nofollow noreferrer\">API</a></p>\n"
},
{
"answer_id": 3003080,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 3,
"selected": false,
"text": "<p>In Silverlight there is no <code>ToTitleCase</code> in the <code>TextInfo</code> class.</p>\n\n<p>Here's a simple regex based way. </p>\n\n<p>Note: Silverlight doesn't have precompiled regexes, but for me this performance loss is not an issue.</p>\n\n<pre><code> public string TitleCase(string str)\n {\n return Regex.Replace(str, @\"\\w+\", (m) =>\n {\n string tmp = m.Value;\n return char.ToUpper(tmp[0]) + tmp.Substring(1, tmp.Length - 1).ToLower();\n });\n }\n</code></pre>\n"
},
{
"answer_id": 5174338,
"author": "rumbu",
"author_id": 642072,
"author_profile": "https://Stackoverflow.com/users/642072",
"pm_score": 2,
"selected": false,
"text": "<p>Excel-like PROPER:</p>\n\n<pre><code>public static string ExcelProper(string s) {\n bool upper_needed = true;\n string result = \"\";\n foreach (char c in s) {\n bool is_letter = Char.IsLetter(c);\n if (is_letter)\n if (upper_needed)\n result += Char.ToUpper(c);\n else\n result += Char.ToLower(c);\n else\n result += c;\n upper_needed = !is_letter;\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 13449709,
"author": "goji",
"author_id": 269469,
"author_profile": "https://Stackoverflow.com/users/269469",
"pm_score": 1,
"selected": false,
"text": "<p>Here's an implementation in Python: <a href=\"https://launchpad.net/titlecase.py\" rel=\"nofollow\">https://launchpad.net/titlecase.py</a></p>\n\n<p>And a port of this implementation that I've just done in C++: <a href=\"http://codepad.org/RrfcsZzO\" rel=\"nofollow\">http://codepad.org/RrfcsZzO</a></p>\n"
},
{
"answer_id": 35744634,
"author": "Ritesh Shakya",
"author_id": 5452950,
"author_profile": "https://Stackoverflow.com/users/5452950",
"pm_score": 3,
"selected": false,
"text": "<p>In Java, you can use the following code.</p>\n\n<pre><code>public String titleCase(String str) {\n char[] chars = str.toCharArray();\n for (int i = 0; i < chars.length; i++) {\n if (i == 0) {\n chars[i] = Character.toUpperCase(chars[i]);\n } else if ((i + 1) < chars.length && chars[i] == ' ') {\n chars[i + 1] = Character.toUpperCase(chars[i + 1]);\n }\n }\n return new String(chars);\n}\n</code></pre>\n"
},
{
"answer_id": 47831875,
"author": "Simony",
"author_id": 9019502,
"author_profile": "https://Stackoverflow.com/users/9019502",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a simple example of how to do it :</p>\n\n<pre><code>public static string ToTitleCaseInvariant(string str)\n{\n return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str);\n}\n</code></pre>\n"
},
{
"answer_id": 58643270,
"author": "Avid Programmer",
"author_id": 3992001,
"author_profile": "https://Stackoverflow.com/users/3992001",
"pm_score": 0,
"selected": false,
"text": "<p>In C#</p>\n\n<pre><code>using System.Globalization; \nusing System.Threading; \nprotected void Page_Load(object sender, EventArgs e) \n{ \n CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; \n TextInfo textInfo = cultureInfo.TextInfo; \n Response.Write(textInfo.ToTitleCase(\"WelcometoHome<br />\")); \n Response.Write(textInfo.ToTitleCase(\"Welcome to Home\")); \nResponse.Write(textInfo.ToTitleCase(\"Welcome@to$home<br/>\").Replace(\"@\",\"\").Replace(\"$\", \"\")); \n}\n</code></pre>\n"
},
{
"answer_id": 65265979,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>In C# you can simply use</p>\n<pre><code>CultureInfo.InvariantCulture.TextInfo.ToTitleCase(str.ToLowerInvariant())\n</code></pre>\n<ul>\n<li>Invariant</li>\n<li>Works with uppercase strings</li>\n</ul>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] | How do I format a string to [title case](http://www.grammar-monster.com/lessons/capital_letters_title_case.htm)? | Here is a simple static method to do this in C#:
```
public static string ToTitleCaseInvariant(string targetString)
{
return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(targetString);
}
``` |
752 | <p>One may not always know the <code>Type</code> of an object at compile-time, but may need to create an instance of the <code>Type</code>. </p>
<p>How do you get a new object instance from a <code>Type</code>?</p>
| [
{
"answer_id": 755,
"author": "Karl Seguin",
"author_id": 34,
"author_profile": "https://Stackoverflow.com/users/34",
"pm_score": 11,
"selected": true,
"text": "<p>The <code>Activator</code> class within the root <code>System</code> namespace is pretty powerful.</p>\n\n<p>There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at: </p>\n\n<blockquote>\n <p><a href=\"http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx</a></p>\n</blockquote>\n\n<p>or (new path)</p>\n\n<blockquote>\n <p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance\" rel=\"noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance</a></p>\n</blockquote>\n\n<p>Here are some simple examples:</p>\n\n<pre><code>ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);\n\nObjectType instance = (ObjectType)Activator.CreateInstance(\"MyAssembly\",\"MyNamespace.ObjectType\");\n</code></pre>\n"
},
{
"answer_id": 26031,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 4,
"selected": false,
"text": "<p>If this is for something that will be called a lot in an application instance, it's a lot faster to compile and cache dynamic code instead of using the activator or <code>ConstructorInfo.Invoke()</code>. Two easy options for dynamic compilation are compiled <a href=\"http://rogeralsing.com/2008/02/28/linq-expressions-creating-objects/\" rel=\"noreferrer\">Linq Expressions</a> or some simple <a href=\"http://web.archive.org/web/20140926050502/http://www.ozcandegirmenci.com/post/2008/02/Create-object-instances-Faster-than-Reflection.aspx\" rel=\"noreferrer\"><code>IL</code> opcodes and <code>DynamicMethod</code></a>. Either way, the difference is huge when you start getting into tight loops or multiple calls.</p>\n"
},
{
"answer_id": 26033,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "<p>The answer was already given:</p>\n<blockquote>\n<pre><code>ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);\n</code></pre>\n</blockquote>\n<p>However, the <code>Activator</code> class has a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance?view=net-7.0#system-activator-createinstance-1\" rel=\"nofollow noreferrer\">generic variant for the parameterless constructor</a> that makes this slightly more readable by making the cast unnecessary and not needing to pass the runtime type of the object:</p>\n<pre><code>ObjectType instance = Activator.CreateInstance<ObjectType>();\n</code></pre>\n"
},
{
"answer_id": 3503517,
"author": "Brady Moritz",
"author_id": 177242,
"author_profile": "https://Stackoverflow.com/users/177242",
"pm_score": 4,
"selected": false,
"text": "<p>Wouldn't the generic <code>T t = new T();</code> work? </p>\n"
},
{
"answer_id": 12343731,
"author": "vikram nayak",
"author_id": 196857,
"author_profile": "https://Stackoverflow.com/users/196857",
"pm_score": 3,
"selected": false,
"text": "<pre><code>public AbstractType New\n{\n get\n {\n return (AbstractType) Activator.CreateInstance(GetType());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 17797389,
"author": "BSharp",
"author_id": 2237957,
"author_profile": "https://Stackoverflow.com/users/2237957",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to use the default constructor then the solution using <code>System.Activator</code> presented earlier is probably the most convenient. However, if the type lacks a default constructor or you have to use a non-default one, then an option is to use reflection or <code>System.ComponentModel.TypeDescriptor</code>. In case of reflection, it is enough to know just the type name (with its namespace).</p>\n\n<p>Example using reflection:</p>\n\n<pre><code>ObjectType instance = \n (ObjectType)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(\n typeName: objectType.FulName, // string including namespace of the type\n ignoreCase: false,\n bindingAttr: BindingFlags.Default,\n binder: null, // use default binder\n args: new object[] { args, to, constructor },\n culture: null, // use CultureInfo from current thread\n activationAttributes: null\n );\n</code></pre>\n\n<p>Example using <code>TypeDescriptor</code>:</p>\n\n<pre><code>ObjectType instance = \n (ObjectType)System.ComponentModel.TypeDescriptor.CreateInstance(\n provider: null, // use standard type description provider, which uses reflection\n objectType: objectType,\n argTypes: new Type[] { types, of, args },\n args: new object[] { args, to, constructor }\n );\n</code></pre>\n"
},
{
"answer_id": 26708746,
"author": "Sarath Subramanian",
"author_id": 3312636,
"author_profile": "https://Stackoverflow.com/users/3312636",
"pm_score": 5,
"selected": false,
"text": "<p>Its pretty simple. Assume that your classname is <code>Car</code> and the namespace is <code>Vehicles</code>, then pass the parameter as <code>Vehicles.Car</code> which returns object of type <code>Car</code>. Like this you can create any instance of any class dynamically.</p>\n\n<pre><code>public object GetInstance(string strNamesapace)\n{ \n Type t = Type.GetType(strNamesapace); \n return Activator.CreateInstance(t); \n}\n</code></pre>\n\n<p>If your <a href=\"https://msdn.microsoft.com/en-us/library/dfb3cx8s%28v=vs.71%29.aspx\" rel=\"noreferrer\">Fully Qualified Name</a>(ie, <code>Vehicles.Car</code> in this case) is in another assembly, the <code>Type.GetType</code> will be null. In such cases, you have loop through all assemblies and find the <code>Type</code>. For that you can use the below code</p>\n\n<pre><code>public object GetInstance(string strFullyQualifiedName)\n{\n Type type = Type.GetType(strFullyQualifiedName);\n if (type != null)\n return Activator.CreateInstance(type);\n foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())\n {\n type = asm.GetType(strFullyQualifiedName);\n if (type != null)\n return Activator.CreateInstance(type);\n }\n return null;\n }\n</code></pre>\n\n<p>And you can get the instance by calling the above method.</p>\n\n<pre><code>object objClassInstance = GetInstance(\"Vehicles.Car\");\n</code></pre>\n"
},
{
"answer_id": 29239907,
"author": "Darrel Lee",
"author_id": 307968,
"author_profile": "https://Stackoverflow.com/users/307968",
"pm_score": 2,
"selected": false,
"text": "<p>I can across this question because I was looking to implement a simple CloneObject method for arbitrary class (with a default constructor)</p>\n\n<p>With generic method you can require that the type implements New().</p>\n\n<pre><code>Public Function CloneObject(Of T As New)(ByVal src As T) As T\n Dim result As T = Nothing\n Dim cloneable = TryCast(src, ICloneable)\n If cloneable IsNot Nothing Then\n result = cloneable.Clone()\n Else\n result = New T\n CopySimpleProperties(src, result, Nothing, \"clone\")\n End If\n Return result\nEnd Function\n</code></pre>\n\n<p>With non-generic assume the type has a default constructor and catch\nan exception if it doesn't.</p>\n\n<pre><code>Public Function CloneObject(ByVal src As Object) As Object\n Dim result As Object = Nothing\n Dim cloneable As ICloneable\n Try\n cloneable = TryCast(src, ICloneable)\n If cloneable IsNot Nothing Then\n result = cloneable.Clone()\n Else\n result = Activator.CreateInstance(src.GetType())\n CopySimpleProperties(src, result, Nothing, \"clone\")\n End If\n Catch ex As Exception\n Trace.WriteLine(\"!!! CloneObject(): \" & ex.Message)\n End Try\n Return result\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 29972767,
"author": "Serj-Tm",
"author_id": 1034136,
"author_profile": "https://Stackoverflow.com/users/1034136",
"pm_score": 7,
"selected": false,
"text": "<p>Compiled expression is best way! (for performance to repeatedly create instance in runtime).</p>\n\n<pre><code>static readonly Func<X> YCreator = Expression.Lambda<Func<X>>(\n Expression.New(typeof(Y).GetConstructor(Type.EmptyTypes))\n ).Compile();\n\nX x = YCreator();\n</code></pre>\n\n<p>Statistics (2012):</p>\n\n<pre><code> Iterations: 5000000\n 00:00:00.8481762, Activator.CreateInstance(string, string)\n 00:00:00.8416930, Activator.CreateInstance(type)\n 00:00:06.6236752, ConstructorInfo.Invoke\n 00:00:00.1776255, Compiled expression\n 00:00:00.0462197, new\n</code></pre>\n\n<p>Statistics (2015, .net 4.5, x64):</p>\n\n<pre><code> Iterations: 5000000\n 00:00:00.2659981, Activator.CreateInstance(string, string)\n 00:00:00.2603770, Activator.CreateInstance(type)\n 00:00:00.7478936, ConstructorInfo.Invoke\n 00:00:00.0700757, Compiled expression\n 00:00:00.0286710, new\n</code></pre>\n\n<p>Statistics (2015, .net 4.5, x86):</p>\n\n<pre><code> Iterations: 5000000\n 00:00:00.3541501, Activator.CreateInstance(string, string)\n 00:00:00.3686861, Activator.CreateInstance(type)\n 00:00:00.9492354, ConstructorInfo.Invoke\n 00:00:00.0719072, Compiled expression\n 00:00:00.0229387, new\n</code></pre>\n\n<p>Statistics (2017, LINQPad 5.22.02/x64/.NET 4.6):</p>\n\n<pre><code> Iterations: 5000000\n No args\n 00:00:00.3897563, Activator.CreateInstance(string assemblyName, string typeName)\n 00:00:00.3500748, Activator.CreateInstance(Type type)\n 00:00:01.0100714, ConstructorInfo.Invoke\n 00:00:00.1375767, Compiled expression\n 00:00:00.1337920, Compiled expression (type)\n 00:00:00.0593664, new\n Single arg\n 00:00:03.9300630, Activator.CreateInstance(Type type)\n 00:00:01.3881770, ConstructorInfo.Invoke\n 00:00:00.1425534, Compiled expression\n 00:00:00.0717409, new\n</code></pre>\n\n<p>Statistics (2019, x64/.NET 4.8):</p>\n\n<pre><code>Iterations: 5000000\nNo args\n00:00:00.3287835, Activator.CreateInstance(string assemblyName, string typeName)\n00:00:00.3122015, Activator.CreateInstance(Type type)\n00:00:00.8035712, ConstructorInfo.Invoke\n00:00:00.0692854, Compiled expression\n00:00:00.0662223, Compiled expression (type)\n00:00:00.0337862, new\nSingle arg\n00:00:03.8081959, Activator.CreateInstance(Type type)\n00:00:01.2507642, ConstructorInfo.Invoke\n00:00:00.0671756, Compiled expression\n00:00:00.0301489, new\n</code></pre>\n\n<p>Statistics (2019, x64/.NET Core 3.0):</p>\n\n<pre><code>Iterations: 5000000\nNo args\n00:00:00.3226895, Activator.CreateInstance(string assemblyName, string typeName)\n00:00:00.2786803, Activator.CreateInstance(Type type)\n00:00:00.6183554, ConstructorInfo.Invoke\n00:00:00.0483217, Compiled expression\n00:00:00.0485119, Compiled expression (type)\n00:00:00.0434534, new\nSingle arg\n00:00:03.4389401, Activator.CreateInstance(Type type)\n00:00:01.0803609, ConstructorInfo.Invoke\n00:00:00.0554756, Compiled expression\n00:00:00.0462232, new\n</code></pre>\n\n<p>Full code:</p>\n\n<pre><code>static X CreateY_New()\n{\n return new Y();\n}\n\nstatic X CreateY_New_Arg(int z)\n{\n return new Y(z);\n}\n\nstatic X CreateY_CreateInstance()\n{\n return (X)Activator.CreateInstance(typeof(Y));\n}\n\nstatic X CreateY_CreateInstance_String()\n{\n return (X)Activator.CreateInstance(\"Program\", \"Y\").Unwrap();\n}\n\nstatic X CreateY_CreateInstance_Arg(int z)\n{\n return (X)Activator.CreateInstance(typeof(Y), new object[] { z, });\n}\n\nprivate static readonly System.Reflection.ConstructorInfo YConstructor =\n typeof(Y).GetConstructor(Type.EmptyTypes);\nprivate static readonly object[] Empty = new object[] { };\nstatic X CreateY_Invoke()\n{\n return (X)YConstructor.Invoke(Empty);\n}\n\nprivate static readonly System.Reflection.ConstructorInfo YConstructor_Arg =\n typeof(Y).GetConstructor(new[] { typeof(int), });\nstatic X CreateY_Invoke_Arg(int z)\n{\n return (X)YConstructor_Arg.Invoke(new object[] { z, });\n}\n\nprivate static readonly Func<X> YCreator = Expression.Lambda<Func<X>>(\n Expression.New(typeof(Y).GetConstructor(Type.EmptyTypes))\n).Compile();\nstatic X CreateY_CompiledExpression()\n{\n return YCreator();\n}\n\nprivate static readonly Func<X> YCreator_Type = Expression.Lambda<Func<X>>(\n Expression.New(typeof(Y))\n).Compile();\nstatic X CreateY_CompiledExpression_Type()\n{\n return YCreator_Type();\n}\n\nprivate static readonly ParameterExpression YCreator_Arg_Param = Expression.Parameter(typeof(int), \"z\");\nprivate static readonly Func<int, X> YCreator_Arg = Expression.Lambda<Func<int, X>>(\n Expression.New(typeof(Y).GetConstructor(new[] { typeof(int), }), new[] { YCreator_Arg_Param, }),\n YCreator_Arg_Param\n).Compile();\nstatic X CreateY_CompiledExpression_Arg(int z)\n{\n return YCreator_Arg(z);\n}\n\nstatic void Main(string[] args)\n{\n const int iterations = 5000000;\n\n Console.WriteLine(\"Iterations: {0}\", iterations);\n\n Console.WriteLine(\"No args\");\n foreach (var creatorInfo in new[]\n {\n new {Name = \"Activator.CreateInstance(string assemblyName, string typeName)\", Creator = (Func<X>)CreateY_CreateInstance},\n new {Name = \"Activator.CreateInstance(Type type)\", Creator = (Func<X>)CreateY_CreateInstance},\n new {Name = \"ConstructorInfo.Invoke\", Creator = (Func<X>)CreateY_Invoke},\n new {Name = \"Compiled expression\", Creator = (Func<X>)CreateY_CompiledExpression},\n new {Name = \"Compiled expression (type)\", Creator = (Func<X>)CreateY_CompiledExpression_Type},\n new {Name = \"new\", Creator = (Func<X>)CreateY_New},\n })\n {\n var creator = creatorInfo.Creator;\n\n var sum = 0;\n for (var i = 0; i < 1000; i++)\n sum += creator().Z;\n\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n for (var i = 0; i < iterations; ++i)\n {\n var x = creator();\n sum += x.Z;\n }\n stopwatch.Stop();\n Console.WriteLine(\"{0}, {1}\", stopwatch.Elapsed, creatorInfo.Name);\n }\n\n Console.WriteLine(\"Single arg\");\n foreach (var creatorInfo in new[]\n {\n new {Name = \"Activator.CreateInstance(Type type)\", Creator = (Func<int, X>)CreateY_CreateInstance_Arg},\n new {Name = \"ConstructorInfo.Invoke\", Creator = (Func<int, X>)CreateY_Invoke_Arg},\n new {Name = \"Compiled expression\", Creator = (Func<int, X>)CreateY_CompiledExpression_Arg},\n new {Name = \"new\", Creator = (Func<int, X>)CreateY_New_Arg},\n })\n {\n var creator = creatorInfo.Creator;\n\n var sum = 0;\n for (var i = 0; i < 1000; i++)\n sum += creator(i).Z;\n\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n for (var i = 0; i < iterations; ++i)\n {\n var x = creator(i);\n sum += x.Z;\n }\n stopwatch.Stop();\n Console.WriteLine(\"{0}, {1}\", stopwatch.Elapsed, creatorInfo.Name);\n }\n}\n\npublic class X\n{\n public X() { }\n public X(int z) { this.Z = z; }\n public int Z;\n}\n\npublic class Y : X\n{\n public Y() {}\n public Y(int z) : base(z) {}\n}\n</code></pre>\n"
},
{
"answer_id": 31138841,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Without use of Reflection:</p>\n\n<pre><code>private T Create<T>() where T : class, new()\n{\n return new T();\n}\n</code></pre>\n"
},
{
"answer_id": 31143718,
"author": "Thulani Chivandikwa",
"author_id": 611628,
"author_profile": "https://Stackoverflow.com/users/611628",
"pm_score": 4,
"selected": false,
"text": "<p>Given this problem the Activator will work when there is a parameterless ctor. If this is a constraint consider using </p>\n\n<pre><code>System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject()\n</code></pre>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] | One may not always know the `Type` of an object at compile-time, but may need to create an instance of the `Type`.
How do you get a new object instance from a `Type`? | The `Activator` class within the root `System` namespace is pretty powerful.
There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at:
>
> <http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx>
>
>
>
or (new path)
>
> <https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance>
>
>
>
Here are some simple examples:
```
ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);
ObjectType instance = (ObjectType)Activator.CreateInstance("MyAssembly","MyNamespace.ObjectType");
``` |
761 | <p>What is the best way to localise a date format descriptor?</p>
<p>As anyone from a culture which does not use the mm/dd/yyyy format knows, it is annoying to have to enter dates in this format. The .NET framework provides some very good localisation support, so it's trivial to parse dates according to the users culture, but you often want to also display a helpful hint as to the format required (especially to distinguish between yy and yyyy which is interchangeable in most cultures).</p>
<p>What is the best way to do this in a way that make sense to most users (e.g. dd/M/yyy is confusing because of the change in case and the switching between one and two letters).</p>
| [
{
"answer_id": 762,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 3,
"selected": true,
"text": "<p>Here is my current method. Any suggestions?</p>\n\n<pre><code>Regex singleMToDoubleRegex = new Regex(\"(?<!m)m(?!m)\");\nRegex singleDToDoubleRegex = new Regex(\"(?<!d)d(?!d)\");\nCultureInfo currentCulture = CultureInfo.CurrentUICulture;\n\n// If the culture is netural there is no date pattern to use, so use the default.\nif (currentCulture.IsNeutralCulture)\n{\n currentCulture = CultureInfo.InvariantCulture;\n}\n\n// Massage the format into a more general user friendly form.\nstring shortDatePattern = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern.ToLower();\nshortDatePattern = singleMToDoubleRegex.Replace(shortDatePattern, \"mm\");\nshortDatePattern = singleDToDoubleRegex.Replace(shortDatePattern, \"dd\");\n</code></pre>\n"
},
{
"answer_id": 763,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 1,
"selected": false,
"text": "<p>How about giving the format (mm/dd/yyyy or dd/mm/yyyy) followed by a printout of today's date in the user's culture. MSDN has an article on <a href=\"http://msdn.microsoft.com/en-us/library/5hh873ya(VS.71).aspx\" rel=\"nofollow noreferrer\">formatting a DateTime for the person's culture</a>, using the CultureInfo object that might be helpful in doing this. A combination of the format (which most people are familiar with) combined with the current date represented in that format should be enough of a clue to the person on how they should enter the date. (Also include a calendar control for those who still cant figure it out).</p>\n"
},
{
"answer_id": 770,
"author": "engtech",
"author_id": 175,
"author_profile": "https://Stackoverflow.com/users/175",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow noreferrer\">Just use ISO-8601</a>. It's an international standard.</p>\n\n<pre><code>Date and time (current at page generation) expressed according to ISO 8601:\nDate: 2014-07-05\nCombined date and time in UTC: 2014-07-05T04:00:25+00:00\n 2014-07-05T04:00:25Z\nWeek: 2014-W27\nDate with week number: 2014-W27-6\nOrdinal date: 2014-186\n</code></pre>\n"
},
{
"answer_id": 1077,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 2,
"selected": false,
"text": "<p>The trouble with international standards is that pretty much noone uses them. I try where I can, but I am forced to use dd/mm/yyyy almost everywhere in real life, which means I am so used to it it's always a conscious process to use ISO-8601. For the majority of people who don't even try to use ISO-8601 it's even worse. If you can internationalize where you can, I think it's a great advantage.</p>\n"
},
{
"answer_id": 1495,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 2,
"selected": false,
"text": "<p>I have to agree with the OP 'wrong' dates really jar with my DD/MM/YYYY upbringing and I find ISO 8601 dates and times extremely easy to work with. For once the standard got it right and <a href=\"https://stackoverflow.com/questions/761/#770\">engtech</a> has the obvious answer that doesn't require localisation.</p>\n\n<p>I was going to report the birthday input form on stack overflow as a bug because of how much of a sore thumb it is to the majority of the world.</p>\n"
},
{
"answer_id": 1524,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 1,
"selected": false,
"text": "<p>A short form is convenient and helps avoid spelling mistakes. Localize as applicable, but be sure to display the expected format (do not leave the user blind). Provide a date-picker control as an <em>optional</em> aide to filling in the field.</p>\n\n<p>As an extra, on-the-fly parsing and display of the date in long form might help too.</p>\n"
},
{
"answer_id": 103717,
"author": "user19050",
"author_id": 19050,
"author_profile": "https://Stackoverflow.com/users/19050",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Best option</strong>: I would instead recommend to use a standard date picker.</p>\n\n<p><strong>Alternative</strong>: every time the content of the edit control changes, parse it and display (in a separate control?) the long format of the date (ie: input \"03/04/09\" display \"Your input: March 4, 2009\")</p>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214/"
] | What is the best way to localise a date format descriptor?
As anyone from a culture which does not use the mm/dd/yyyy format knows, it is annoying to have to enter dates in this format. The .NET framework provides some very good localisation support, so it's trivial to parse dates according to the users culture, but you often want to also display a helpful hint as to the format required (especially to distinguish between yy and yyyy which is interchangeable in most cultures).
What is the best way to do this in a way that make sense to most users (e.g. dd/M/yyy is confusing because of the change in case and the switching between one and two letters). | Here is my current method. Any suggestions?
```
Regex singleMToDoubleRegex = new Regex("(?<!m)m(?!m)");
Regex singleDToDoubleRegex = new Regex("(?<!d)d(?!d)");
CultureInfo currentCulture = CultureInfo.CurrentUICulture;
// If the culture is netural there is no date pattern to use, so use the default.
if (currentCulture.IsNeutralCulture)
{
currentCulture = CultureInfo.InvariantCulture;
}
// Massage the format into a more general user friendly form.
string shortDatePattern = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern.ToLower();
shortDatePattern = singleMToDoubleRegex.Replace(shortDatePattern, "mm");
shortDatePattern = singleDToDoubleRegex.Replace(shortDatePattern, "dd");
``` |
769 | <p>I need to programmatically solve a system of linear equations in C, Objective C, or (if needed) C++.</p>
<p>Here's an example of the equations:</p>
<pre><code>-44.3940 = a * 50.0 + b * 37.0 + tx
-45.3049 = a * 43.0 + b * 39.0 + tx
-44.9594 = a * 52.0 + b * 41.0 + tx
</code></pre>
<p>From this, I'd like to get the best approximation for <code>a</code>, <code>b</code>, and <code>tx</code>.</p>
| [
{
"answer_id": 774,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": "<p>Are you looking for a software package that'll do the work or actually doing the matrix operations and such and do each step?</p>\n\n<p>The the first, a coworker of mine just used <a href=\"http://ocaml-glpk.sourceforge.net/\" rel=\"nofollow noreferrer\" title=\"Ocaml GLPK\">Ocaml GLPK</a>. It is just a wrapper for the <a href=\"http://www.gnu.org/software/glpk/\" rel=\"nofollow noreferrer\" title=\"GNU Linear Programming Kit\">GLPK</a>, but it removes a lot of the steps of setting things up. It looks like you're going to have to stick with the GLPK, in C, though. For the latter, thanks to delicious for saving an old article I used to learn LP awhile back, <a href=\"http://www.math.ucla.edu/~tom/LP.pdf\" rel=\"nofollow noreferrer\" title=\"Linear Programming\">PDF</a>. If you need specific help setting up further, let us know and I'm sure, me or someone will wander back in and help, but, I think it's fairly straight forward from here. Good Luck! </p>\n"
},
{
"answer_id": 781,
"author": "Brian Jorgensen",
"author_id": 229,
"author_profile": "https://Stackoverflow.com/users/229",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Cramers_rule\" rel=\"noreferrer\">Cramer's Rule</a>\nand\n<a href=\"http://en.wikipedia.org/wiki/Gaussian_elimination\" rel=\"noreferrer\">Gaussian Elimination</a>\nare two good, general-purpose algorithms (also see <a href=\"http://en.wikipedia.org/wiki/Simultaneous_linear_equations\" rel=\"noreferrer\">Simultaneous Linear Equations</a>). If you're looking for code, check out <a href=\"http://en.wikipedia.org/wiki/GiNaC\" rel=\"noreferrer\">GiNaC</a>, <a href=\"http://maxima.sourceforge.net/\" rel=\"noreferrer\">Maxima</a>, and <a href=\"http://issc.uj.ac.za/symbolic/symbolic.html\" rel=\"noreferrer\">SymbolicC++</a> (depending on your licensing requirements, of course).</p>\n\n<p>EDIT: I know you're working in C land, but I also have to put in a good word for <a href=\"http://code.google.com/p/sympy/\" rel=\"noreferrer\">SymPy</a> (a computer algebra system in Python). You can learn a lot from its algorithms (if you can read a bit of python). Also, it's under the new BSD license, while most of the free math packages are GPL.</p>\n"
},
{
"answer_id": 6206,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>For a 3x3 system of linear equations I guess it would be okay to roll out your own algorithms. </p>\n\n<p>However, you might have to worry about accuracy, division by zero or really small numbers and what to do about infinitely many solutions. My suggestion is to go with a standard numerical linear algebra package such as <a href=\"http://en.wikipedia.org/wiki/Lapack\" rel=\"nofollow noreferrer\">LAPACK</a>. </p>\n"
},
{
"answer_id": 26578,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "<p>Personally, I'm partial to the algorithms of <a href=\"http://www.nr.com/\" rel=\"nofollow noreferrer\">Numerical Recipes</a>. (I'm fond of the C++ edition.)</p>\n\n<p>This book will teach you why the algorithms work, plus show you some pretty-well debugged implementations of those algorithms.</p>\n\n<p>Of course, you could just blindly use <a href=\"http://www.netlib.org/clapack/\" rel=\"nofollow noreferrer\">CLAPACK</a> (I've used it with great success), but I would first hand-type a Gaussian Elimination algorithm to at least have a faint idea of the kind of work that has gone into making these algorithms stable.</p>\n\n<p>Later, if you're doing more interesting linear algebra, looking around the source code of <a href=\"http://www.gnu.org/software/octave/\" rel=\"nofollow noreferrer\">Octave</a> will answer a lot of questions.</p>\n"
},
{
"answer_id": 26637,
"author": "Baltimark",
"author_id": 1179,
"author_profile": "https://Stackoverflow.com/users/1179",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://math.nist.gov/tnt/download.html\" rel=\"nofollow noreferrer\">Template Numerical Toolkit</a> from NIST has tools for doing that. </p>\n\n<p>One of the more reliable ways is to use a <a href=\"http://en.wikipedia.org/wiki/QR_decomposition\" rel=\"nofollow noreferrer\">QR Decomposition</a>. </p>\n\n<p>Here's an example of a wrapper so that I can call \"GetInverse(A, InvA)\" in my code and it will put the inverse into InvA.</p>\n\n<pre><code>void GetInverse(const Array2D<double>& A, Array2D<double>& invA)\n {\n QR<double> qr(A); \n invA = qr.solve(I); \n }\n</code></pre>\n\n<p>Array2D is defined in the library. </p>\n"
},
{
"answer_id": 83758,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 2,
"selected": false,
"text": "<p>From the wording of your question, it seems like you have more equations than unknowns and you want to minimize the inconsistencies. This is typically done with linear regression, which minimizes the sum of the squares of the inconsistencies. Depending on the size of the data, you can do this in a spreadsheet or in a statistical package. R is a high-quality, free package that does linear regression, among a lot of other things. There is a lot to linear regression (and a lot of gotcha's), but as it's straightforward to do for simple cases. Here's an R example using your data. Note that the \"tx\" is the intercept to your model.</p>\n\n<pre><code>> y <- c(-44.394, -45.3049, -44.9594)\n> a <- c(50.0, 43.0, 52.0)\n> b <- c(37.0, 39.0, 41.0)\n> regression = lm(y ~ a + b)\n> regression\n\nCall:\nlm(formula = y ~ a + b)\n\nCoefficients:\n(Intercept) a b \n -41.63759 0.07852 -0.18061 \n</code></pre>\n"
},
{
"answer_id": 99339,
"author": "Thelema",
"author_id": 12874,
"author_profile": "https://Stackoverflow.com/users/12874",
"pm_score": 2,
"selected": false,
"text": "<p>In terms of run-time efficiency, others have answered better than I. If you always will have the same number of equations as variables, I like <a href=\"http://en.wikipedia.org/wiki/Cramer's_rule\" rel=\"nofollow noreferrer\">Cramer's rule</a> as it's easy to implement. Just write a function to calculate determinant of a matrix (or use one that's already written, I'm sure you can find one out there), and divide the determinants of two matrices.</p>\n"
},
{
"answer_id": 590060,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": false,
"text": "<p>You can solve this with a program exactly the same way you solve it by hand (with multiplication and subtraction, then feeding results back into the equations). This is pretty standard secondary-school-level mathematics.</p>\n\n<pre><code>-44.3940 = 50a + 37b + c (A)\n-45.3049 = 43a + 39b + c (B)\n-44.9594 = 52a + 41b + c (C)\n\n(A-B): 0.9109 = 7a - 2b (D)\n(B-C): 0.3455 = -9a - 2b (E)\n\n(D-E): 1.2564 = 16a (F)\n\n(F/16): a = 0.078525 (G)\n\nFeed G into D:\n 0.9109 = 7a - 2b\n => 0.9109 = 0.549675 - 2b (substitute a)\n => 0.361225 = -2b (subtract 0.549675 from both sides)\n => -0.1806125 = b (divide both sides by -2) (H)\n\nFeed H/G into A:\n -44.3940 = 50a + 37b + c\n => -44.3940 = 3.92625 - 6.6826625 + c (substitute a/b)\n => -41.6375875 = c (subtract 3.92625 - 6.6826625 from both sides)\n</code></pre>\n\n<p>So you end up with:</p>\n\n<pre><code>a = 0.0785250\nb = -0.1806125\nc = -41.6375875\n</code></pre>\n\n<p>If you plug these values back into A, B and C, you'll find they're correct.</p>\n\n<p>The trick is to use a simple 4x3 matrix which reduces in turn to a 3x2 matrix, then a 2x1 which is \"a = n\", n being an actual number. Once you have that, you feed it into the next matrix up to get another value, then those two values into the next matrix up until you've solved all variables.</p>\n\n<p>Provided you have N distinct equations, you can always solve for N variables. I say distinct because these two are not:</p>\n\n<pre><code> 7a + 2b = 50\n14a + 4b = 100\n</code></pre>\n\n<p>They are the <em>same</em> equation multiplied by two so you cannot get a solution from them - multiplying the first by two then subtracting leaves you with the true but useless statement:</p>\n\n<pre><code>0 = 0 + 0\n</code></pre>\n\n<hr>\n\n<p>By way of example, here's some C code that works out the simultaneous equations that you're placed in your question. First some necessary types, variables, a support function for printing out an equation, and the start of <code>main</code>:</p>\n\n<pre><code>#include <stdio.h>\n\ntypedef struct { double r, a, b, c; } tEquation;\ntEquation equ1[] = {\n { -44.3940, 50, 37, 1 }, // -44.3940 = 50a + 37b + c (A)\n { -45.3049, 43, 39, 1 }, // -45.3049 = 43a + 39b + c (B)\n { -44.9594, 52, 41, 1 }, // -44.9594 = 52a + 41b + c (C)\n};\ntEquation equ2[2], equ3[1];\n\nstatic void dumpEqu (char *desc, tEquation *e, char *post) {\n printf (\"%10s: %12.8lf = %12.8lfa + %12.8lfb + %12.8lfc (%s)\\n\",\n desc, e->r, e->a, e->b, e->c, post);\n}\n\nint main (void) {\n double a, b, c;\n</code></pre>\n\n<p>Next, the reduction of the three equations with three unknowns to two equations with two unknowns:</p>\n\n<pre><code> // First step, populate equ2 based on removing c from equ.\n\n dumpEqu (\">\", &(equ1[0]), \"A\");\n dumpEqu (\">\", &(equ1[1]), \"B\");\n dumpEqu (\">\", &(equ1[2]), \"C\");\n puts (\"\");\n\n // A - B\n equ2[0].r = equ1[0].r * equ1[1].c - equ1[1].r * equ1[0].c;\n equ2[0].a = equ1[0].a * equ1[1].c - equ1[1].a * equ1[0].c;\n equ2[0].b = equ1[0].b * equ1[1].c - equ1[1].b * equ1[0].c;\n equ2[0].c = 0;\n\n // B - C\n equ2[1].r = equ1[1].r * equ1[2].c - equ1[2].r * equ1[1].c;\n equ2[1].a = equ1[1].a * equ1[2].c - equ1[2].a * equ1[1].c;\n equ2[1].b = equ1[1].b * equ1[2].c - equ1[2].b * equ1[1].c;\n equ2[1].c = 0;\n\n dumpEqu (\"A-B\", &(equ2[0]), \"D\");\n dumpEqu (\"B-C\", &(equ2[1]), \"E\");\n puts (\"\");\n</code></pre>\n\n<p>Next, the reduction of the two equations with two unknowns to one equation with one unknown:</p>\n\n<pre><code> // Next step, populate equ3 based on removing b from equ2.\n\n // D - E\n equ3[0].r = equ2[0].r * equ2[1].b - equ2[1].r * equ2[0].b;\n equ3[0].a = equ2[0].a * equ2[1].b - equ2[1].a * equ2[0].b;\n equ3[0].b = 0;\n equ3[0].c = 0;\n\n dumpEqu (\"D-E\", &(equ3[0]), \"F\");\n puts (\"\");\n</code></pre>\n\n<p>Now that we have a formula of the type <code>number1 = unknown * number2</code>, we can simply work out the unknown value with <code>unknown <- number1 / number2</code>. Then, once you've figured that value out, substitute it into one of the equations with two unknowns and work out the second value. Then substitute both those (now-known) unknowns into one of the original equations and you now have the values for all three unknowns:</p>\n\n<pre><code> // Finally, substitute values back into equations.\n\n a = equ3[0].r / equ3[0].a;\n printf (\"From (F ), a = %12.8lf (G)\\n\", a);\n\n b = (equ2[0].r - equ2[0].a * a) / equ2[0].b;\n printf (\"From (D,G ), b = %12.8lf (H)\\n\", b);\n\n c = (equ1[0].r - equ1[0].a * a - equ1[0].b * b) / equ1[0].c;\n printf (\"From (A,G,H), c = %12.8lf (I)\\n\", c);\n\n return 0;\n}\n</code></pre>\n\n<p>The output of that code matches the earlier calculations in this answer:</p>\n\n<pre><code> >: -44.39400000 = 50.00000000a + 37.00000000b + 1.00000000c (A)\n >: -45.30490000 = 43.00000000a + 39.00000000b + 1.00000000c (B)\n >: -44.95940000 = 52.00000000a + 41.00000000b + 1.00000000c (C)\n\n A-B: 0.91090000 = 7.00000000a + -2.00000000b + 0.00000000c (D)\n B-C: -0.34550000 = -9.00000000a + -2.00000000b + 0.00000000c (E)\n\n D-E: -2.51280000 = -32.00000000a + 0.00000000b + 0.00000000c (F)\n\nFrom (F ), a = 0.07852500 (G)\nFrom (D,G ), b = -0.18061250 (H)\nFrom (A,G,H), c = -41.63758750 (I)\n</code></pre>\n"
},
{
"answer_id": 770947,
"author": "Bobby Ortiz",
"author_id": 25843,
"author_profile": "https://Stackoverflow.com/users/25843",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at the <a href=\"http://code.msdn.microsoft.com/solverfoundation\" rel=\"noreferrer\">Microsoft Solver Foundation</a>.</p>\n\n<p>With it you could write code like this:</p>\n\n<pre><code> SolverContext context = SolverContext.GetContext();\n Model model = context.CreateModel();\n\n Decision a = new Decision(Domain.Real, \"a\");\n Decision b = new Decision(Domain.Real, \"b\");\n Decision c = new Decision(Domain.Real, \"c\");\n model.AddDecisions(a,b,c);\n model.AddConstraint(\"eqA\", -44.3940 == 50*a + 37*b + c);\n model.AddConstraint(\"eqB\", -45.3049 == 43*a + 39*b + c);\n model.AddConstraint(\"eqC\", -44.9594 == 52*a + 41*b + c);\n Solution solution = context.Solve();\n string results = solution.GetReport().ToString();\n Console.WriteLine(results); \n</code></pre>\n\n<p><strong>Here is the output:</strong><br/>\n===Solver Foundation Service Report===<br/>\nDatetime: 04/20/2009 23:29:55<br/>\nModel Name: Default<br/>\nCapabilities requested: LP<br/>\nSolve Time (ms): 1027<br/>\nTotal Time (ms): 1414<br/>\nSolve Completion Status: Optimal<br/>\nSolver Selected: Microsoft.SolverFoundation.Solvers.SimplexSolver<br/>\nDirectives:<br/>\nMicrosoft.SolverFoundation.Services.Directive<br/>\nAlgorithm: Primal<br/>\nArithmetic: Hybrid<br/>\nPricing (exact): Default<br/>\nPricing (double): SteepestEdge<br/>\nBasis: Slack<br/>\nPivot Count: 3<br/>\n===Solution Details===<br/>\nGoals:<br/>\n<br/>\nDecisions:<br/>\na: 0.0785250000000004<br/>\nb: -0.180612500000001<br/>\nc: -41.6375875<br/></p>\n"
},
{
"answer_id": 27708081,
"author": "Bulent S.",
"author_id": 4405846,
"author_profile": "https://Stackoverflow.com/users/4405846",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function x = LinSolve(A,y)\n%\n% Recursive Solution of Linear System Ax=y\n% matlab equivalent: x = A\\y \n% x = n x 1\n% A = n x n\n% y = n x 1\n% Uses stack space extensively. Not efficient.\n% C allows recursion, so convert it into C. \n% ----------------------------------------------\nn=length(y);\nx=zeros(n,1);\nif(n>1)\n x(1:n-1,1) = LinSolve( A(1:n-1,1:n-1) - (A(1:n-1,n)*A(n,1:n-1))./A(n,n) , ...\n y(1:n-1,1) - A(1:n-1,n).*(y(n,1)/A(n,n))); \n x(n,1) = (y(n,1) - A(n,1:n-1)*x(1:n-1,1))./A(n,n); \nelse\n x = y(1,1) / A(1,1);\nend\n</code></pre>\n"
},
{
"answer_id": 69017457,
"author": "Hussain Chitalwala",
"author_id": 11280050,
"author_profile": "https://Stackoverflow.com/users/11280050",
"pm_score": -1,
"selected": false,
"text": "<p>For general cases, you could use python along with numpy for Gaussian elimination. And then plug in values and get the remaining values.</p>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79/"
] | I need to programmatically solve a system of linear equations in C, Objective C, or (if needed) C++.
Here's an example of the equations:
```
-44.3940 = a * 50.0 + b * 37.0 + tx
-45.3049 = a * 43.0 + b * 39.0 + tx
-44.9594 = a * 52.0 + b * 41.0 + tx
```
From this, I'd like to get the best approximation for `a`, `b`, and `tx`. | [Cramer's Rule](http://en.wikipedia.org/wiki/Cramers_rule)
and
[Gaussian Elimination](http://en.wikipedia.org/wiki/Gaussian_elimination)
are two good, general-purpose algorithms (also see [Simultaneous Linear Equations](http://en.wikipedia.org/wiki/Simultaneous_linear_equations)). If you're looking for code, check out [GiNaC](http://en.wikipedia.org/wiki/GiNaC), [Maxima](http://maxima.sourceforge.net/), and [SymbolicC++](http://issc.uj.ac.za/symbolic/symbolic.html) (depending on your licensing requirements, of course).
EDIT: I know you're working in C land, but I also have to put in a good word for [SymPy](http://code.google.com/p/sympy/) (a computer algebra system in Python). You can learn a lot from its algorithms (if you can read a bit of python). Also, it's under the new BSD license, while most of the free math packages are GPL. |
773 | <p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p>
<ul>
<li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li>
<li>Divide it into groups based on some criteria</li>
<li>Then later iterate over each of these groups separately.</li>
</ul>
<p>I've reviewed <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="noreferrer">the documentation</a>, but I've had trouble trying to apply them beyond a simple list of numbers.</p>
<p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.</p>
| [
{
"answer_id": 783,
"author": "Seb",
"author_id": 189,
"author_profile": "https://Stackoverflow.com/users/189",
"pm_score": 6,
"selected": false,
"text": "<p>The example on the Python docs is quite straightforward:</p>\n\n<pre><code>groups = []\nuniquekeys = []\nfor k, g in groupby(data, keyfunc):\n groups.append(list(g)) # Store group iterator as a list\n uniquekeys.append(k)\n</code></pre>\n\n<p>So in your case, data is a list of nodes, <code>keyfunc</code> is where the logic of your criteria function goes and then <code>groupby()</code> groups the data.</p>\n\n<p>You must be careful to <strong>sort the data</strong> by the criteria before you call <code>groupby</code> or it won't work. <code>groupby</code> method actually just iterates through a list and whenever the key changes it creates a new group.</p>\n"
},
{
"answer_id": 7286,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 11,
"selected": true,
"text": "<p><strong>IMPORTANT NOTE:</strong> You have to <strong>sort your data</strong> first.</p>\n<hr />\n<p>The part I didn't get is that in the example construction</p>\n<pre><code>groups = []\nuniquekeys = []\nfor k, g in groupby(data, keyfunc):\n groups.append(list(g)) # Store group iterator as a list\n uniquekeys.append(k)\n</code></pre>\n<p><code>k</code> is the current grouping key, and <code>g</code> is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the <code>groupby</code> iterator itself returns iterators.</p>\n<p>Here's an example of that, using clearer variable names:</p>\n<pre><code>from itertools import groupby\n\nthings = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]\n\nfor key, group in groupby(things, lambda x: x[0]):\n for thing in group:\n print("A %s is a %s." % (thing[1], key))\n print("")\n \n</code></pre>\n<p>This will give you the output:</p>\n<blockquote>\n<p>A bear is a animal.<br />\nA duck is a animal.</p>\n<p>A cactus is a plant.</p>\n<p>A speed boat is a vehicle.<br />\nA school bus is a vehicle.</p>\n</blockquote>\n<p>In this example, <code>things</code> is a list of tuples where the first item in each tuple is the group the second item belongs to.</p>\n<p>The <code>groupby()</code> function takes two arguments: (1) the data to group and (2) the function to group it with.</p>\n<p>Here, <code>lambda x: x[0]</code> tells <code>groupby()</code> to use the first item in each tuple as the grouping key.</p>\n<p>In the above <code>for</code> statement, <code>groupby</code> returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group.</p>\n<p>Here's a slightly different example with the same data, using a list comprehension:</p>\n<pre><code>for key, group in groupby(things, lambda x: x[0]):\n listOfThings = " and ".join([thing[1] for thing in group])\n print(key + "s: " + listOfThings + ".")\n</code></pre>\n<p>This will give you the output:</p>\n<blockquote>\n<p>animals: bear and duck.<br />\nplants: cactus.<br />\nvehicles: speed boat and school bus.</p>\n</blockquote>\n"
},
{
"answer_id": 37252,
"author": "nimish",
"author_id": 3926,
"author_profile": "https://Stackoverflow.com/users/3926",
"pm_score": 6,
"selected": false,
"text": "<p>A neato trick with groupby is to run length encoding in one line:</p>\n\n<pre><code>[(c,len(list(cgen))) for c,cgen in groupby(some_string)]\n</code></pre>\n\n<p>will give you a list of 2-tuples where the first element is the char and the 2nd is the number of repetitions.</p>\n\n<p>Edit: Note that this is what separates <code>itertools.groupby</code> from the SQL <code>GROUP BY</code> semantics: itertools doesn't (and in general can't) sort the iterator in advance, so groups with the same \"key\" aren't merged.</p>\n"
},
{
"answer_id": 1573195,
"author": "pedromanoel",
"author_id": 83284,
"author_profile": "https://Stackoverflow.com/users/83284",
"pm_score": 3,
"selected": false,
"text": "<p>@CaptSolo, I tried your example, but it didn't work.</p>\n\n<pre><code>from itertools import groupby \n[(c,len(list(cs))) for c,cs in groupby('Pedro Manoel')]\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[('P', 1), ('e', 1), ('d', 1), ('r', 1), ('o', 1), (' ', 1), ('M', 1), ('a', 1), ('n', 1), ('o', 1), ('e', 1), ('l', 1)]\n</code></pre>\n\n<p>As you can see, there are two o's and two e's, but they got into separate groups. That's when I realized you need to sort the list passed to the groupby function. So, the correct usage would be:</p>\n\n<pre><code>name = list('Pedro Manoel')\nname.sort()\n[(c,len(list(cs))) for c,cs in groupby(name)]\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[(' ', 1), ('M', 1), ('P', 1), ('a', 1), ('d', 1), ('e', 2), ('l', 1), ('n', 1), ('o', 2), ('r', 1)]\n</code></pre>\n\n<p>Just remembering, if the list is not sorted, the groupby function <strong>will not work</strong>!</p>\n"
},
{
"answer_id": 14443477,
"author": "user650654",
"author_id": 650654,
"author_profile": "https://Stackoverflow.com/users/650654",
"pm_score": 5,
"selected": false,
"text": "<p>Another example:</p>\n<pre><code>for key, igroup in itertools.groupby(xrange(12), lambda x: x // 5):\n print key, list(igroup)\n</code></pre>\n<p>results in</p>\n<pre><code>0 [0, 1, 2, 3, 4]\n1 [5, 6, 7, 8, 9]\n2 [10, 11]\n</code></pre>\n<p>Note that <code>igroup</code> is an iterator (a sub-iterator as the documentation calls it).</p>\n<p>This is useful for chunking a generator:</p>\n<pre><code>def chunker(items, chunk_size):\n '''Group items in chunks of chunk_size'''\n for _key, group in itertools.groupby(enumerate(items), lambda x: x[0] // chunk_size):\n yield (g[1] for g in group)\n\nwith open('file.txt') as fobj:\n for chunk in chunker(fobj):\n process(chunk)\n</code></pre>\n<p>Another example of <code>groupby</code> - when the keys are not sorted. In the following example, items in <code>xx</code> are grouped by values in <code>yy</code>. In this case, one set of zeros is output first, followed by a set of ones, followed again by a set of zeros.</p>\n<pre><code>xx = range(10)\nyy = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0]\nfor group in itertools.groupby(iter(xx), lambda x: yy[x]):\n print group[0], list(group[1])\n</code></pre>\n<p>Produces:</p>\n<pre><code>0 [0, 1, 2]\n1 [3, 4, 5]\n0 [6, 7, 8, 9]\n</code></pre>\n"
},
{
"answer_id": 16427674,
"author": "kiriloff",
"author_id": 1141493,
"author_profile": "https://Stackoverflow.com/users/1141493",
"pm_score": 4,
"selected": false,
"text": "<p>I would like to give another example where groupby without sort is not working. Adapted from example by James Sulak</p>\n\n<pre><code>from itertools import groupby\n\nthings = [(\"vehicle\", \"bear\"), (\"animal\", \"duck\"), (\"animal\", \"cactus\"), (\"vehicle\", \"speed boat\"), (\"vehicle\", \"school bus\")]\n\nfor key, group in groupby(things, lambda x: x[0]):\n for thing in group:\n print \"A %s is a %s.\" % (thing[1], key)\n print \" \"\n</code></pre>\n\n<p>output is</p>\n\n<pre><code>A bear is a vehicle.\n\nA duck is a animal.\nA cactus is a animal.\n\nA speed boat is a vehicle.\nA school bus is a vehicle.\n</code></pre>\n\n<p>there are two groups with vehicule, whereas one could expect only one group</p>\n"
},
{
"answer_id": 20013133,
"author": "RussellStewart",
"author_id": 2237635,
"author_profile": "https://Stackoverflow.com/users/2237635",
"pm_score": 5,
"selected": false,
"text": "<p>WARNING:</p>\n\n<p>The syntax list(groupby(...)) won't work the way that you intend. It seems to destroy the internal iterator objects, so using</p>\n\n<pre><code>for x in list(groupby(range(10))):\n print(list(x[1]))\n</code></pre>\n\n<p>will produce:</p>\n\n<pre><code>[]\n[]\n[]\n[]\n[]\n[]\n[]\n[]\n[]\n[9]\n</code></pre>\n\n<p>Instead, of list(groupby(...)), try [(k, list(g)) for k,g in groupby(...)], or if you use that syntax often,</p>\n\n<pre><code>def groupbylist(*args, **kwargs):\n return [(k, list(g)) for k, g in groupby(*args, **kwargs)]\n</code></pre>\n\n<p>and get access to the groupby functionality while avoiding those pesky (for small data) iterators all together.</p>\n"
},
{
"answer_id": 31660194,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p><strong>How do I use Python's itertools.groupby()?</strong></p>\n</blockquote>\n\n<p>You can use groupby to group things to iterate over. You give groupby an iterable, and a optional <strong>key</strong> function/callable by which to check the items as they come out of the iterable, and it returns an iterator that gives a two-tuple of the result of the key callable and the actual items in another iterable. From the help:</p>\n\n<pre><code>groupby(iterable[, keyfunc]) -> create an iterator which returns\n(key, sub-iterator) grouped by each value of key(value).\n</code></pre>\n\n<p>Here's an example of groupby using a coroutine to group by a count, it uses a key callable (in this case, <code>coroutine.send</code>) to just spit out the count for however many iterations and a grouped sub-iterator of elements:</p>\n\n<pre><code>import itertools\n\n\ndef grouper(iterable, n):\n def coroutine(n):\n yield # queue up coroutine\n for i in itertools.count():\n for j in range(n):\n yield i\n groups = coroutine(n)\n next(groups) # queue up coroutine\n\n for c, objs in itertools.groupby(iterable, groups.send):\n yield c, list(objs)\n # or instead of materializing a list of objs, just:\n # return itertools.groupby(iterable, groups.send)\n\nlist(grouper(range(10), 3))\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>[(0, [0, 1, 2]), (1, [3, 4, 5]), (2, [6, 7, 8]), (3, [9])]\n</code></pre>\n"
},
{
"answer_id": 44617583,
"author": "Arko",
"author_id": 7933904,
"author_profile": "https://Stackoverflow.com/users/7933904",
"pm_score": 2,
"selected": false,
"text": "<p>One useful example that I came across may be helpful:</p>\n\n<pre><code>from itertools import groupby\n\n#user input\n\nmyinput = input()\n\n#creating empty list to store output\n\nmyoutput = []\n\nfor k,g in groupby(myinput):\n\n myoutput.append((len(list(g)),int(k)))\n\nprint(*myoutput)\n</code></pre>\n\n<p>Sample input: 14445221</p>\n\n<p>Sample output: (1,1) (3,4) (1,5) (2,2) (1,1)</p>\n"
},
{
"answer_id": 45431237,
"author": "Satyajit Das",
"author_id": 8137464,
"author_profile": "https://Stackoverflow.com/users/8137464",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Sorting and groupby</p>\n</blockquote>\n\n<pre><code>from itertools import groupby\n\nval = [{'name': 'satyajit', 'address': 'btm', 'pin': 560076}, \n {'name': 'Mukul', 'address': 'Silk board', 'pin': 560078},\n {'name': 'Preetam', 'address': 'btm', 'pin': 560076}]\n\n\nfor pin, list_data in groupby(sorted(val, key=lambda k: k['pin']),lambda x: x['pin']):\n... print pin\n... for rec in list_data:\n... print rec\n... \no/p:\n\n560076\n{'name': 'satyajit', 'pin': 560076, 'address': 'btm'}\n{'name': 'Preetam', 'pin': 560076, 'address': 'btm'}\n560078\n{'name': 'Mukul', 'pin': 560078, 'address': 'Silk board'}\n</code></pre>\n"
},
{
"answer_id": 45873519,
"author": "pylang",
"author_id": 4531270,
"author_profile": "https://Stackoverflow.com/users/4531270",
"pm_score": 7,
"selected": false,
"text": "<p><code>itertools.groupby</code> is a tool for grouping items.</p>\n<p>From <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\">the docs</a>, we glean further what it might do:</p>\n<blockquote>\n<p><code># [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B</code></p>\n<p><code># [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D</code></p>\n</blockquote>\n<p><code>groupby</code> objects yield key-group pairs where the group is a generator.</p>\n<p>Features</p>\n<ul>\n<li>A. Group consecutive items together</li>\n<li>B. Group all occurrences of an item, given a sorted iterable</li>\n<li>C. Specify how to group items with a <em>key function</em> <sup>*</sup></li>\n</ul>\n<p>Comparisons</p>\n<pre><code># Define a printer for comparing outputs\n>>> def print_groupby(iterable, keyfunc=None):\n... for k, g in it.groupby(iterable, keyfunc):\n... print("key: '{}'--> group: {}".format(k, list(g)))\n</code></pre>\n \n<pre><code># Feature A: group consecutive occurrences\n>>> print_groupby("BCAACACAADBBB")\nkey: 'B'--> group: ['B']\nkey: 'C'--> group: ['C']\nkey: 'A'--> group: ['A', 'A']\nkey: 'C'--> group: ['C']\nkey: 'A'--> group: ['A']\nkey: 'C'--> group: ['C']\nkey: 'A'--> group: ['A', 'A']\nkey: 'D'--> group: ['D']\nkey: 'B'--> group: ['B', 'B', 'B']\n\n# Feature B: group all occurrences\n>>> print_groupby(sorted("BCAACACAADBBB"))\nkey: 'A'--> group: ['A', 'A', 'A', 'A', 'A']\nkey: 'B'--> group: ['B', 'B', 'B', 'B']\nkey: 'C'--> group: ['C', 'C', 'C']\nkey: 'D'--> group: ['D']\n\n# Feature C: group by a key function\n>>> # islower = lambda s: s.islower() # equivalent\n>>> def islower(s):\n... """Return True if a string is lowercase, else False.""" \n... return s.islower()\n>>> print_groupby(sorted("bCAaCacAADBbB"), keyfunc=islower)\nkey: 'False'--> group: ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D']\nkey: 'True'--> group: ['a', 'a', 'b', 'b', 'c']\n</code></pre>\n<p>Uses</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/8181513/finding-and-grouping-anagrams-by-python\">Anagrams</a> (<a href=\"https://github.com/vterron/EuroPython-2016/blob/master/kung-fu-itertools.ipynb\" rel=\"noreferrer\">see notebook</a>)</li>\n<li><a href=\"https://stackoverflow.com/a/45991797/4531270\">Binning</a></li>\n<li><a href=\"https://naiquevin.github.io/a-look-at-some-of-pythons-useful-itertools.html\" rel=\"noreferrer\">Group odd and even numbers</a></li>\n<li><a href=\"https://stackoverflow.com/questions/5695208/group-list-by-values\">Group a list by values</a></li>\n<li><a href=\"https://stackoverflow.com/questions/56796328/how-to-delete-repeat-elements-in-this-list\">Remove duplicate elements</a></li>\n<li><a href=\"https://stackoverflow.com/a/44792205/4531270\">Find indices of repeated elements in an array</a></li>\n<li><a href=\"https://stackoverflow.com/a/42677465/4531270\">Split an array into n-sized chunks</a></li>\n<li><a href=\"https://stackoverflow.com/a/41993784/4531270\">Find corresponding elements between two lists</a></li>\n<li><a href=\"https://youtu.be/iCrOGS1QlB8?t=27m27s\" rel=\"noreferrer\">Compression algorithm</a> (<a href=\"https://github.com/vterron/EuroPython-2016/blob/master/kung-fu-itertools.ipynb\" rel=\"noreferrer\">see notebook</a>)/<a href=\"https://stackoverflow.com/questions/25537028/run-length-encoding-in-python-with-list-comprehension/25537050#25537050\">Run Length Encoding</a></li>\n<li><a href=\"https://youtu.be/iCrOGS1QlB8?t=29m11s\" rel=\"noreferrer\">Grouping letters by length, key function</a> (<a href=\"https://github.com/vterron/EuroPython-2016/blob/master/kung-fu-itertools.ipynb\" rel=\"noreferrer\">see notebook</a>)</li>\n<li><a href=\"https://youtu.be/iCrOGS1QlB8?t=30m19s\" rel=\"noreferrer\">Consecutive values over a threshold</a> (<a href=\"https://github.com/vterron/EuroPython-2016/blob/master/kung-fu-itertools.ipynb\" rel=\"noreferrer\">see notebook</a>)</li>\n<li><a href=\"https://stackoverflow.com/questions/4628333/converting-a-list-of-integers-into-range-in-python\">Find ranges of numbers in a list</a> or <a href=\"https://stackoverflow.com/questions/2154249/identify-groups-of-continuous-numbers-in-a-list\">continuous items</a> (see <a href=\"https://docs.python.org/release/2.4.4/lib/itertools-example.html\" rel=\"noreferrer\">docs</a>)</li>\n<li><a href=\"https://stackoverflow.com/questions/46928922/pythonic-way-to-find-all-potential-longest-sequence\">Find all related longest sequences</a></li>\n<li><a href=\"https://stackoverflow.com/a/46752214/4531270\">Take consecutive sequences that meet a condition</a> (<a href=\"https://stackoverflow.com/a/46432991/4531270\">see related post</a>)</li>\n</ul>\n<p><em>Note: Several of the latter examples derive from Víctor Terrón's PyCon <a href=\"https://www.youtube.com/watch?v=iCrOGS1QlB8\" rel=\"noreferrer\">(talk)</a> <a href=\"https://www.youtube.com/watch?v=4ZIxcdREYVc\" rel=\"noreferrer\">(Spanish)</a>, "Kung Fu at Dawn with Itertools". See also the <code>groupby </code><a href=\"https://github.com/python/cpython/blob/6cca5c8459cc439cb050010ffa762a03859d3051/Modules/itertoolsmodule.c#L11-L375\" rel=\"noreferrer\">source code</a> written in C.</em></p>\n<p><sup>* A function where all items are passed through and compared, influencing the result. Other objects with key functions include <code>sorted()</code>, <code>max()</code> and <code>min()</code>.</sup></p>\n<hr />\n<p>Response</p>\n<pre><code># OP: Yes, you can use `groupby`, e.g. \n[do_something(list(g)) for _, g in groupby(lxml_elements, criteria_func)]\n</code></pre>\n"
},
{
"answer_id": 61048516,
"author": "Tiago",
"author_id": 9726459,
"author_profile": "https://Stackoverflow.com/users/9726459",
"pm_score": 3,
"selected": false,
"text": "<p>This basic implementation helped me understand this function. Hope it helps others as well:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>arr = [(1, \"A\"), (1, \"B\"), (1, \"C\"), (2, \"D\"), (2, \"E\"), (3, \"F\")]\n\nfor k,g in groupby(arr, lambda x: x[0]):\n print(\"--\", k, \"--\")\n for tup in g:\n print(tup[1]) # tup[0] == k\n</code></pre>\n\n<pre><code>-- 1 --\nA\nB\nC\n-- 2 --\nD\nE\n-- 3 --\nF\n</code></pre>\n"
},
{
"answer_id": 68091577,
"author": "andrewdotn",
"author_id": 14558,
"author_profile": "https://Stackoverflow.com/users/14558",
"pm_score": 3,
"selected": false,
"text": "<p>Sadly I don’t think it’s advisable to use <code>itertools.groupby()</code>. It’s just too hard to use safely, and it’s only a handful of lines to write something that works as expected.</p>\n<pre><code>def my_group_by(iterable, keyfunc):\n """Because itertools.groupby is tricky to use\n\n The stdlib method requires sorting in advance, and returns iterators not\n lists, and those iterators get consumed as you try to use them, throwing\n everything off if you try to look at something more than once.\n """\n ret = defaultdict(list)\n for k in iterable:\n ret[keyfunc(k)].append(k)\n return dict(ret)\n</code></pre>\n<p>Use it like this:</p>\n<pre><code>def first_letter(x):\n return x[0]\n\nmy_group_by('four score and seven years ago'.split(), first_letter)\n</code></pre>\n<p>to get</p>\n<pre><code>{'f': ['four'], 's': ['score', 'seven'], 'a': ['and', 'ago'], 'y': ['years']}\n</code></pre>\n"
},
{
"answer_id": 69783850,
"author": "Ankit Gupta",
"author_id": 7864006,
"author_profile": "https://Stackoverflow.com/users/7864006",
"pm_score": 2,
"selected": false,
"text": "<pre><code>from random import randint\nfrom itertools import groupby\n\n l = [randint(1, 3) for _ in range(20)]\n\n d = {}\n for k, g in groupby(l, lambda x: x):\n if not d.get(k, None):\n d[k] = list(g)\n else:\n d[k] = d[k] + list(g)\n</code></pre>\n<p>the code above shows how groupby can be used to group a list based on the lambda function/key supplied. The only problem is that the output is not merged, this can be easily resolved using a dictionary.</p>\n<p>Example:</p>\n<pre><code>l = [2, 1, 2, 3, 1, 3, 2, 1, 3, 3, 1, 3, 2, 3, 1, 2, 1, 3, 2, 3]\n</code></pre>\n<p>after applying groupby the result will be:</p>\n<pre><code>for k, g in groupby(l, lambda x:x):\n print(k, list(g))\n\n2 [2]\n1 [1]\n2 [2]\n3 [3]\n1 [1]\n3 [3]\n2 [2]\n1 [1]\n3 [3, 3]\n1 [1]\n3 [3]\n2 [2]\n3 [3]\n1 [1]\n2 [2]\n1 [1]\n3 [3]\n2 [2]\n3 [3]\n</code></pre>\n<p>Once a dictionary is used as shown above following result is derived which can be easily iterated over:</p>\n<pre><code>{2: [2, 2, 2, 2, 2, 2], 1: [1, 1, 1, 1, 1, 1], 3: [3, 3, 3, 3, 3, 3, 3, 3]}\n</code></pre>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207/"
] | I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this:
* Take a list - in this case, the children of an objectified `lxml` element
* Divide it into groups based on some criteria
* Then later iterate over each of these groups separately.
I've reviewed [the documentation](https://docs.python.org/3/library/itertools.html#itertools.groupby), but I've had trouble trying to apply them beyond a simple list of numbers.
So, how do I use of `itertools.groupby()`? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated. | **IMPORTANT NOTE:** You have to **sort your data** first.
---
The part I didn't get is that in the example construction
```
groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
groups.append(list(g)) # Store group iterator as a list
uniquekeys.append(k)
```
`k` is the current grouping key, and `g` is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the `groupby` iterator itself returns iterators.
Here's an example of that, using clearer variable names:
```
from itertools import groupby
things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
for key, group in groupby(things, lambda x: x[0]):
for thing in group:
print("A %s is a %s." % (thing[1], key))
print("")
```
This will give you the output:
>
> A bear is a animal.
>
> A duck is a animal.
>
>
> A cactus is a plant.
>
>
> A speed boat is a vehicle.
>
> A school bus is a vehicle.
>
>
>
In this example, `things` is a list of tuples where the first item in each tuple is the group the second item belongs to.
The `groupby()` function takes two arguments: (1) the data to group and (2) the function to group it with.
Here, `lambda x: x[0]` tells `groupby()` to use the first item in each tuple as the grouping key.
In the above `for` statement, `groupby` returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group.
Here's a slightly different example with the same data, using a list comprehension:
```
for key, group in groupby(things, lambda x: x[0]):
listOfThings = " and ".join([thing[1] for thing in group])
print(key + "s: " + listOfThings + ".")
```
This will give you the output:
>
> animals: bear and duck.
>
> plants: cactus.
>
> vehicles: speed boat and school bus.
>
>
> |
810 | <p>I'm trying to maintain a Setup Project in <code>Visual Studio 2003</code> (yes, it's a legacy application). The problem we have at the moment is that we need to write registry entries to <code>HKCU</code> for every user on the computer. They need to be in the <code>HKCU</code> rather than <code>HKLM</code> because they are the default user settings, and they do change per user. My feeling is that</p>
<ol>
<li>This isn't possible</li>
<li>This isn't something the installer should be doing, but something the application should be doing (after all what happens when a user profile is created after the install?).</li>
</ol>
<p>With that in mind, I still want to change as little as possible in the application, so my question is, <strong>is it possible to add registry entries for every user in a <code>Visual Studio 2003</code> setup project?</strong> </p>
<p>And, at the moment the project lists five registry root keys (<code>HKEY_CLASSES_ROOT, HKEY_CURRENT_USER</code>, <code>HKEY_LOCAL_MACHINE</code>, <code>HKEY_USERS</code>, and User/Machine Hive). I don't really know anything about the Users root key, and haven't seen User/Machine Hive. Can anyone enlighten me on what they are? Perhaps they could solve my problem above.</p>
| [
{
"answer_id": 818,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 2,
"selected": false,
"text": "<p>I'm partway to my solution with this entry on MSDN (don't know how I couldn't find it before).</p>\n\n<p>User/Machine Hive<br>\nSubkeys and values entered under this hive will be installed under the HKEY_CURRENT_USER hive when a user chooses \"Just Me\" or the HKEY_USERS hive or when a user chooses \"Everyone\" during installation.</p>\n\n<p><s><a href=\"http://msdn.microsoft.com/en-us/library/x6kd89c5(VS.80).aspx\" rel=\"nofollow noreferrer\">Registry Editor</a></s> <a href=\"http://web.archive.org/web/20100112132447/http://msdn.microsoft.com/en-us/library/x6kd89c5(VS.80).aspx\" rel=\"nofollow noreferrer\">Archive of MSDN Article</a></p>\n"
},
{
"answer_id": 820,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 4,
"selected": true,
"text": "<p>First: Yes, this is something that belongs in the Application for the exact reson you specified: What happens after new user profiles are created? Sure, if you're using a domain it's possible to have some stuff put in the registry on creation, but this is not really a use case. The Application should check if there are seetings and use the default settings if not.</p>\n\n<p>That being said, it IS possible to change other users Keys through the HKEY_USERS Hive.</p>\n\n<p>I have no experience with the Visual Studio 2003 Setup Project, so here is a bit of (totally unrelated) VBScript code that might just give you an idea where to look:</p>\n\n<pre><code>const HKEY_USERS = &H80000003\nstrComputer = \".\"\nSet objReg=GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\default:StdRegProv\")\nstrKeyPath = \"\"\nobjReg.EnumKey HKEY_USERS, strKeyPath, arrSubKeys\nstrKeyPath = \"\\Software\\Microsoft\\Windows\\CurrentVersion\\WinTrust\\Trust Providers\\Software Publishing\"\nFor Each subkey In arrSubKeys\n objReg.SetDWORDValue HKEY_USERS, subkey & strKeyPath, \"State\", 146944\nNext\n</code></pre>\n\n<p>(Code Courtesy of <a href=\"http://jritmeijer.spaces.live.com/blog/cns!8A48A27460FB898A!965.entry\" rel=\"noreferrer\">Jeroen Ritmeijer</a>)</p>\n"
},
{
"answer_id": 829,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": false,
"text": "<p>I'm guessing that because you want to set it for all users, that you're on some kind of shared computer, which is probably running under a domain?</p>\n\n<p><strong>HERE BE DRAGONS</strong></p>\n\n<p>Let's say Joe and Jane regularly log onto the computer, then they will each have 'registries'.</p>\n\n<p>You'll then install your app, and the installer will employ giant hacks and disgusting things to set items under HKCU for them.</p>\n\n<p>THEN, bob will come along and log on (he, and 500 other people have accounts in the domain and so can do this). He's never used this computer before, so he has no registry. The first time he logs in, windows creates him one, but he won't have your setting. </p>\n\n<p>Your app then falls over or behaves incorrectly, and bob complains loudly about those crappy products from raynixon incorporated.</p>\n\n<p>The correct answer is to just have some default settings in your app, which can write them to the registry if it doesn't find them. It's general good practice that your app should never depend on the registry, and should create things as needed, for any registry entry, not just HKCU, anyway</p>\n"
},
{
"answer_id": 870,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 2,
"selected": false,
"text": "<p>Despite what the <s><a href=\"http://msdn.microsoft.com/en-us/library/x6kd89c5(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN article</a></s> <a href=\"http://web.archive.org/web/20100112132447/http://msdn.microsoft.com/en-us/library/x6kd89c5(VS.80).aspx\" rel=\"nofollow noreferrer\">Archive of MSDN Article</a> says about User/Machine Hive, it doesn't write to HKEY_USERS. Rather it writes to HKCU if you select Just Me and HKLM if you select everyone.</p>\n\n<p>So my solution is going to be to use the User/Machine Hive, and then in the application it checks if the registry entries are in HKCU and if not, copies them from HKLM. I know this probably isn't the most ideal way of doing it, but it has the least amount of changes.</p>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233/"
] | I'm trying to maintain a Setup Project in `Visual Studio 2003` (yes, it's a legacy application). The problem we have at the moment is that we need to write registry entries to `HKCU` for every user on the computer. They need to be in the `HKCU` rather than `HKLM` because they are the default user settings, and they do change per user. My feeling is that
1. This isn't possible
2. This isn't something the installer should be doing, but something the application should be doing (after all what happens when a user profile is created after the install?).
With that in mind, I still want to change as little as possible in the application, so my question is, **is it possible to add registry entries for every user in a `Visual Studio 2003` setup project?**
And, at the moment the project lists five registry root keys (`HKEY_CLASSES_ROOT, HKEY_CURRENT_USER`, `HKEY_LOCAL_MACHINE`, `HKEY_USERS`, and User/Machine Hive). I don't really know anything about the Users root key, and haven't seen User/Machine Hive. Can anyone enlighten me on what they are? Perhaps they could solve my problem above. | First: Yes, this is something that belongs in the Application for the exact reson you specified: What happens after new user profiles are created? Sure, if you're using a domain it's possible to have some stuff put in the registry on creation, but this is not really a use case. The Application should check if there are seetings and use the default settings if not.
That being said, it IS possible to change other users Keys through the HKEY\_USERS Hive.
I have no experience with the Visual Studio 2003 Setup Project, so here is a bit of (totally unrelated) VBScript code that might just give you an idea where to look:
```
const HKEY_USERS = &H80000003
strComputer = "."
Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
strKeyPath = ""
objReg.EnumKey HKEY_USERS, strKeyPath, arrSubKeys
strKeyPath = "\Software\Microsoft\Windows\CurrentVersion\WinTrust\Trust Providers\Software Publishing"
For Each subkey In arrSubKeys
objReg.SetDWORDValue HKEY_USERS, subkey & strKeyPath, "State", 146944
Next
```
(Code Courtesy of [Jeroen Ritmeijer](http://jritmeijer.spaces.live.com/blog/cns!8A48A27460FB898A!965.entry)) |
826 | <p>You have an ascending list of numbers, what is the most efficient algorithm you can think of to get the ascending list of sums of every two numbers in that list. Duplicates in the resulting list are irrelevant, you can remove them or avoid them if you like.</p>
<p>To be clear, I'm interested in the algorithm. Feel free to post code in any language and paradigm that you like.</p>
| [
{
"answer_id": 834,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": -1,
"selected": false,
"text": "<p>If you are looking for a truly language agnostic solution then you will be sorely disappointed in my opinion because you'll be stuck with a for loop and some conditionals. However if you opened it up to functional languages or functional language features (I'm looking at you LINQ) then my colleagues here can fill this page with elegant examples in Ruby, Lisp, Erlang, and others.</p>\n"
},
{
"answer_id": 840,
"author": "Peter Burns",
"author_id": 101,
"author_profile": "https://Stackoverflow.com/users/101",
"pm_score": 1,
"selected": false,
"text": "<p>The best I could come up with is to produce a matrix of sums of each pair, and then merge the rows together, a-la merge sort. I feel like I'm missing some simple insight that will reveal a much more efficient solution.</p>\n\n<p>My algorithm, in Haskell:</p>\n\n<pre><code>matrixOfSums list = [[a+b | b <- list, b >= a] | a <- list]\n\nsortedSums = foldl merge [] matrixOfSums\n\n--A normal merge, save that we remove duplicates\nmerge xs [] = xs\nmerge [] ys = ys\nmerge (x:xs) (y:ys) = case compare x y of\n LT -> x:(merge xs (y:ys))\n EQ -> x:(merge xs (dropWhile (==x) ys))\n GT -> y:(merge (x:xs) ys)\n</code></pre>\n\n<p>I found a minor improvement, one that's more amenable to lazy stream-based coding. Instead of merging the columns pair-wise, merge all of them at once. The advantage being that you start getting elements of the list immediately.</p>\n\n<pre><code>-- wide-merge does a standard merge (ala merge-sort) across an arbitrary number of lists\n-- wideNubMerge does this while eliminating duplicates\nwideNubMerge :: Ord a => [[a]] -> [a]\nwideNubMerge ls = wideNubMerge1 $ filter (/= []) ls\nwideNubMerge1 [] = []\nwideNubMerge1 ls = mini:(wideNubMerge rest)\n where mini = minimum $ map head ls\n rest = map (dropWhile (== mini)) ls\n\nbetterSortedSums = wideNubMerge matrixOfSums\n</code></pre>\n\n<p>However, if you know you're going to use all of the sums, and there's no advantage to getting some of them earlier, go with '<code>foldl merge []</code>', as it's faster.</p>\n"
},
{
"answer_id": 884,
"author": "Holtorf",
"author_id": 159,
"author_profile": "https://Stackoverflow.com/users/159",
"pm_score": 2,
"selected": false,
"text": "<p>Rather than coding this out, I figure I'll pseudo-code it in steps and explain my logic, so that better programmers can poke holes in my logic if necessary. </p>\n\n<p>On the first step we start out with a list of numbers length n. For each number we need to create a list of length n-1 becuase we aren't adding a number to itself. By the end we have a list of about n sorted lists that was generated in O(n^2) time.</p>\n\n<pre><code>step 1 (startinglist) \nfor each number num1 in startinglist\n for each number num2 in startinglist\n add num1 plus num2 into templist\n add templist to sumlist\nreturn sumlist \n</code></pre>\n\n<p>In step 2 because the lists were sorted by design (add a number to each element in a sorted list and the list will still be sorted) we can simply do a mergesort by merging each list together rather than mergesorting the whole lot. In the end this should take O(n^2) time.</p>\n\n<pre><code>step 2 (sumlist) \ncreate an empty list mergedlist\nfor each list templist in sumlist\n set mergelist equal to: merge(mergedlist,templist)\nreturn mergedlist\n</code></pre>\n\n<p>The merge method would be then the normal merge step with a check to make sure that there are no duplicate sums. I won't write this out because anyone can look up mergesort.</p>\n\n<p>So there's my solution. The entire algorithm is O(n^2) time. Feel free to point out any mistakes or improvements.</p>\n"
},
{
"answer_id": 6458,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 1,
"selected": false,
"text": "<p>In SQL:</p>\n\n<pre><code>create table numbers(n int not null)\ninsert into numbers(n) values(1),(1), (2), (2), (3), (4)\n\n\nselect distinct num1.n+num2.n sum2n\nfrom numbers num1\ninner join numbers num2 \n on num1.n<>num2.n\norder by sum2n\n</code></pre>\n\n<p>C# LINQ:</p>\n\n<pre><code>List<int> num = new List<int>{ 1, 1, 2, 2, 3, 4};\nvar uNum = num.Distinct().ToList();\nvar sums=(from num1 in uNum\n from num2 in uNum \n where num1!=num2\n select num1+num2).Distinct();\nforeach (var s in sums)\n{\n Console.WriteLine(s);\n}\n</code></pre>\n"
},
{
"answer_id": 7842,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this in two lines in python with</p>\n<pre><code>allSums = set(a+b for a in X for b in X)\nallSums = sorted(allSums)\n</code></pre>\n<p>The cost of this is <code>n^2</code> (maybe an extra log factor for the set?) for the iteration and s * log(s) for the sorting where s is the size of the set.</p>\n<p>The size of the set could be as big as <code>n*(n-1)/2</code> for example if <code>X = [1,2,4,...,2^n]</code>. So if you want to generate this list it will take at least <code>n^2/2</code> in the worst case since this is the size of the output.</p>\n<p>However if you want to select the first k elements of the result you can do this in O(kn) using a selection algorithm for sorted <code>X+Y</code> matrices by Frederickson and Johnson (<a href=\"http://arxiv.org/abs/0804.0936\" rel=\"nofollow noreferrer\">see here for gory details)</a>. Although this can probably be modified to generate them online by reusing computation and get an efficient generator for this set.</p>\n<p>@deuseldorf, Peter\nThere is some confusion about <code>(n!)</code> I seriously doubt deuseldorf meant "n factorial" but simply "n, (very excited)!"</p>\n"
},
{
"answer_id": 20701,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 1,
"selected": false,
"text": "<p>This question has been wracking my brain for about a day now. Awesome.</p>\n\n<p>Anyways, you can't get away from the n^2 nature of it easily, but you can do slightly better with the merge since you can bound the range to insert each element in.</p>\n\n<p>If you look at all the lists you generate, they have the following form:</p>\n\n<p><code>(a[i], a[j]) | j>=i</code></p>\n\n<p>If you flip it 90 degrees, you get:</p>\n\n<p><code>(a[i], a[j]) | i<=j</code></p>\n\n<p>Now, the merge process should be taking two lists <code>i</code> and <code>i+1</code> (which correspond to lists where the first member is always <code>a[i]</code> and <code>a[i+1]</code>), you can bound the range to insert element <code>(a[i + 1], a[j])</code> into list <code>i</code> by the location of <code>(a[i], a[j])</code> and the location of <code>(a[i + 1], a[j + 1])</code>.</p>\n\n<p>This means that you should merge in reverse in terms of <code>j</code>. I don't know (yet) if you can leverage this across <code>j</code> as well, but it seems possible.</p>\n"
},
{
"answer_id": 97294,
"author": "porges",
"author_id": 10311,
"author_profile": "https://Stackoverflow.com/users/10311",
"pm_score": 5,
"selected": true,
"text": "<p>Edit as of 2018: You should probably stop reading this. (But I can't delete it as it is accepted.)</p>\n\n<p>If you write out the sums like this:</p>\n\n<pre><code>1 4 5 6 8 9\n---------------\n2 5 6 7 9 10\n 8 9 10 12 13\n 10 11 13 14\n 12 14 15\n 16 17\n 18\n</code></pre>\n\n<p>You'll notice that since M[i,j] <= M[i,j+1] and M[i,j] <= M[i+1,j], then you only need to examine the top left \"corners\" and choose the lowest one.</p>\n\n<p>e.g.</p>\n\n<ul>\n<li>only 1 top left corner, pick 2</li>\n<li>only 1, pick 5</li>\n<li>6 or 8, pick 6</li>\n<li>7 or 8, pick 7</li>\n<li>9 or 8, pick 8</li>\n<li>9 or 9, pick both :)</li>\n<li>10 or 10 or 10, pick all</li>\n<li>12 or 11, pick 11</li>\n<li>12 or 12, pick both</li>\n<li>13 or 13, pick both</li>\n<li>14 or 14, pick both</li>\n<li>15 or 16, pick 15</li>\n<li>only 1, pick 16</li>\n<li>only 1, pick 17</li>\n<li>only 1, pick 18</li>\n</ul>\n\n<p>Of course, when you have <em>lots</em> of top left corners then this solution devolves.</p>\n\n<p>I'm pretty sure this problem is Ω(n²), because you have to calculate the sums for each M[i,j] -- unless someone has a better algorithm for the summation :)</p>\n"
},
{
"answer_id": 97567,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": 1,
"selected": false,
"text": "<p>No matter what you do, without additional constraints on the input values, you cannot do better than O(n^2), simply because you have to iterate through all pairs of numbers. The iteration will dominate sorting (which you can do in O(n log n) or faster).</p>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101/"
] | You have an ascending list of numbers, what is the most efficient algorithm you can think of to get the ascending list of sums of every two numbers in that list. Duplicates in the resulting list are irrelevant, you can remove them or avoid them if you like.
To be clear, I'm interested in the algorithm. Feel free to post code in any language and paradigm that you like. | Edit as of 2018: You should probably stop reading this. (But I can't delete it as it is accepted.)
If you write out the sums like this:
```
1 4 5 6 8 9
---------------
2 5 6 7 9 10
8 9 10 12 13
10 11 13 14
12 14 15
16 17
18
```
You'll notice that since M[i,j] <= M[i,j+1] and M[i,j] <= M[i+1,j], then you only need to examine the top left "corners" and choose the lowest one.
e.g.
* only 1 top left corner, pick 2
* only 1, pick 5
* 6 or 8, pick 6
* 7 or 8, pick 7
* 9 or 8, pick 8
* 9 or 9, pick both :)
* 10 or 10 or 10, pick all
* 12 or 11, pick 11
* 12 or 12, pick both
* 13 or 13, pick both
* 14 or 14, pick both
* 15 or 16, pick 15
* only 1, pick 16
* only 1, pick 17
* only 1, pick 18
Of course, when you have *lots* of top left corners then this solution devolves.
I'm pretty sure this problem is Ω(n²), because you have to calculate the sums for each M[i,j] -- unless someone has a better algorithm for the summation :) |
832 | <p>SQL:</p>
<pre><code>SELECT
u.id,
u.name,
isnull(MAX(h.dateCol), '1900-01-01') dateColWithDefault
FROM universe u
LEFT JOIN history h
ON u.id=h.id
AND h.dateCol<GETDATE()-1
GROUP BY u.Id, u.name
</code></pre>
| [
{
"answer_id": 837,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 4,
"selected": true,
"text": "<p>A solution, albeit one that defers handling of the null value to the code, could be:</p>\n\n<blockquote>\n <p>DateTime yesterday = DateTime.Now.Date.AddDays(-1);</p>\n</blockquote>\n\n<pre><code>var collection=\n from u in db.Universe\n select new\n {\n u.id,\n u.name,\n MaxDate =(DateTime?)\n (\n from h in db.History\n where u.Id == h.Id\n && h.dateCol < yesterday\n select h.dateCol \n ).Max()\n };\n</code></pre>\n\n<p>This does not produce exactly the same SQL, but does provide the same logical result. Translating \"complex\" SQL queries to LINQ is not always straightforward.</p>\n"
},
{
"answer_id": 33140,
"author": "AdamB",
"author_id": 2176,
"author_profile": "https://Stackoverflow.com/users/2176",
"pm_score": 0,
"selected": false,
"text": "<p>This isn't a full answer for you, but on the left join piece you can use the DefaultIfEmpty operator like so:</p>\n\n<pre><code>var collection = \nfrom u in db.Universe\njoin history in db.History on u.id = history.id into temp\nfrom h in temp.DefaultIfEmpty()\nwhere h.dateCol < DateTime.Now.Date.AddDays(-1)\nselect u.id, u.name, h.dateCol ?? '1900-01-01'\n</code></pre>\n\n<p>I haven't had the need to do any <code>groupby</code> commands yet, so I left that out as to not send you down the wrong path. Two other quick things to note. I have been unable to actually join on two parameters although as above there are ways to get around it. Also, the ?? operator works really well in place of the <code>isnull</code> in SQL. </p>\n"
},
{
"answer_id": 80296,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 0,
"selected": false,
"text": "<p>You're going to want to use the <code>join into</code> construct to create a group query.</p>\n\n<pre><code>TestContext db = new TestContext(CreateSparqlTripleStore());\nvar q = from a in db.Album\n join t in db.Track on a.Name equals t.AlbumName into tracks\n select new Album{Name = a.Name, Tracks = tracks};\nforeach(var album in q){\n Console.WriteLine(album.Name);\n foreach (Track track in album.Tracks)\n {\n Console.WriteLine(track.Title);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36693733,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var collection=\n from u in db.Universe\n select new\n {\n u.id,\n u.name,\n MaxDate =(DateTime?)\n (\n from h in db.History\n where u.Id == h.Id\n && h.dateCol < yesterday\n select h.dateCol \n ).Max()\n };\n</code></pre>\n\n<p>Just youse the above code and this should work fine!</p>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/224/"
] | SQL:
```
SELECT
u.id,
u.name,
isnull(MAX(h.dateCol), '1900-01-01') dateColWithDefault
FROM universe u
LEFT JOIN history h
ON u.id=h.id
AND h.dateCol<GETDATE()-1
GROUP BY u.Id, u.name
``` | A solution, albeit one that defers handling of the null value to the code, could be:
>
> DateTime yesterday = DateTime.Now.Date.AddDays(-1);
>
>
>
```
var collection=
from u in db.Universe
select new
{
u.id,
u.name,
MaxDate =(DateTime?)
(
from h in db.History
where u.Id == h.Id
&& h.dateCol < yesterday
select h.dateCol
).Max()
};
```
This does not produce exactly the same SQL, but does provide the same logical result. Translating "complex" SQL queries to LINQ is not always straightforward. |
835 | <p>I'm trying to setup CruiseControl.net at the moment. So far it works nice, but I have a Problem with the MSBuild Task.</p>
<p>According to the <a href="http://confluence.public.thoughtworks.org/display/CCNET/MsBuild+Task" rel="noreferrer">Documentation</a>, it passes CCNetArtifactDirectory to MSBuild. But how do I use it?</p>
<p>I tried this:</p>
<pre><code><buildArgs>
/noconsolelogger /p:OutputPath=$(CCNetArtifactDirectory)\test
</buildArgs>
</code></pre>
<p>But that does not work. In fact, it kills the service with this error:</p>
<blockquote>
<p>ThoughtWorks.CruiseControl.Core.Config.Preprocessor.EvaluationException: Reference to unknown symbol CCNetArtifactDirectory</p>
</blockquote>
<p>Documentation is rather sparse, and google und mainly offers modifying the .sln Project file, which is what I want to avoid in order to be able to manually build this project later - I would really prefer <code>/p:OutputPath</code>.</p>
| [
{
"answer_id": 1023,
"author": "FryHard",
"author_id": 231,
"author_profile": "https://Stackoverflow.com/users/231",
"pm_score": 4,
"selected": true,
"text": "<p>The CCNetArtifactDirectory is passed to the MSBuild by default, so you dont need to worry about it. MSBuild will place the build output in the \"bin location\" relevant to the working directory that you have specified.</p>\n\n<pre><code><executable>c:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MSBuild.exe</executable>\n<workingDirectory>C:\\data\\projects\\FooSolution\\</workingDirectory>\n<projectFile>FooSolution.sln</projectFile>\n<buildArgs>/noconsolelogger /p:Configuration=Debug </buildArgs>\n</code></pre>\n\n<p>So in the above example your build output will be put in C:\\data\\projects\\FooSolution[ProjectName]\\bin\\Debug. Should you want to output to a different location you may want to look at of the tag in CCNET.</p>\n\n<pre><code><publishers>\n <xmllogger />\n <buildpublisher>\n <sourceDir>C:\\data\\projects\\FooSolution\\FooProject\\bin\\Debug</sourceDir>\n <publishDir>C:\\published\\FooSolution\\</publishDir>\n <useLabelSubDirectory>false</useLabelSubDirectory>\n </buildpublisher>\n</publishers>\n</code></pre>\n\n<p>This will allow you to publish your output to a different location.</p>\n"
},
{
"answer_id": 1281,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the artifact directory variable inside the MSBuild script itself. Here's an example of how I'm running FxCop right now from my CC.Net MSBuild script (this script is what CC.Net points to - there is also a \"Build\" target in the script that includes an MSBuild task against the SLN to do the actual compilation):</p>\n\n<pre><code><Exec\n Command='FxCopCmd.exe /project:\"$(MSBuildProjectDirectory)\\FXCopRules.FxCop\" /out:\"$(CCNetArtifactDirectory)\\ProjectName.FxCop.xml\"'\n WorkingDirectory=\"C:\\Program Files\\Microsoft FxCop 1.35\"\n ContinueOnError=\"true\"\n IgnoreExitCode=\"true\"\n/>\n</code></pre>\n"
},
{
"answer_id": 2343524,
"author": "The Chairman",
"author_id": 38029,
"author_profile": "https://Stackoverflow.com/users/38029",
"pm_score": 2,
"selected": false,
"text": "<p>Parameters like <code>CCNetArtifactDirectory</code> are passed to external programs using environment variables. They are available in the external program but they aren't inside <code>CCNET</code> configuration. This often leads to confusion.</p>\n\n<p>You can use a preprocessor constant instead: </p>\n\n<pre><code><cb:define project.artifactDirectory=\"C:\\foo\">\n<project>\n <!-- [...] -->\n <artifactDirectory>$(project.artifactDirectory)</artifactDirectory>\n <!-- [...] -->\n <tasks>\n <!-- [...] -->\n <msbuild>\n <!-- [...] -->\n <buildArgs>/noconsolelogger /p:OutputPath=$(project.artifactDirectory)\\test</buildArgs>\n <!-- [...] -->\n </msbuild>\n <!-- [...] -->\n </tasks>\n <!-- [...] -->\n</project>\n</code></pre>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | I'm trying to setup CruiseControl.net at the moment. So far it works nice, but I have a Problem with the MSBuild Task.
According to the [Documentation](http://confluence.public.thoughtworks.org/display/CCNET/MsBuild+Task), it passes CCNetArtifactDirectory to MSBuild. But how do I use it?
I tried this:
```
<buildArgs>
/noconsolelogger /p:OutputPath=$(CCNetArtifactDirectory)\test
</buildArgs>
```
But that does not work. In fact, it kills the service with this error:
>
> ThoughtWorks.CruiseControl.Core.Config.Preprocessor.EvaluationException: Reference to unknown symbol CCNetArtifactDirectory
>
>
>
Documentation is rather sparse, and google und mainly offers modifying the .sln Project file, which is what I want to avoid in order to be able to manually build this project later - I would really prefer `/p:OutputPath`. | The CCNetArtifactDirectory is passed to the MSBuild by default, so you dont need to worry about it. MSBuild will place the build output in the "bin location" relevant to the working directory that you have specified.
```
<executable>c:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable>
<workingDirectory>C:\data\projects\FooSolution\</workingDirectory>
<projectFile>FooSolution.sln</projectFile>
<buildArgs>/noconsolelogger /p:Configuration=Debug </buildArgs>
```
So in the above example your build output will be put in C:\data\projects\FooSolution[ProjectName]\bin\Debug. Should you want to output to a different location you may want to look at of the tag in CCNET.
```
<publishers>
<xmllogger />
<buildpublisher>
<sourceDir>C:\data\projects\FooSolution\FooProject\bin\Debug</sourceDir>
<publishDir>C:\published\FooSolution\</publishDir>
<useLabelSubDirectory>false</useLabelSubDirectory>
</buildpublisher>
</publishers>
```
This will allow you to publish your output to a different location. |
845 | <p>Suppose I have the following CSS rule in my page:</p>
<pre class="lang-css prettyprint-override"><code>body {
font-family: Calibri, Trebuchet MS, Helvetica, sans-serif;
}
</code></pre>
<p>How could I detect which one of the defined fonts were used in the user's browser?</p>
<p>For people wondering why I want to do this is because the font I'm detecting contains glyphs that are <em>not</em> available in other fonts. If the user does <em>not</em> have the font, then I want it to display a link asking the user to download that font (so they can use my web application with the correct font).</p>
<p>Currently, I am displaying the download font link for all users. I want to only display this for people who do <em>not</em> have the correct font installed.</p>
| [
{
"answer_id": 849,
"author": "MojoFilter",
"author_id": 93,
"author_profile": "https://Stackoverflow.com/users/93",
"pm_score": 7,
"selected": true,
"text": "<p>I've seen it done in a kind of iffy, but pretty reliable way. Basically, an element is set to use a specific font and a string is set to that element. If the font set for the element does not exist, it takes the font of the parent element. So, what they do is measure the width of the rendered string. If it matches what they expected for the desired font as opposed to the derived font, it's present. This won't work for monospaced fonts.</p>\n\n<p>Here's where it came from:\n<a href=\"http://ajaxian.com/archives/javascriptcss-font-detector\" rel=\"noreferrer\">Javascript/CSS Font Detector (ajaxian.com; 12 Mar 2007)</a></p>\n"
},
{
"answer_id": 27035,
"author": "runeh",
"author_id": 2906,
"author_profile": "https://Stackoverflow.com/users/2906",
"pm_score": 4,
"selected": false,
"text": "<p>A technique that works is to look at the computed style of the element. This is supported in Opera and Firefox (and I recon in safari, but haven't tested). IE (7 at least), provides a method to get a style, but it seems to be whatever was in the stylesheet, not the computed style. More details on quirksmode: <a href=\"http://www.quirksmode.org/dom/getstyles.html\" rel=\"noreferrer\">Get Styles</a></p>\n\n<p>Here's a simple function to grab the font used in an element:</p>\n\n<pre><code>/**\n * Get the font used for a given element\n * @argument {HTMLElement} the element to check font for\n * @returns {string} The name of the used font or null if font could not be detected\n */\nfunction getFontForElement(ele) {\n if (ele.currentStyle) { // sort of, but not really, works in IE\n return ele.currentStyle[\"fontFamily\"];\n } else if (document.defaultView) { // works in Opera and FF\n return document.defaultView.getComputedStyle(ele,null).getPropertyValue(\"font-family\");\n } else {\n return null;\n }\n}\n</code></pre>\n\n<p>If the CSS rule for this was:</p>\n\n<pre><code>#fonttester {\n font-family: sans-serif, arial, helvetica;\n}\n</code></pre>\n\n<p>Then it should return helvetica if that is installed, if not, arial, and lastly, the name of the system default sans-serif font. Note that the ordering of fonts in your CSS declaration is significant.</p>\n\n<p>An interesting hack you could also try is to create lots of hidden elements with lots of different fonts to try to detect which fonts are installed on a machine. I'm sure someone could make a nifty font statistics gathering page with this technique.</p>\n"
},
{
"answer_id": 887291,
"author": "philoye",
"author_id": 109864,
"author_profile": "https://Stackoverflow.com/users/109864",
"pm_score": 4,
"selected": false,
"text": "<p>@pat Actually, Safari does not give the font used, Safari instead always returns the first font in the stack regardless of whether it is installed, at least in my experience.</p>\n\n<pre><code>font-family: \"my fake font\", helvetica, san-serif;\n</code></pre>\n\n<p>Assuming Helvetica is the one installed/used, you'll get:</p>\n\n<ul>\n<li>\"my fake font\" in Safari (and I believe other webkit browsers).</li>\n<li>\"my fake font, helvetica, san-serif\" in Gecko browsers and IE. </li>\n<li>\"helvetica\" in Opera 9, though I read that they are changing this in Opera 10 to match\nGecko.</li>\n</ul>\n\n<p>I took a pass at this problem and created <a href=\"http://github.com/philoye/fontunstack/tree/master\" rel=\"noreferrer\">Font Unstack</a>, which tests each font in a stack and returns the first installed one only. It uses the trick that @MojoFilter mentions, but only returns the first one if multiple are installed. Though it does suffer from the weakness that @tlrobinson mentions (Windows will substitute Arial for Helvetica silently and report that Helvetica is installed), it otherwise works well.</p>\n"
},
{
"answer_id": 6083463,
"author": "Derek 朕會功夫",
"author_id": 283863,
"author_profile": "https://Stackoverflow.com/users/283863",
"pm_score": 5,
"selected": false,
"text": "<p>I wrote a simple JavaScript tool that you can use it to check if a font is installed or not.<br>\nIt uses simple technique and should be correct most of the time.\n<br></p>\n\n<p><strong><a href=\"https://github.com/derek1906/jFont-Checker/\" rel=\"noreferrer\">jFont Checker</a></strong> on github</p>\n"
},
{
"answer_id": 7866425,
"author": "Facebiz",
"author_id": 1009517,
"author_profile": "https://Stackoverflow.com/users/1009517",
"pm_score": 3,
"selected": false,
"text": "<p>A simplified form is:</p>\n\n<pre><code>function getFont() {\n return document.getElementById('header').style.font;\n}\n</code></pre>\n\n<p>If you need something more complete, check <a href=\"http://www.lalit.org/lab/javascript-css-font-detect/#comment-43\" rel=\"noreferrer\">this</a> out.</p>\n"
},
{
"answer_id": 8307897,
"author": "Naeem Ul Wahhab",
"author_id": 1067051,
"author_profile": "https://Stackoverflow.com/users/1067051",
"pm_score": 3,
"selected": false,
"text": "<p>There is a simple solution - just use <code>element.style.font</code>:</p>\n\n<pre><code>function getUserBrowsersFont() {\n var browserHeader = document.getElementById('header');\n return browserHeader.style.font;\n}\n</code></pre>\n\n<p>This function will exactly do what you want. On execution It will return the font type of the user/browser. Hope this will help.</p>\n"
},
{
"answer_id": 8741592,
"author": "PaulnOZ",
"author_id": 1131991,
"author_profile": "https://Stackoverflow.com/users/1131991",
"pm_score": 3,
"selected": false,
"text": "<p>Another solution would be to install the font automatically via <code>@font-face</code> which might negate the need for detection.</p>\n<pre class=\"lang-css prettyprint-override\"><code>@font-face {\n font-family: "Calibri";\n src: url("http://www.yourwebsite.com/fonts/Calibri.eot");\n src: local("Calibri"), url("http://www.yourwebsite.com/fonts/Calibri.ttf") format("truetype");\n}\n</code></pre>\n<p>Of course it wouldn't solve any copyright issues, however you could always use a freeware font or even make your own font. You will need both <code>.eot</code> & <code>.ttf</code> files to work best.</p>\n"
},
{
"answer_id": 13385418,
"author": "Mark Kimitch",
"author_id": 1090092,
"author_profile": "https://Stackoverflow.com/users/1090092",
"pm_score": 3,
"selected": false,
"text": "<p>Calibri is a font owned by Microsoft, and shouldn't be distributed for free. Also, requiring a user to download a specific font isn't very user-friendly. </p>\n\n<p>I would suggest purchasing a license for the font and embedding it into your application.</p>\n"
},
{
"answer_id": 29582806,
"author": "user2267379",
"author_id": 2267379,
"author_profile": "https://Stackoverflow.com/users/2267379",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this website :</p>\n\n<p><a href=\"http://website-font-analyzer.com/\" rel=\"nofollow noreferrer\">http://website-font-analyzer.com/</a></p>\n\n<p>It does exactly what you want...</p>\n"
},
{
"answer_id": 42756664,
"author": "Woppi",
"author_id": 2098493,
"author_profile": "https://Stackoverflow.com/users/2098493",
"pm_score": 2,
"selected": false,
"text": "<p>I am using Fount. You just have to drag the Fount button to your bookmarks bar, click on it and then click on a specific text on the website. It will then show the font of that text. </p>\n\n<p><a href=\"https://fount.artequalswork.com/\" rel=\"nofollow noreferrer\">https://fount.artequalswork.com/</a></p>\n"
},
{
"answer_id": 47571799,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 2,
"selected": false,
"text": "<p>You can put <a href=\"https://technet.microsoft.com/en-us/library/cc939627.aspx\" rel=\"nofollow noreferrer\">Adobe Blank</a> in the font-family after the font you want to see, and then any glyphs not in that font won't be rendered.</p>\n\n<p>e.g.:</p>\n\n<pre><code>font-family: Arial, 'Adobe Blank';\n</code></pre>\n\n<p>As far as I'm aware there is no JS method to tell which glyphs in an element are being rendered by which font in the font stack for that element.</p>\n\n<p>This is complicated by the fact that browsers have user settings for serif/sans-serif/monospace fonts and they also have their own hard-coded fall-back fonts that they will use if a glyph is not found in any of the fonts in a font stack. <strong>So browser may render some glyphs in a font that is not in the font stack or the user's browser font setting.</strong> <a href=\"https://developers.google.com/web/updates/2013/09/DevTools-answers-What-font-is-that\" rel=\"nofollow noreferrer\">Chrome Dev Tools will show you each rendered font for the glyphs in the selected element</a>. So on your machine you can see what it's doing, but there's no way to tell what's happening on a user's machine.</p>\n\n<p>It's also possible the user's system may play a part in this as e.g. <a href=\"https://learn.microsoft.com/en-us/globalization/input/font-technology#font-linking\" rel=\"nofollow noreferrer\">Window does Font Substitution</a> at the glyph level.</p>\n\n<p>so...</p>\n\n<p>For the glyphs you are interested in, you have no way of knowing whether they will be rendered by the user's browser/system fallback, even if they don't have the font you specify.</p>\n\n<p>If you want to test it in JS you could render individual glyphs with a font-family including Adobe Blank and measure their width to see if it is zero, <strong>BUT</strong> you'd have to iterate thorough each glyph and <strong>each font you wanted to test</strong>, but although you can know the fonts in an elements font stack there is no way of knowing what fonts the user's browser is configured to use so for at least some of your users the list of fonts you iterate through will be incomplete. (It is also not future proof if new fonts come out and start getting used.)</p>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238/"
] | Suppose I have the following CSS rule in my page:
```css
body {
font-family: Calibri, Trebuchet MS, Helvetica, sans-serif;
}
```
How could I detect which one of the defined fonts were used in the user's browser?
For people wondering why I want to do this is because the font I'm detecting contains glyphs that are *not* available in other fonts. If the user does *not* have the font, then I want it to display a link asking the user to download that font (so they can use my web application with the correct font).
Currently, I am displaying the download font link for all users. I want to only display this for people who do *not* have the correct font installed. | I've seen it done in a kind of iffy, but pretty reliable way. Basically, an element is set to use a specific font and a string is set to that element. If the font set for the element does not exist, it takes the font of the parent element. So, what they do is measure the width of the rendered string. If it matches what they expected for the desired font as opposed to the derived font, it's present. This won't work for monospaced fonts.
Here's where it came from:
[Javascript/CSS Font Detector (ajaxian.com; 12 Mar 2007)](http://ajaxian.com/archives/javascriptcss-font-detector) |
879 | <p>Are PHP variables passed by value or by reference?</p>
| [
{
"answer_id": 880,
"author": "Karl Seguin",
"author_id": 34,
"author_profile": "https://Stackoverflow.com/users/34",
"pm_score": -1,
"selected": false,
"text": "<p>Depends on the version, 4 is by value, 5 is by reference.</p>\n"
},
{
"answer_id": 881,
"author": "cmcculloh",
"author_id": 58,
"author_profile": "https://Stackoverflow.com/users/58",
"pm_score": 5,
"selected": false,
"text": "<p>PHP variables are assigned by value, passed to functions by value and when containing/representing objects are passed by reference. You can force variables to pass by reference using an '&'.</p>\n<p>Assigned by value/reference example:</p>\n<pre><code>$var1 = "test";\n$var2 = $var1;\n$var2 = "new test";\n$var3 = &$var2;\n$var3 = "final test";\n\nprint ("var1: $var1, var2: $var2, var3: $var3);\n</code></pre>\n<p>output:</p>\n<blockquote>\n<p>var1: test, var2: final test, var3: final test</p>\n</blockquote>\n<p>Passed by value/reference example:</p>\n<pre><code>$var1 = "foo";\n$var2 = "bar";\n\nchangeThem($var1, $var2);\n\nprint "var1: $var1, var2: $var2";\n\nfunction changeThem($var1, &$var2){\n $var1 = "FOO";\n $var2 = "BAR";\n}\n</code></pre>\n<p>output:</p>\n<blockquote>\n<p>var1: foo, var2 BAR</p>\n</blockquote>\n<p>Object variables passed by reference example:</p>\n<pre><code>class Foo{\n public $var1;\n\n function __construct(){\n $this->var1 = "foo";\n }\n\n public function printFoo(){\n print $this->var1;\n }\n}\n\n\n$foo = new Foo();\n\nchangeFoo($foo);\n\n$foo->printFoo();\n\nfunction changeFoo($foo){\n $foo->var1 = "FOO";\n}\n</code></pre>\n<p>output:</p>\n<blockquote>\n<p>FOO</p>\n</blockquote>\n<p>(The last example could be better probably.)</p>\n"
},
{
"answer_id": 885,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 10,
"selected": true,
"text": "<p>It's by value according to the <a href=\"http://php.net/manual/en/functions.arguments.php\" rel=\"noreferrer\">PHP Documentation</a>.</p>\n\n<blockquote>\n <p>By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.</p>\n \n <p>To have an argument to a function always passed by reference, prepend an ampersand (<strong>&</strong>) to the argument name in the function definition.</p>\n</blockquote>\n\n<pre><code><?php\nfunction add_some_extra(&$string)\n{\n $string .= 'and something extra.';\n}\n\n$str = 'This is a string, ';\nadd_some_extra($str);\necho $str; // outputs 'This is a string, and something extra.'\n?>\n</code></pre>\n"
},
{
"answer_id": 896,
"author": "Karl Seguin",
"author_id": 34,
"author_profile": "https://Stackoverflow.com/users/34",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://www.php.net/manual/en/migration5.oop.php\" rel=\"noreferrer\">http://www.php.net/manual/en/migration5.oop.php</a></p>\n\n<blockquote>\n <p>In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).</p>\n</blockquote>\n"
},
{
"answer_id": 897,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 3,
"selected": false,
"text": "<p>Variables containing primitive types are passed by value in PHP5. Variables containing objects are passed by reference. There's quite an interesting article from Linux Journal from 2006 which mentions this and other OO differences between 4 and 5.</p>\n\n<p><a href=\"http://www.linuxjournal.com/article/9170\" rel=\"noreferrer\">http://www.linuxjournal.com/article/9170</a></p>\n"
},
{
"answer_id": 7483,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 6,
"selected": false,
"text": "<p>It seems a lot of people get confused by the way objects are passed to functions and what passing by reference means. Object are still passed by value, it's just the value that is passed in PHP5 is a reference handle. As proof:</p>\n<pre><code><?php\nclass Holder {\n private $value;\n\n public function __construct($value) {\n $this->value = $value;\n }\n\n public function getValue() {\n return $this->value;\n }\n}\n\nfunction swap($x, $y) {\n $tmp = $x;\n $x = $y;\n $y = $tmp;\n}\n\n$a = new Holder('a');\n$b = new Holder('b');\nswap($a, $b);\n\necho $a->getValue() . ", " . $b->getValue() . "\\n";\n</code></pre>\n<p>Outputs:</p>\n<pre><code>a, b\n</code></pre>\n<p>To <a href=\"http://en.wikipedia.org/wiki/Pass_by_reference#Call_by_reference\" rel=\"nofollow noreferrer\">pass by reference</a> means we can modify the variables that are seen by the caller, which clearly the code above does not do. We need to change the swap function to:</p>\n<pre><code><?php\nfunction swap(&$x, &$y) {\n $tmp = $x;\n $x = $y;\n $y = $tmp;\n}\n\n$a = new Holder('a');\n$b = new Holder('b');\nswap($a, $b);\n\necho $a->getValue() . ", " . $b->getValue() . "\\n";\n</code></pre>\n<p>Outputs:</p>\n<pre><code>b, a\n</code></pre>\n<p>in order to pass by reference.</p>\n"
},
{
"answer_id": 574631,
"author": "Bingy",
"author_id": 69518,
"author_profile": "https://Stackoverflow.com/users/69518",
"pm_score": 3,
"selected": false,
"text": "<p>You can do it either way.</p>\n<p>Put an '&' symbol in front and the variable you are passing becomes one and the same as its origin i.e. you can pass by reference, rather than make a copy of it.</p>\n<p>so</p>\n<pre><code> $fred = 5;\n $larry = & $fred;\n $larry = 8;\n echo $fred;//this will output 8, as larry and fred are now the same reference.\n</code></pre>\n"
},
{
"answer_id": 2034022,
"author": "Miha",
"author_id": 247128,
"author_profile": "https://Stackoverflow.com/users/247128",
"pm_score": 1,
"selected": false,
"text": "<p>Objects are passed by reference in PHP 5 and by value in PHP 4.\nVariables are passed by value by default!</p>\n\n<p>Read here: <a href=\"http://www.webeks.net/programming/php/ampersand-operator-used-for-assigning-reference.html\" rel=\"nofollow noreferrer\">http://www.webeks.net/programming/php/ampersand-operator-used-for-assigning-reference.html</a></p>\n"
},
{
"answer_id": 2812176,
"author": "Ricardo Saracino",
"author_id": 338456,
"author_profile": "https://Stackoverflow.com/users/338456",
"pm_score": 1,
"selected": false,
"text": "<pre><code>class Holder\n{\n private $value;\n\n public function __construct( $value )\n {\n $this->value = $value;\n }\n\n public function getValue()\n {\n return $this->value;\n }\n\n public function setValue( $value )\n {\n return $this->value = $value;\n }\n}\n\nclass Swap\n{ \n public function SwapObjects( Holder $x, Holder $y )\n {\n $tmp = $x;\n\n $x = $y;\n\n $y = $tmp;\n }\n\n public function SwapValues( Holder $x, Holder $y )\n {\n $tmp = $x->getValue();\n\n $x->setValue($y->getValue());\n\n $y->setValue($tmp);\n }\n}\n\n\n$a1 = new Holder('a');\n\n$b1 = new Holder('b');\n\n\n\n$a2 = new Holder('a');\n\n$b2 = new Holder('b');\n\n\nSwap::SwapValues($a1, $b1);\n\nSwap::SwapObjects($a2, $b2);\n\n\n\necho 'SwapValues: ' . $a2->getValue() . \", \" . $b2->getValue() . \"<br>\";\n\necho 'SwapObjects: ' . $a1->getValue() . \", \" . $b1->getValue() . \"<br>\";\n</code></pre>\n\n<p>Attributes are still modifiable when not passed by reference so beware.</p>\n\n<p>Output:</p>\n\n<p>SwapObjects: b, a\nSwapValues: a, b</p>\n"
},
{
"answer_id": 9696799,
"author": "hardik",
"author_id": 805437,
"author_profile": "https://Stackoverflow.com/users/805437",
"pm_score": 7,
"selected": false,
"text": "<p>In PHP, by default, objects are passed as reference to a new object.</p>\n<p>See this example:</p>\n<pre><code>class X {\n var $abc = 10; \n}\n\nclass Y {\n\n var $abc = 20; \n function changeValue($obj)\n {\n $obj->abc = 30;\n }\n}\n\n$x = new X();\n$y = new Y();\n\necho $x->abc; //outputs 10\n$y->changeValue($x);\necho $x->abc; //outputs 30\n</code></pre>\n<p>Now see this:</p>\n<pre><code>class X {\n var $abc = 10; \n}\n\nclass Y {\n\n var $abc = 20; \n function changeValue($obj)\n {\n $obj = new Y();\n }\n}\n\n$x = new X();\n$y = new Y();\n\necho $x->abc; //outputs 10\n$y->changeValue($x);\necho $x->abc; //outputs 10 not 20 same as java does.\n</code></pre>\n<p>Now see this:</p>\n<pre><code>class X {\n var $abc = 10; \n}\n\nclass Y {\n\n var $abc = 20; \n function changeValue(&$obj)\n {\n $obj = new Y();\n }\n}\n\n$x = new X();\n$y = new Y();\n\necho $x->abc; //outputs 10\n$y->changeValue($x);\necho $x->abc; //outputs 20 not possible in java.\n</code></pre>\n<p>I hope you can understand this.</p>\n"
},
{
"answer_id": 27588152,
"author": "Mahsin",
"author_id": 3699965,
"author_profile": "https://Stackoverflow.com/users/3699965",
"pm_score": 3,
"selected": false,
"text": "<p>You can pass a variable to a function by reference. This function will be able to modify the original variable.</p>\n\n<p>You can define the passage by reference in the function definition:</p>\n\n<pre><code><?php\nfunction changeValue(&$var)\n{\n $var++;\n}\n\n$result=5;\nchangeValue($result);\n\necho $result; // $result is 6 here\n?>\n</code></pre>\n"
},
{
"answer_id": 31429088,
"author": "atif",
"author_id": 5027344,
"author_profile": "https://Stackoverflow.com/users/5027344",
"pm_score": 0,
"selected": false,
"text": "<p>Actually both methods are valid but it depends upon your requirement. Passing values by reference often makes your script slow. So it's better to pass variables by value considering time of execution. Also the code flow is more consistent when you pass variables by value.</p>\n"
},
{
"answer_id": 49587783,
"author": "PPL",
"author_id": 9411789,
"author_profile": "https://Stackoverflow.com/users/9411789",
"pm_score": 0,
"selected": false,
"text": "<p>Use this for functions when you wish to simply alter the original variable and return it again to the same variable name with its new value assigned.</p>\n\n<pre><code>function add(&$var){ // The &amp; is before the argument $var\n $var++;\n}\n$a = 1;\n$b = 10;\nadd($a);\necho \"a is $a,\";\nadd($b);\necho \" a is $a, and b is $b\"; // Note: $a and $b are NOT referenced\n</code></pre>\n"
},
{
"answer_id": 60082753,
"author": "AleksandrH",
"author_id": 5323344,
"author_profile": "https://Stackoverflow.com/users/5323344",
"pm_score": 3,
"selected": false,
"text": "<p><strong>TL;DR</strong>: PHP supports both pass by value and pass by reference. References are declared using an ampersand (<code>&</code>); this is very similar to how C++ does it. When the formal parameter of a function is not declared with an ampersand (i.e., it's not a reference), <strong>everything</strong> is passed by value, including objects. There is no distinction between how objects and primitives are passed around. The key is to understand <em>what</em> gets passed along when you pass in objects to a function. This is where understanding pointers is invaluable.</p>\n<p>For anyone who comes across this in the future, I want to share this gem from the <a href=\"https://www.php.net/manual/en/language.oop5.references.php\" rel=\"nofollow noreferrer\">PHP docs, posted by an anonymous user</a>:</p>\n<blockquote>\n<p>There seems to be some confusion here. The distinction between pointers and references is not particularly helpful.\nThe behavior in some of the "comprehensive" examples already posted can be explained in simpler unifying terms. Hayley's code, for example, is doing EXACTLY what you should expect it should. (Using >= 5.3)</p>\n</blockquote>\n<blockquote>\n<p>First principle:\nA pointer stores a memory address to access an object. Any time an object is assigned, a pointer is generated. (I haven't delved TOO deeply into the Zend engine yet, but as far as I can see, this applies)</p>\n</blockquote>\n<blockquote>\n<p>2nd principle, and source of the most confusion:\nPassing a variable to a function is done by default as a value pass, ie, you are working with a copy. "But objects are passed by reference!" A common misconception both here and in the Java world. I never said a copy OF WHAT. The default passing is done by value. Always. WHAT is being copied and passed, however, is the pointer. When using the "->", you will of course be accessing the same internals as the original variable in the caller function. Just using "=" will only play with copies.</p>\n</blockquote>\n<blockquote>\n<p>3rd principle:\n"&" automatically and permanently sets another variable name/pointer to the same memory address as something else until you decouple them. It is correct to use the term "alias" here. Think of it as joining two pointers at the hip until forcibly separated with "unset()". This functionality exists both in the same scope and when an argument is passed to a function. Often the passed argument is called a "reference," due to certain distinctions between "passing by value" and "passing by reference" that were clearer in C and C++.</p>\n</blockquote>\n<blockquote>\n<p>Just remember: pointers to objects, not objects themselves, are passed to functions. These pointers are COPIES of the original unless you use "&" in your parameter list to actually pass the originals. Only when you dig into the internals of an object will the originals change.</p>\n</blockquote>\n<p>And here's the example they provide:</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php\n\n//The two are meant to be the same\n$a = "Clark Kent"; //a==Clark Kent\n$b = &$a; //The two will now share the same fate.\n\n$b="Superman"; // $a=="Superman" too.\necho $a;\necho $a="Clark Kent"; // $b=="Clark Kent" too.\nunset($b); // $b divorced from $a\n$b="Bizarro";\necho $a; // $a=="Clark Kent" still, since $b is a free agent pointer now.\n\n//The two are NOT meant to be the same.\n$c="King";\n$d="Pretender to the Throne";\necho $c."\\n"; // $c=="King"\necho $d."\\n"; // $d=="Pretender to the Throne"\nswapByValue($c, $d);\necho $c."\\n"; // $c=="King"\necho $d."\\n"; // $d=="Pretender to the Throne"\nswapByRef($c, $d);\necho $c."\\n"; // $c=="Pretender to the Throne"\necho $d."\\n"; // $d=="King"\n\nfunction swapByValue($x, $y){\n$temp=$x;\n$x=$y;\n$y=$temp;\n//All this beautiful work will disappear\n//because it was done on COPIES of pointers.\n//The originals pointers still point as they did.\n}\n\nfunction swapByRef(&$x, &$y){\n$temp=$x;\n$x=$y;\n$y=$temp;\n//Note the parameter list: now we switched 'em REAL good.\n}\n\n?>\n</code></pre>\n<p><a href=\"https://www.aleksandrhovhannisyan.com/blog/javascript-pass-by-reference/\" rel=\"nofollow noreferrer\">I wrote an extensive, detailed blog post on this subject for JavaScript</a>, but I believe it applies equally well to PHP, C++, and any other language where people seem to be confused about pass by value vs. pass by reference.</p>\n<p>Clearly, PHP, like C++, is a language that does support pass by reference. By default, objects are passed by value. When working with variables that store objects, it helps to see those variables as pointers (because that is fundamentally what they are, at the assembly level). If you pass a pointer by value, you can still "trace" the pointer and modify the properties of the object being pointed to. What you cannot do is have it point to a different object. Only if you explicitly declare a parameter as being passed by reference will you be able to do that.</p>\n"
},
{
"answer_id": 67052160,
"author": "CGeorgian",
"author_id": 4195727,
"author_profile": "https://Stackoverflow.com/users/4195727",
"pm_score": 1,
"selected": false,
"text": "<p>Regarding how objects are passed to functions you still need to understand that without "&", you pass to the function an object handle , object handle that is still passed by value , and it contains the value of a pointer. But you can not change this pointer until you pass it by reference using the "&"</p>\n<pre><code><?php\n class Example \n {\n public $value;\n \n }\n \n function test1($x) \n {\n //let's say $x is 0x34313131\n $x->value = 1; //will reflect outsite of this function\n //php use pointer 0x34313131 and search for the \n //address of 'value' and change it to 1\n\n }\n \n function test2($x) \n {\n //$x is 0x34313131\n $x = new Example;\n //now $x is 0x88888888\n //this will NOT reflect outside of this function \n //you need to rewrite it as "test2(&$x)"\n $x->value = 1000; //this is 1000 JUST inside this function\n \n \n }\n \n $example = new Example;\n \n $example->value = 0;\n \n test1($example); // $example->value changed to 1\n \n test2($example); // $example did NOT changed to a new object \n // $example->value is still 1\n \n ?>\n</code></pre>\n"
},
{
"answer_id": 68130959,
"author": "HSLM",
"author_id": 2763028,
"author_profile": "https://Stackoverflow.com/users/2763028",
"pm_score": 0,
"selected": false,
"text": "<p>A PHP reference is an alias, allowing two different variables to write to the same value.</p>\n<p>And in PHP, if you have a variable that contains an object, that variable does not contain the object itself. Instead, it contains an identifier for that object. The object accessor will use the identifier to find the actual object. So when we use the object as an argument in function or assign it to another variable, we will be copying the identifier that points to the object itself.</p>\n<p><a href=\"https://hsalem.com/posts/you-think-you-know-php.html\" rel=\"nofollow noreferrer\">https://hsalem.com/posts/you-think-you-know-php.html</a></p>\n<pre><code>class Type {}\n\n$x = new Type();\n$y = $x;\n$y = "New value";\n\nvar_dump($x); // Will print the object.\nvar_dump($y); // Will print the "New value"\n\n$z = &$x; // $z is a reference of $x\n\n$z = "New value";\nvar_dump($x); // Will print "New value"\nvar_dump($z); // Will print "New value"\n\n</code></pre>\n"
}
] | 2008/08/03 | [
"https://Stackoverflow.com/questions/879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
] | Are PHP variables passed by value or by reference? | It's by value according to the [PHP Documentation](http://php.net/manual/en/functions.arguments.php).
>
> By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.
>
>
> To have an argument to a function always passed by reference, prepend an ampersand (**&**) to the argument name in the function definition.
>
>
>
```
<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str; // outputs 'This is a string, and something extra.'
?>
``` |
904 | <p>Given a relatively simple CSS:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
width: 150px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
12333-2333-233-23339392-332332323
</div></code></pre>
</div>
</div>
</p>
<blockquote>
<p>How do I make it so that the string stays constrained to the <code>width</code>
of <strong>150</strong>, and wraps to a new line on the <em>hyphen</em>?</p>
</blockquote>
| [
{
"answer_id": 911,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 7,
"selected": true,
"text": "<p>Replace your hyphens with this:</p>\n\n<pre><code>&shy;\n</code></pre>\n\n<p>It's called a \"soft\" hyphen.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div {\r\n width: 150px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div>\r\n 12333&shy;2333&shy;233&shy;23339392&shy;332332323\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 912,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 4,
"selected": false,
"text": "<p>As part of CSS3, it is not yet fully supported, <a href=\"http://www.css3.info/preview/word-wrap/\" rel=\"noreferrer\">but you can find information on word-wrapping here</a>. Another option is the <a href=\"http://www.quirksmode.org/oddsandends/wbr.html\" rel=\"noreferrer\">wbr tag, &shy;, and &#8203;</a> none of which are fully supported either.</p>\n"
},
{
"answer_id": 67878,
"author": "Dave Rutledge",
"author_id": 2486915,
"author_profile": "https://Stackoverflow.com/users/2486915",
"pm_score": 3,
"selected": false,
"text": "<p>Your example works as expected in Google Chrome, Safari (Windows), and IE8. The text breaks out of the 150px box in Firefox 3 and Opera 9.5.</p>\n\n<p>Additionally <code>&shy;</code> won't work for your example, as it will either:</p>\n\n<ul>\n<li><p>work when word-breaking but when not word-breaking not display any hyphens, or </p></li>\n<li><p>work when not word-breaking but display two hyphens when word-breaking\nsince it adds a hyphen on a break.</p></li>\n</ul>\n"
},
{
"answer_id": 343686,
"author": "Peter T. LaComb Jr.",
"author_id": 8513,
"author_profile": "https://Stackoverflow.com/users/8513",
"pm_score": 3,
"selected": false,
"text": "<p>In this specific instance (where your string is going to contain hyphens) I'd transform the text to this server-side:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div style=\"width:150px;\">\r\n <span>12333-</span><span>2333-</span><span>233-</span><span>23339392-</span><span>332332323</span>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 3725181,
"author": "Orion",
"author_id": 449300,
"author_profile": "https://Stackoverflow.com/users/449300",
"pm_score": 3,
"selected": false,
"text": "<p>Depending on what you want to see exactly, you can use a combination of <code>hyphen</code>, <code>soft hyphen</code>, and/or <code>zero width space</code>.</p>\n\n<p>On a soft hyphen, your browser can word-break (adding an hyphen).\nOn a zero width space, your browser can word break (without adding anything).</p>\n\n<p>Thus, if your code is something like : </p>\n\n<p><code>111111&shy;222222&shy;-333333&#8203;444444-&#8203;555555</code></p>\n\n<p>then your browser will show this with no word-break :</p>\n\n<blockquote>\n <p>1111112222222-33333334444444-5555555</p>\n</blockquote>\n\n<p>and this will every possible word-break :</p>\n\n<blockquote>\n <p>111111-<br/>\n 222222-<br/>\n -333333<br/>\n 444444-<br/>\n 555555</p>\n</blockquote>\n\n<p>Just pick up the option you need. In your case, it may be the one between 4s and 5s.</p>\n"
},
{
"answer_id": 9060345,
"author": "aeskr",
"author_id": 1125471,
"author_profile": "https://Stackoverflow.com/users/1125471",
"pm_score": 5,
"selected": false,
"text": "<p>In all modern browsers<sup>*</sup> (and in some <a href=\"http://www.quirksmode.org/oddsandends/wbr.html\" rel=\"noreferrer\">older browsers</a>, too), the <a href=\"https://developer.mozilla.org/en/HTML/Element/wbr\" rel=\"noreferrer\"><code><wbr></code> element</a> is the perfect tool for providing the opportunity to break long words at specific points.</p>\n\n<p>To quote from that link:</p>\n\n<blockquote>\n <p>The Word Break Opportunity (<code><wbr></code>) HTML element represents a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location.</p>\n</blockquote>\n\n<p>Here's how it could be used to in the OP's example (or see it in action at <a href=\"http://jsfiddle.net/AdleyEskridge/qrgaK/\" rel=\"noreferrer\">JSFiddle</a>):</p>\n\n<pre><code><div style=\"width: 150px;\">\n 12333-<wbr>2333-<wbr>233-<wbr>23339392-<wbr>332332323\n</div>\n</code></pre>\n\n<p><sup>*</sup>I've tested it in IE9, IE10, and the latest versions of Chrome, Firefox, and Opera, and Safari.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div {\r\n width: 150px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div>\r\n 12333-<wbr>2333-<wbr>233-<wbr>23339392-<wbr>332332323\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 22570418,
"author": "ImaJedi4ever",
"author_id": 3329778,
"author_profile": "https://Stackoverflow.com/users/3329778",
"pm_score": 0,
"selected": false,
"text": "<p>The non-breaking hyphen works well.</p>\n\n<p><strong>HTML Entity (decimal)</strong> </p>\n\n<pre><code>&#8209;\n</code></pre>\n"
},
{
"answer_id": 30229247,
"author": "TObject",
"author_id": 4736743,
"author_profile": "https://Stackoverflow.com/users/4736743",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of <code>-</code> you can use <code>&hyphen;</code> or <code>\\u2010</code>.</p>\n\n<p>Also, make sure the <strong>hyphens</strong> css property was <strong>not</strong> set to <em>none</em> (The default value is <em>manual</em>).</p>\n\n<p><code><wbr></code> is not supported by <em>Internet Explorer</em>.</p>\n"
},
{
"answer_id": 32249676,
"author": "Ajay Gupta",
"author_id": 2663073,
"author_profile": "https://Stackoverflow.com/users/2663073",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use :</p>\n\n<pre><code>word-break:break-all;\n</code></pre>\n\n<p>ex.</p>\n\n<pre><code><div style='width:10px'>ababababababbabaabababababababbabababa</div>\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>abababababa\nababababbba\nabbabbababa\nababb\n</code></pre>\n\n<p>word-break is break all the word or line even if no-space in sentence that not feets in provided width or height. nut for that you must be provide a width or height.</p>\n"
},
{
"answer_id": 45979734,
"author": "Mohammed Wahed Khan",
"author_id": 8040185,
"author_profile": "https://Stackoverflow.com/users/8040185",
"pm_score": 0,
"selected": false,
"text": "<p>Hope this may help</p>\n\n<p>use <code><br></code>(break) tag where you want to break the line.</p>\n"
},
{
"answer_id": 52311670,
"author": "jcubic",
"author_id": 387194,
"author_profile": "https://Stackoverflow.com/users/387194",
"pm_score": 0,
"selected": false,
"text": "<p>You can use 0 width space after hyphen character:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div {\r\n width: 150px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div>\r\n 12333-&#8203;2333-&#8203;233-&#8203;23339392-&#8203;332332323\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>if You want line break before hyphen use <code>&#8203;-</code> instead.</p>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34/"
] | Given a relatively simple CSS:
```css
div {
width: 150px;
}
```
```html
<div>
12333-2333-233-23339392-332332323
</div>
```
>
> How do I make it so that the string stays constrained to the `width`
> of **150**, and wraps to a new line on the *hyphen*?
>
>
> | Replace your hyphens with this:
```
­
```
It's called a "soft" hyphen.
```css
div {
width: 150px;
}
```
```html
<div>
12333­2333­233­23339392­332332323
</div>
``` |
930 | <p>What's the simplest way to connect and query a database for a set of records in C#?</p>
| [
{
"answer_id": 940,
"author": "Goyuix",
"author_id": 243,
"author_profile": "https://Stackoverflow.com/users/243",
"pm_score": 4,
"selected": false,
"text": "<p>Very roughly and from memory since I don't have code on this laptop:</p>\n\n<pre><code>using (OleDBConnection conn = new OleDbConnection())\n{\n conn.ConnectionString = \"Whatever connection string\";\n\n using (OleDbCommand cmd = new OleDbCommand())\n {\n cmd.Connection = conn;\n cmd.CommandText = \"Select * from CoolTable\";\n\n using (OleDbDataReader dr = cmd.ExecuteReader())\n {\n while (dr.Read())\n {\n // do something like Console.WriteLine(dr[\"column name\"] as String);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 951,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 6,
"selected": true,
"text": "<p>@Goyuix -- that's excellent for something written from memory.\ntested it here -- found the connection wasn't opened. Otherwise very nice.</p>\n\n<pre><code>using System.Data.OleDb;\n...\n\nusing (OleDbConnection conn = new OleDbConnection())\n{\n conn.ConnectionString = \"Provider=sqloledb;Data Source=yourServername\\\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;\";\n\n using (OleDbCommand cmd = new OleDbCommand())\n {\n conn.Open();\n cmd.Connection = conn;\n cmd.CommandText = \"Select * from yourTable\";\n\n using (OleDbDataReader dr = cmd.ExecuteReader())\n {\n while (dr.Read())\n {\n Console.WriteLine(dr[\"columnName\"]);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1022,
"author": "MojoFilter",
"author_id": 93,
"author_profile": "https://Stackoverflow.com/users/93",
"pm_score": 4,
"selected": false,
"text": "<p>That's definitely a good way to do it. But you if you happen to be using a database that supports LINQ to SQL, it can be a lot more fun. It can look something like this:</p>\n\n<pre><code>MyDB db = new MyDB(\"Data Source=...\");\nvar q = from db.MyTable\n select c;\nforeach (var c in q)\n Console.WriteLine(c.MyField.ToString());\n</code></pre>\n"
},
{
"answer_id": 2369,
"author": "Marek Grzenkowicz",
"author_id": 95,
"author_profile": "https://Stackoverflow.com/users/95",
"pm_score": 3,
"selected": false,
"text": "<p>This is an alternative way (DataReader is faster than this one):</p>\n\n<pre><code>string s = \"\";\nSqlConnection conn = new SqlConnection(\"Server=192.168.1.1;Database=master;Connect Timeout=30;User ID=foobar;Password=raboof;\");\nSqlDataAdapter da = new SqlDataAdapter(\"SELECT TOP 5 name, dbid FROM sysdatabases\", conn);\nDataTable dt = new DataTable();\n\nda.Fill(dt);\n\nfor (int i = 0; i < dt.Rows.Count; i++)\n{\n s += dt.Rows[i][\"name\"].ToString() + \" -- \" + dt.Rows[i][\"dbid\"].ToString() + \"\\n\";\n}\n\nMessageBox.Show(s);\n</code></pre>\n"
},
{
"answer_id": 20049,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 2,
"selected": false,
"text": "<p>If you are querying a SQL Server database (Version 7 and up) you should replace the OleDb classes with corresponding classes in the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient\" rel=\"nofollow noreferrer\">System.Data.SqlClient</a> namespace (<a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection\" rel=\"nofollow noreferrer\">SqlConnection</a>, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand\" rel=\"nofollow noreferrer\">SqlCommand</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader\" rel=\"nofollow noreferrer\">SqlDataReader</a>) as those classes have been optimized to work with SQL Server.</p>\n\n<p>Another thing to note is that you should 'never' select all as this might lead to unexpected results later on if you add or remove columns to this table.</p>\n"
},
{
"answer_id": 65774,
"author": "DamienG",
"author_id": 5720,
"author_profile": "https://Stackoverflow.com/users/5720",
"pm_score": 2,
"selected": false,
"text": "<p>If you are intending on reading a large number of columns or records it's also worth caching the ordinals and accessing the strongly-typed methods, e.g.</p>\n\n<pre><code>using (DbDataReader dr = cmd.ExecuteReader()) {\n if (dr.Read()) {\n int idxColumnName = dr.GetOrdinal(\"columnName\");\n int idxSomethingElse = dr.GetOrdinal(\"somethingElse\");\n\n do {\n Console.WriteLine(dr.GetString(idxColumnName));\n Console.WriteLine(dr.GetInt32(idxSomethingElse));\n } while (dr.Read());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 12288220,
"author": "kril",
"author_id": 1650003,
"author_profile": "https://Stackoverflow.com/users/1650003",
"pm_score": 1,
"selected": false,
"text": "<p>I guess, you can try entity framework.</p>\n\n<pre><code>using (SchoolDBEntities ctx = new SchoolDBEntities())\n{\n IList<Course> courseList = ctx.GetCoursesByStudentId(1).ToList<Course>();\n //do something with courselist here\n}\n</code></pre>\n"
},
{
"answer_id": 56179247,
"author": "Josué Martínez",
"author_id": 11507342,
"author_profile": "https://Stackoverflow.com/users/11507342",
"pm_score": 0,
"selected": false,
"text": "<p>Charge the libraries</p>\n\n<pre><code>using MySql.Data.MySqlClient;\n</code></pre>\n\n<p>This is the connection:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static MySqlConnection obtenerconexion()\n{\n string server = \"Server\";\n string database = \"Name_Database\";\n string Uid = \"User\";\n string pwd = \"Password\";\n MySqlConnection conect = new MySqlConnection(\"server = \" + server + \";\" + \"database =\" + database + \";\" + \"Uid =\" + Uid + \";\" + \"pwd=\" + pwd + \";\");\n\n try\n {\n conect.Open();\n return conect;\n }\n catch (Exception)\n {\n MessageBox.Show(\"Error. Ask the administrator\", \"An error has occurred while trying to connect to the system\", MessageBoxButtons.OK, MessageBoxIcon.Error);\n return conect;\n }\n}\n</code></pre>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245/"
] | What's the simplest way to connect and query a database for a set of records in C#? | @Goyuix -- that's excellent for something written from memory.
tested it here -- found the connection wasn't opened. Otherwise very nice.
```
using System.Data.OleDb;
...
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;";
using (OleDbCommand cmd = new OleDbCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "Select * from yourTable";
using (OleDbDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
Console.WriteLine(dr["columnName"]);
}
}
}
}
``` |
935 | <p>Attempting to insert an escape character into a table results in a warning. </p>
<p>For example:</p>
<pre><code>create table EscapeTest (text varchar(50));
insert into EscapeTest (text) values ('This is the first part \n And this is the second');
</code></pre>
<p>Produces the warning:</p>
<pre><code>WARNING: nonstandard use of escape in a string literal
</code></pre>
<p>(<em>Using PSQL 8.2</em>)</p>
<p>Anyone know how to get around this?</p>
| [
{
"answer_id": 938,
"author": "rjohnston",
"author_id": 246,
"author_profile": "https://Stackoverflow.com/users/246",
"pm_score": 8,
"selected": true,
"text": "<p>Partially. The text is inserted, but the warning is still generated.</p>\n\n<p>I found a discussion that indicated the text needed to be preceded with 'E', as such:</p>\n\n<pre><code>insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');\n</code></pre>\n\n<p>This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.</p>\n\n<p>As such:</p>\n\n<pre><code>insert into EscapeTest (text) values (E'This is the first part \\\\n And this is the second');\n</code></pre>\n"
},
{
"answer_id": 943,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 6,
"selected": false,
"text": "<p>Cool.</p>\n\n<p>I also found the documentation regarding the E:</p>\n\n<p><a href=\"http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS\" rel=\"noreferrer\">http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS</a></p>\n\n<blockquote>\n <p>PostgreSQL also accepts \"escape\" string constants, which are an extension to the SQL standard. An escape string constant is specified by writing the letter E (upper or lower case) just before the opening single quote, e.g. E'foo'. (When continuing an escape string constant across lines, write E only before the first opening quote.) Within an escape string, a backslash character (\\) begins a C-like backslash escape sequence, in which the combination of backslash and following character(s) represents a special byte value. \\b is a backspace, \\f is a form feed, \\n is a newline, \\r is a carriage return, \\t is a tab. Also supported are \\digits, where digits represents an octal byte value, and \\xhexdigits, where hexdigits represents a hexadecimal byte value. (It is your responsibility that the byte sequences you create are valid characters in the server character set encoding.) Any other character following a backslash is taken literally. Thus, to include a backslash character, write two backslashes (\\\\). Also, a single quote can be included in an escape string by writing \\', in addition to the normal way of ''.</p>\n</blockquote>\n"
},
{
"answer_id": 72132,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Really stupid question: Are you sure the string is being truncated, and not just broken at the linebreak you specify (and possibly not showing in your interface)? Ie, do you expect the field to show as</p>\n<blockquote>\n<p>This will be inserted \\n This will not\nbe</p>\n</blockquote>\n<p>or</p>\n<blockquote>\n<p>This will be inserted</p>\n<p>This will not be</p>\n</blockquote>\n<p>Also, what interface are you using? Is it possible that something along the way is eating your backslashes?</p>\n"
},
{
"answer_id": 104780,
"author": "Milen A. Radev",
"author_id": 15785,
"author_profile": "https://Stackoverflow.com/users/15785",
"pm_score": 2,
"selected": false,
"text": "<p>I find it highly unlikely for Postgres to truncate your data on input - it either rejects it or stores it as is.</p>\n\n<pre><code>milen@dev:~$ psql\nWelcome to psql 8.2.7, the PostgreSQL interactive terminal.\n\nType: \\copyright for distribution terms\n \\h for help with SQL commands\n \\? for help with psql commands\n \\g or terminate with semicolon to execute query\n \\q to quit\n\nmilen=> create table EscapeTest (text varchar(50));\nCREATE TABLE\nmilen=> insert into EscapeTest (text) values ('This will be inserted \\n This will not be');\nWARNING: nonstandard use of escape in a string literal\nLINE 1: insert into EscapeTest (text) values ('This will be inserted...\n ^\nHINT: Use the escape string syntax for escapes, e.g., E'\\r\\n'.\nINSERT 0 1\nmilen=> select * from EscapeTest;\n text\n------------------------\n This will be inserted\n This will not be\n(1 row)\n\nmilen=>\n</code></pre>\n"
},
{
"answer_id": 2277307,
"author": "eppesuig",
"author_id": 387880,
"author_profile": "https://Stackoverflow.com/users/387880",
"pm_score": 3,
"selected": false,
"text": "<p>The warning is issued since you are using backslashes in your strings. If you want to avoid the message, type this command \"set standard_conforming_strings=on;\". Then use \"E\" before your string including backslashes that you want postgresql to intrepret.</p>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246/"
] | Attempting to insert an escape character into a table results in a warning.
For example:
```
create table EscapeTest (text varchar(50));
insert into EscapeTest (text) values ('This is the first part \n And this is the second');
```
Produces the warning:
```
WARNING: nonstandard use of escape in a string literal
```
(*Using PSQL 8.2*)
Anyone know how to get around this? | Partially. The text is inserted, but the warning is still generated.
I found a discussion that indicated the text needed to be preceded with 'E', as such:
```
insert into EscapeTest (text) values (E'This is the first part \n And this is the second');
```
This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.
As such:
```
insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');
``` |
947 | <p>I have imported the <code>kernel32</code> library. So, I have the <code>createMutex</code> function available but I am not quite sure of the various parameters and return values.</p>
<p>This is classic Visual Basic, not Visual Basic.NET but I can probably work with either language in the form of an answer.</p>
| [
{
"answer_id": 1025,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>Well, based on the <a href=\"http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx\" rel=\"nofollow noreferrer\">documentation</a> it looks like:</p>\n\n<ol>\n<li>Security attributes (can pass null)</li>\n<li>Whether it's initially owned (can pass false)</li>\n<li>The name of it</li>\n</ol>\n\n<p>HTH</p>\n"
},
{
"answer_id": 1028,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>The VB code looks something like this:</p>\n\n<pre><code>hMutex = CreateMutex(ByVal 0&, 1, ByVal 0&)\n</code></pre>\n\n<p>The first parameter is a pointer to an <code>SECURITY_ATTRIBUTES</code> structure. If you don't know what it is, you don't need it. Pass NULL (0).</p>\n\n<p>The second parameter is <code>TRUE</code> (non-zero, or 1) if the calling thread should take ownership of the mutex. <code>FALSE</code> otherwise.</p>\n\n<p>The third parameter is the mutex name and may be NULL (0), as shown. If you need a named mutex, pass the name (anything unique) in. Not sure whether the <code>VB</code> wrapper marshals the length-prefixed <code>VB</code> string type (<code>BSTR</code>) over to a null-terminated Ascii/Unicode string if not, you'll need to do that and numerous examples are out there.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 82335,
"author": "MarkJ",
"author_id": 15639,
"author_profile": "https://Stackoverflow.com/users/15639",
"pm_score": 3,
"selected": false,
"text": "<p>Here's the VB6 declarations for <a href=\"http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx\" rel=\"noreferrer\">CreateMutex</a> - I just copied them from the API viewer, which you should have as part of your VB6 installation. VB6 marshalls strings to null-terminated ANSI using the current code page.</p>\n\n<pre><code>Public Type SECURITY_ATTRIBUTES\n nLength As Long\n lpSecurityDescriptor As Long\n bInheritHandle As Long \nEnd Type\n\nPublic Declare Function CreateMutex Lib \"kernel32\" Alias \"CreateMutexA\" _\n (lpMutexAttributes As SECURITY_ATTRIBUTES, ByVal bInitialOwner As Long, _\n ByVal lpName As String) As Long\n</code></pre>\n\n<p>Bear in mind that if you create a mutex from the VB6 IDE, the mutex belongs to the IDE and won't be destroyed when you stop running your program - only when you close the IDE.</p>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/243/"
] | I have imported the `kernel32` library. So, I have the `createMutex` function available but I am not quite sure of the various parameters and return values.
This is classic Visual Basic, not Visual Basic.NET but I can probably work with either language in the form of an answer. | The VB code looks something like this:
```
hMutex = CreateMutex(ByVal 0&, 1, ByVal 0&)
```
The first parameter is a pointer to an `SECURITY_ATTRIBUTES` structure. If you don't know what it is, you don't need it. Pass NULL (0).
The second parameter is `TRUE` (non-zero, or 1) if the calling thread should take ownership of the mutex. `FALSE` otherwise.
The third parameter is the mutex name and may be NULL (0), as shown. If you need a named mutex, pass the name (anything unique) in. Not sure whether the `VB` wrapper marshals the length-prefixed `VB` string type (`BSTR`) over to a null-terminated Ascii/Unicode string if not, you'll need to do that and numerous examples are out there.
Good luck! |
972 | <p>I've read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python. </p>
<p>I understand that it's not always good to do so. But how might one do this?</p>
| [
{
"answer_id": 982,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 5,
"selected": false,
"text": "<p>In Python monkeypatching generally works by overwriting a class or function's signature with your own. Below is an example from the <a href=\"http://web.archive.org/web/20130610034152/http://wiki.zope.org:80/zope2/MonkeyPatch\" rel=\"noreferrer\">Zope Wiki</a>:</p>\n<pre><code>from SomeOtherProduct.SomeModule import SomeClass\ndef speak(self):\n return "ook ook eee eee eee!"\nSomeClass.speak = speak\n</code></pre>\n<p>This code will overwrite/create a method called <code>speak</code> in the class. In Jeff Atwood's <a href=\"https://blog.codinghorror.com/monkeypatching-for-humans/\" rel=\"noreferrer\">recent post on monkey patching</a>, he showed an example in C# 3.0 which is the current language I use for work.</p>\n"
},
{
"answer_id": 2982,
"author": "Jason Pratt",
"author_id": 99,
"author_profile": "https://Stackoverflow.com/users/99",
"pm_score": 11,
"selected": true,
"text": "<p>In Python, there is a difference between functions and bound methods.</p>\n<pre><code>>>> def foo():\n... print "foo"\n...\n>>> class A:\n... def bar( self ):\n... print "bar"\n...\n>>> a = A()\n>>> foo\n<function foo at 0x00A98D70>\n>>> a.bar\n<bound method A.bar of <__main__.A instance at 0x00A9BC88>>\n>>>\n</code></pre>\n<p>Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called.</p>\n<p>Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want:</p>\n<pre><code>>>> def fooFighters( self ):\n... print "fooFighters"\n...\n>>> A.fooFighters = fooFighters\n>>> a2 = A()\n>>> a2.fooFighters\n<bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>>\n>>> a2.fooFighters()\nfooFighters\n</code></pre>\n<p>Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves):</p>\n<pre><code>>>> a.fooFighters()\nfooFighters\n</code></pre>\n<p>The problem comes when you want to attach a method to a single instance:</p>\n<pre><code>>>> def barFighters( self ):\n... print "barFighters"\n...\n>>> a.barFighters = barFighters\n>>> a.barFighters()\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nTypeError: barFighters() takes exactly 1 argument (0 given)\n</code></pre>\n<p>The function is not automatically bound when it's attached directly to an instance:</p>\n<pre><code>>>> a.barFighters\n<function barFighters at 0x00A98EF0>\n</code></pre>\n<p>To bind it, we can use the <a href=\"https://docs.python.org/3/library/types.html#types.MethodType\" rel=\"noreferrer\">MethodType function in the types module</a>:</p>\n<pre><code>>>> import types\n>>> a.barFighters = types.MethodType( barFighters, a )\n>>> a.barFighters\n<bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>>\n>>> a.barFighters()\nbarFighters\n</code></pre>\n<p>This time other instances of the class have not been affected:</p>\n<pre><code>>>> a2.barFighters()\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nAttributeError: A instance has no attribute 'barFighters'\n</code></pre>\n<p>More information can be found by reading about <a href=\"https://docs.python.org/3/howto/descriptor.html\" rel=\"noreferrer\">descriptors</a> and <a href=\"https://web.archive.org/web/20090124004817/http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html\" rel=\"noreferrer\">metaclass</a> <a href=\"http://www.gnosis.cx/publish/programming/metaclass_2.html\" rel=\"noreferrer\">programming</a>.</p>\n"
},
{
"answer_id": 4600,
"author": "HS.",
"author_id": 618,
"author_profile": "https://Stackoverflow.com/users/618",
"pm_score": 4,
"selected": false,
"text": "<p>What you're looking for is <code>setattr</code> I believe.\nUse this to set an attribute on an object.</p>\n\n<pre><code>>>> def printme(s): print repr(s)\n>>> class A: pass\n>>> setattr(A,'printme',printme)\n>>> a = A()\n>>> a.printme() # s becomes the implicit 'self' variable\n< __ main __ . A instance at 0xABCDEFG>\n</code></pre>\n"
},
{
"answer_id": 22525,
"author": "Acuminate",
"author_id": 2482,
"author_profile": "https://Stackoverflow.com/users/2482",
"pm_score": 2,
"selected": false,
"text": "<p>What Jason Pratt posted is correct.</p>\n\n<pre><code>>>> class Test(object):\n... def a(self):\n... pass\n... \n>>> def b(self):\n... pass\n... \n>>> Test.b = b\n>>> type(b)\n<type 'function'>\n>>> type(Test.a)\n<type 'instancemethod'>\n>>> type(Test.b)\n<type 'instancemethod'>\n</code></pre>\n\n<p>As you can see, Python doesn't consider b() any different than a(). In Python all methods are just variables that happen to be functions. </p>\n"
},
{
"answer_id": 959064,
"author": "Evgeny",
"author_id": 110274,
"author_profile": "https://Stackoverflow.com/users/110274",
"pm_score": 7,
"selected": false,
"text": "<p>Module <strong>new</strong> is deprecated since python 2.6 and removed in 3.0, use <strong>types</strong></p>\n\n<p>see <a href=\"http://docs.python.org/library/new.html\" rel=\"noreferrer\">http://docs.python.org/library/new.html</a></p>\n\n<p>In the example below I've deliberately removed return value from <code>patch_me()</code> function.\nI think that giving return value may make one believe that patch returns a new object, which is not true - it modifies the incoming one. Probably this can facilitate a more disciplined use of monkeypatching.</p>\n\n<pre><code>import types\n\nclass A(object):#but seems to work for old style objects too\n pass\n\ndef patch_me(target):\n def method(target,x):\n print \"x=\",x\n print \"called from\", target\n target.method = types.MethodType(method,target)\n #add more if needed\n\na = A()\nprint a\n#out: <__main__.A object at 0x2b73ac88bfd0> \npatch_me(a) #patch instance\na.method(5)\n#out: x= 5\n#out: called from <__main__.A object at 0x2b73ac88bfd0>\npatch_me(A)\nA.method(6) #can patch class too\n#out: x= 6\n#out: called from <class '__main__.A'>\n</code></pre>\n"
},
{
"answer_id": 8961717,
"author": "Tomasz Zieliński",
"author_id": 176186,
"author_profile": "https://Stackoverflow.com/users/176186",
"pm_score": 5,
"selected": false,
"text": "<p>I think that the above answers missed the key point. </p>\n\n<p>Let's have a class with a method:</p>\n\n<pre><code>class A(object):\n def m(self):\n pass\n</code></pre>\n\n<p>Now, let's play with it in ipython:</p>\n\n<pre><code>In [2]: A.m\nOut[2]: <unbound method A.m>\n</code></pre>\n\n<p>Ok, so <em>m()</em> somehow becomes an unbound method of <em>A</em>. But is it really like that?</p>\n\n<pre><code>In [5]: A.__dict__['m']\nOut[5]: <function m at 0xa66b8b4>\n</code></pre>\n\n<p>It turns out that <em>m()</em> is just a function, reference to which is added to <em>A</em> class dictionary - there's no magic. Then why <em>A.m</em> gives us an unbound method? It's because the dot is not translated to a simple dictionary lookup. It's de facto a call of A.__class__.__getattribute__(A, 'm'):</p>\n\n<pre><code>In [11]: class MetaA(type):\n ....: def __getattribute__(self, attr_name):\n ....: print str(self), '-', attr_name\n\nIn [12]: class A(object):\n ....: __metaclass__ = MetaA\n\nIn [23]: A.m\n<class '__main__.A'> - m\n<class '__main__.A'> - m\n</code></pre>\n\n<p>Now, I'm not sure out of the top of my head why the last line is printed twice, but still it's clear what's going on there.</p>\n\n<p>Now, what the default __getattribute__ does is that it checks if the attribute is a so-called <a href=\"http://docs.python.org/reference/datamodel.html#implementing-descriptors\" rel=\"noreferrer\">descriptor</a> or not, i.e. if it implements a special __get__ method. If it implements that method, then what is returned is the result of calling that __get__ method. Going back to the first version of our <em>A</em> class, this is what we have:</p>\n\n<pre><code>In [28]: A.__dict__['m'].__get__(None, A)\nOut[28]: <unbound method A.m>\n</code></pre>\n\n<p>And because Python functions implement the descriptor protocol, if they are called on behalf of an object, they bind themselves to that object in their __get__ method.</p>\n\n<p>Ok, so how to add a method to an existing object? Assuming you don't mind patching class, it's as simple as:</p>\n\n<pre><code>B.m = m\n</code></pre>\n\n<p>Then <em>B.m</em> \"becomes\" an unbound method, thanks to the descriptor magic.</p>\n\n<p>And if you want to add a method just to a single object, then you have to emulate the machinery yourself, by using types.MethodType:</p>\n\n<pre><code>b.m = types.MethodType(m, b)\n</code></pre>\n\n<p>By the way:</p>\n\n<pre><code>In [2]: A.m\nOut[2]: <unbound method A.m>\n\nIn [59]: type(A.m)\nOut[59]: <type 'instancemethod'>\n\nIn [60]: type(b.m)\nOut[60]: <type 'instancemethod'>\n\nIn [61]: types.MethodType\nOut[61]: <type 'instancemethod'>\n</code></pre>\n"
},
{
"answer_id": 9041763,
"author": "Nisan.H",
"author_id": 841337,
"author_profile": "https://Stackoverflow.com/users/841337",
"pm_score": 3,
"selected": false,
"text": "<p>Consolidating Jason Pratt's and the community wiki answers, with a look at the results of different methods of binding:</p>\n\n<p>Especially note how adding the binding function as a class method <em>works</em>, but the referencing scope is incorrect.</p>\n\n<pre><code>#!/usr/bin/python -u\nimport types\nimport inspect\n\n## dynamically adding methods to a unique instance of a class\n\n\n# get a list of a class's method type attributes\ndef listattr(c):\n for m in [(n, v) for n, v in inspect.getmembers(c, inspect.ismethod) if isinstance(v,types.MethodType)]:\n print m[0], m[1]\n\n# externally bind a function as a method of an instance of a class\ndef ADDMETHOD(c, method, name):\n c.__dict__[name] = types.MethodType(method, c)\n\nclass C():\n r = 10 # class attribute variable to test bound scope\n\n def __init__(self):\n pass\n\n #internally bind a function as a method of self's class -- note that this one has issues!\n def addmethod(self, method, name):\n self.__dict__[name] = types.MethodType( method, self.__class__ )\n\n # predfined function to compare with\n def f0(self, x):\n print 'f0\\tx = %d\\tr = %d' % ( x, self.r)\n\na = C() # created before modified instnace\nb = C() # modified instnace\n\n\ndef f1(self, x): # bind internally\n print 'f1\\tx = %d\\tr = %d' % ( x, self.r )\ndef f2( self, x): # add to class instance's .__dict__ as method type\n print 'f2\\tx = %d\\tr = %d' % ( x, self.r )\ndef f3( self, x): # assign to class as method type\n print 'f3\\tx = %d\\tr = %d' % ( x, self.r )\ndef f4( self, x): # add to class instance's .__dict__ using a general function\n print 'f4\\tx = %d\\tr = %d' % ( x, self.r )\n\n\nb.addmethod(f1, 'f1')\nb.__dict__['f2'] = types.MethodType( f2, b)\nb.f3 = types.MethodType( f3, b)\nADDMETHOD(b, f4, 'f4')\n\n\nb.f0(0) # OUT: f0 x = 0 r = 10\nb.f1(1) # OUT: f1 x = 1 r = 10\nb.f2(2) # OUT: f2 x = 2 r = 10\nb.f3(3) # OUT: f3 x = 3 r = 10\nb.f4(4) # OUT: f4 x = 4 r = 10\n\n\nk = 2\nprint 'changing b.r from {0} to {1}'.format(b.r, k)\nb.r = k\nprint 'new b.r = {0}'.format(b.r)\n\nb.f0(0) # OUT: f0 x = 0 r = 2\nb.f1(1) # OUT: f1 x = 1 r = 10 !!!!!!!!!\nb.f2(2) # OUT: f2 x = 2 r = 2\nb.f3(3) # OUT: f3 x = 3 r = 2\nb.f4(4) # OUT: f4 x = 4 r = 2\n\nc = C() # created after modifying instance\n\n# let's have a look at each instance's method type attributes\nprint '\\nattributes of a:'\nlistattr(a)\n# OUT:\n# attributes of a:\n# __init__ <bound method C.__init__ of <__main__.C instance at 0x000000000230FD88>>\n# addmethod <bound method C.addmethod of <__main__.C instance at 0x000000000230FD88>>\n# f0 <bound method C.f0 of <__main__.C instance at 0x000000000230FD88>>\n\nprint '\\nattributes of b:'\nlistattr(b)\n# OUT:\n# attributes of b:\n# __init__ <bound method C.__init__ of <__main__.C instance at 0x000000000230FE08>>\n# addmethod <bound method C.addmethod of <__main__.C instance at 0x000000000230FE08>>\n# f0 <bound method C.f0 of <__main__.C instance at 0x000000000230FE08>>\n# f1 <bound method ?.f1 of <class __main__.C at 0x000000000237AB28>>\n# f2 <bound method ?.f2 of <__main__.C instance at 0x000000000230FE08>>\n# f3 <bound method ?.f3 of <__main__.C instance at 0x000000000230FE08>>\n# f4 <bound method ?.f4 of <__main__.C instance at 0x000000000230FE08>>\n\nprint '\\nattributes of c:'\nlistattr(c)\n# OUT:\n# attributes of c:\n# __init__ <bound method C.__init__ of <__main__.C instance at 0x0000000002313108>>\n# addmethod <bound method C.addmethod of <__main__.C instance at 0x0000000002313108>>\n# f0 <bound method C.f0 of <__main__.C instance at 0x0000000002313108>>\n</code></pre>\n\n<p>Personally, I prefer the external ADDMETHOD function route, as it allows me to dynamically assign new method names within an iterator as well.</p>\n\n<pre><code>def y(self, x):\n pass\nd = C()\nfor i in range(1,5):\n ADDMETHOD(d, y, 'f%d' % i)\nprint '\\nattributes of d:'\nlistattr(d)\n# OUT:\n# attributes of d:\n# __init__ <bound method C.__init__ of <__main__.C instance at 0x0000000002303508>>\n# addmethod <bound method C.addmethod of <__main__.C instance at 0x0000000002303508>>\n# f0 <bound method C.f0 of <__main__.C instance at 0x0000000002303508>>\n# f1 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>\n# f2 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>\n# f3 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>\n# f4 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>\n</code></pre>\n"
},
{
"answer_id": 9636303,
"author": "Tamzin Blake",
"author_id": 650551,
"author_profile": "https://Stackoverflow.com/users/650551",
"pm_score": 3,
"selected": false,
"text": "<p>Since this question asked for non-Python versions, here's JavaScript:</p>\n\n<pre><code>a.methodname = function () { console.log(\"Yay, a new method!\") }\n</code></pre>\n"
},
{
"answer_id": 16240409,
"author": "ndpu",
"author_id": 1099876,
"author_profile": "https://Stackoverflow.com/users/1099876",
"pm_score": 4,
"selected": false,
"text": "<p>There are at least two ways for attach a method to an instance without <code>types.MethodType</code>:</p>\n\n<pre><code>>>> class A:\n... def m(self):\n... print 'im m, invoked with: ', self\n\n>>> a = A()\n>>> a.m()\nim m, invoked with: <__main__.A instance at 0x973ec6c>\n>>> a.m\n<bound method A.m of <__main__.A instance at 0x973ec6c>>\n>>> \n>>> def foo(firstargument):\n... print 'im foo, invoked with: ', firstargument\n\n>>> foo\n<function foo at 0x978548c>\n</code></pre>\n\n<p>1:</p>\n\n<pre><code>>>> a.foo = foo.__get__(a, A) # or foo.__get__(a, type(a))\n>>> a.foo()\nim foo, invoked with: <__main__.A instance at 0x973ec6c>\n>>> a.foo\n<bound method A.foo of <__main__.A instance at 0x973ec6c>>\n</code></pre>\n\n<p>2:</p>\n\n<pre><code>>>> instancemethod = type(A.m)\n>>> instancemethod\n<type 'instancemethod'>\n>>> a.foo2 = instancemethod(foo, a, type(a))\n>>> a.foo2()\nim foo, invoked with: <__main__.A instance at 0x973ec6c>\n>>> a.foo2\n<bound method instance.foo of <__main__.A instance at 0x973ec6c>>\n</code></pre>\n\n<p>Useful links:<br>\n<a href=\"http://docs.python.org/2/reference/datamodel.html#invoking-descriptors\" rel=\"noreferrer\">Data model - invoking descriptors</a><br>\n<a href=\"http://docs.python.org/2.7/howto/descriptor.html#invoking-descriptors\" rel=\"noreferrer\">Descriptor HowTo Guide - invoking descriptors</a></p>\n"
},
{
"answer_id": 24748849,
"author": "ChristopherC",
"author_id": 1640404,
"author_profile": "https://Stackoverflow.com/users/1640404",
"pm_score": 2,
"selected": false,
"text": "<p>If it can be of any help, I recently released a Python library named Gorilla to make the process of monkey patching more convenient.</p>\n\n<p>Using a function <code>needle()</code> to patch a module named <code>guineapig</code> goes as follows:</p>\n\n<pre><code>import gorilla\nimport guineapig\n@gorilla.patch(guineapig)\ndef needle():\n print(\"awesome\")\n</code></pre>\n\n<p>But it also takes care of more interesting use cases as shown in the <a href=\"http://gorilla.readthedocs.org/en/latest/faq.html\" rel=\"nofollow\">FAQ</a> from the <a href=\"http://gorilla.readthedocs.org/\" rel=\"nofollow\">documentation</a>.</p>\n\n<p>The code is available on <a href=\"https://github.com/christophercrouzet/gorilla\" rel=\"nofollow\">GitHub</a>.</p>\n"
},
{
"answer_id": 24865663,
"author": "Evgeny Prokurat",
"author_id": 3748584,
"author_profile": "https://Stackoverflow.com/users/3748584",
"pm_score": 4,
"selected": false,
"text": "<p>You can use lambda to bind a method to an instance:</p>\n\n<pre><code>def run(self):\n print self._instanceString\n\nclass A(object):\n def __init__(self):\n self._instanceString = \"This is instance string\"\n\na = A()\na.run = lambda: run(a)\na.run()\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>This is instance string\n</code></pre>\n"
},
{
"answer_id": 28060251,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 7,
"selected": false,
"text": "<p>Preface - a note on compatibility: other answers may only work in Python 2 - this answer should work perfectly well in Python 2 and 3. If writing Python 3 only, you might leave out explicitly inheriting from <code>object</code>, but otherwise the code should remain the same.</p>\n<blockquote>\n<h1>Adding a Method to an Existing Object Instance</h1>\n<p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in Python.</p>\n<p>I understand that it's not always a good decision to do so. <strong>But, how might one do this?</strong></p>\n</blockquote>\n<h2>Yes, it is possible - But not recommended</h2>\n<p>I don't recommend this. This is a bad idea. Don't do it.</p>\n<p>Here's a couple of reasons:</p>\n<ul>\n<li>You'll add a bound object to every instance you do this to. If you do this a lot, you'll probably waste a lot of memory. Bound methods are typically only created for the short duration of their call, and they then cease to exist when automatically garbage collected. If you do this manually, you'll have a name binding referencing the bound method - which will prevent its garbage collection on usage.</li>\n<li>Object instances of a given type generally have its methods on all objects of that type. If you add methods elsewhere, some instances will have those methods and others will not. Programmers will not expect this, and you risk violating the <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"noreferrer\">rule of least surprise</a>.</li>\n<li>Since there are other really good reasons not to do this, you'll additionally give yourself a poor reputation if you do it.</li>\n</ul>\n<p>Thus, I suggest that you not do this unless you have a really good reason. <strong>It is far better to define the correct method in the class definition</strong> or <em>less</em> preferably to monkey-patch the class directly, like this:</p>\n<pre><code>Foo.sample_method = sample_method\n</code></pre>\n<p>Since it's instructive, however, I'm going to show you some ways of doing this.</p>\n<h2>How it can be done</h2>\n<p>Here's some setup code. We need a class definition. It could be imported, but it really doesn't matter.</p>\n<pre><code>class Foo(object):\n '''An empty class to demonstrate adding a method to an instance'''\n</code></pre>\n<p>Create an instance:</p>\n<pre><code>foo = Foo()\n</code></pre>\n<p>Create a method to add to it:</p>\n<pre><code>def sample_method(self, bar, baz):\n print(bar + baz)\n</code></pre>\n<h3>Method nought (0) - use the descriptor method, <code>__get__</code></h3>\n<p>Dotted lookups on functions call the <code>__get__</code> method of the function with the instance, binding the object to the method and thus creating a "bound method."</p>\n<pre><code>foo.sample_method = sample_method.__get__(foo)\n</code></pre>\n<p>and now:</p>\n<pre><code>>>> foo.sample_method(1,2)\n3\n</code></pre>\n<h3>Method one - types.MethodType</h3>\n<p>First, import types, from which we'll get the method constructor:</p>\n<pre><code>import types\n</code></pre>\n<p>Now we add the method to the instance. To do this, we require the MethodType constructor from the <code>types</code> module (which we imported above).</p>\n<p>The argument signature for types.MethodType (in Python 3) is <code>(function, instance)</code>:</p>\n<pre><code>foo.sample_method = types.MethodType(sample_method, foo)\n</code></pre>\n<p>and usage:</p>\n<pre><code>>>> foo.sample_method(1,2)\n3\n</code></pre>\n<p>Parenthetically, in Python 2 the signature was <code>(function, instance, class)</code>:</p>\n<pre><code>foo.sample_method = types.MethodType(sample_method, foo, Foo)\n</code></pre>\n<h3>Method two: lexical binding</h3>\n<p>First, we create a wrapper function that binds the method to the instance:</p>\n<pre><code>def bind(instance, method):\n def binding_scope_fn(*args, **kwargs): \n return method(instance, *args, **kwargs)\n return binding_scope_fn\n</code></pre>\n<p>usage:</p>\n<pre><code>>>> foo.sample_method = bind(foo, sample_method) \n>>> foo.sample_method(1,2)\n3\n</code></pre>\n<h3>Method three: functools.partial</h3>\n<p>A partial function applies the first argument(s) to a function (and optionally keyword arguments), and can later be called with the remaining arguments (and overriding keyword arguments). Thus:</p>\n<pre><code>>>> from functools import partial\n>>> foo.sample_method = partial(sample_method, foo)\n>>> foo.sample_method(1,2)\n3 \n</code></pre>\n<p>This makes sense when you consider that bound methods are partial functions of the instance.</p>\n<h2>Unbound function as an object attribute - why this doesn't work:</h2>\n<p>If we try to add the sample_method in the same way as we might add it to the class, it is unbound from the instance, and doesn't take the implicit self as the first argument.</p>\n<pre><code>>>> foo.sample_method = sample_method\n>>> foo.sample_method(1,2)\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nTypeError: sample_method() takes exactly 3 arguments (2 given)\n</code></pre>\n<p>We can make the unbound function work by explicitly passing the instance (or anything, since this method doesn't actually use the <code>self</code> argument variable), but it would not be consistent with the expected signature of other instances (if we're monkey-patching this instance):</p>\n<pre><code>>>> foo.sample_method(foo, 1, 2)\n3\n</code></pre>\n<h2>Conclusion</h2>\n<p>You now know several ways you <em>could</em> do this, but in all seriousness - don't do this.</p>\n"
},
{
"answer_id": 32076685,
"author": "Max",
"author_id": 5010481,
"author_profile": "https://Stackoverflow.com/users/5010481",
"pm_score": 3,
"selected": false,
"text": "<h1>This is actually an addon to the answer of "Jason Pratt"</h1>\n<p>Although Jasons answer works, it does only work if one wants to add a function to a class.\nIt did not work for me when I tried to reload an already existing method from the .py source code file.</p>\n<p>It took me for ages to find a workaround, but the trick seems simple...\n1.st import the code from the source code file\n2.nd force a reload\n3.rd use types.FunctionType(...) to convert the imported and bound method to a function\nyou can also pass on the current global variables, as the reloaded method would be in a different namespace\n4.th now you can continue as suggested by "Jason Pratt"\nusing the types.MethodType(...)</p>\n<p>Example:</p>\n<pre><code># this class resides inside ReloadCodeDemo.py\nclass A:\n def bar( self ):\n print "bar1"\n \n def reloadCode(self, methodName):\n ''' use this function to reload any function of class A'''\n import types\n import ReloadCodeDemo as ReloadMod # import the code as module\n reload (ReloadMod) # force a reload of the module\n myM = getattr(ReloadMod.A,methodName) #get reloaded Method\n myTempFunc = types.FunctionType(# convert the method to a simple function\n myM.im_func.func_code, #the methods code\n globals(), # globals to use\n argdefs=myM.im_func.func_defaults # default values for variables if any\n ) \n myNewM = types.MethodType(myTempFunc,self,self.__class__) #convert the function to a method\n setattr(self,methodName,myNewM) # add the method to the function\n\nif __name__ == '__main__':\n a = A()\n a.bar()\n # now change your code and save the file\n a.reloadCode('bar') # reloads the file\n a.bar() # now executes the reloaded code\n</code></pre>\n"
},
{
"answer_id": 34404761,
"author": "lain",
"author_id": 4548106,
"author_profile": "https://Stackoverflow.com/users/4548106",
"pm_score": 3,
"selected": false,
"text": "<p>This question was opened years ago, but hey, there's an easy way to simulate the binding of a function to a class instance using decorators:</p>\n\n<pre><code>def binder (function, instance):\n copy_of_function = type (function) (function.func_code, {})\n copy_of_function.__bind_to__ = instance\n def bound_function (*args, **kwargs):\n return copy_of_function (copy_of_function.__bind_to__, *args, **kwargs)\n return bound_function\n\n\nclass SupaClass (object):\n def __init__ (self):\n self.supaAttribute = 42\n\n\ndef new_method (self):\n print self.supaAttribute\n\n\nsupaInstance = SupaClass ()\nsupaInstance.supMethod = binder (new_method, supaInstance)\n\notherInstance = SupaClass ()\notherInstance.supaAttribute = 72\notherInstance.supMethod = binder (new_method, otherInstance)\n\notherInstance.supMethod ()\nsupaInstance.supMethod ()\n</code></pre>\n\n<p>There, when you pass the function and the instance to the binder decorator, it will create a new function, with the same code object as the first one. Then, the given instance of the class is stored in an attribute of the newly created function. The decorator return a (third) function calling automatically the copied function, giving the instance as the first parameter.\n <br/>\n <br/>\nIn conclusion you get a function simulating it's binding to the class instance. Letting the original function unchanged.</p>\n"
},
{
"answer_id": 43703054,
"author": "Yu Feng",
"author_id": 3781929,
"author_profile": "https://Stackoverflow.com/users/3781929",
"pm_score": 3,
"selected": false,
"text": "<p>I find it strange that nobody mentioned that all of the methods listed above creates a cycle reference between the added method and the instance, causing the object to be persistent till garbage collection. There was an old trick adding a descriptor by extending the class of the object:</p>\n\n<pre><code>def addmethod(obj, name, func):\n klass = obj.__class__\n subclass = type(klass.__name__, (klass,), {})\n setattr(subclass, name, func)\n obj.__class__ = subclass\n</code></pre>\n"
},
{
"answer_id": 45341362,
"author": "Arturo Morales Rangel",
"author_id": 4475534,
"author_profile": "https://Stackoverflow.com/users/4475534",
"pm_score": 2,
"selected": false,
"text": "<pre><code>from types import MethodType\n\ndef method(self):\n print 'hi!'\n\n\nsetattr( targetObj, method.__name__, MethodType(method, targetObj, type(method)) )\n</code></pre>\n\n<p>With this, you can use the self pointer</p>\n"
},
{
"answer_id": 64950870,
"author": "danbst",
"author_id": 1190453,
"author_profile": "https://Stackoverflow.com/users/1190453",
"pm_score": -1,
"selected": false,
"text": "<p>Apart from what others said, I found that <code>__repr__</code> and <code>__str__</code> methods can't be monkeypatched on object level, because <code>repr()</code> and <code>str()</code> use class-methods, not locally-bounded object methods:</p>\n<pre><code># Instance monkeypatch\n[ins] In [55]: x.__str__ = show.__get__(x) \n\n[ins] In [56]: x \nOut[56]: <__main__.X at 0x7fc207180c10>\n\n[ins] In [57]: str(x) \nOut[57]: '<__main__.X object at 0x7fc207180c10>'\n\n[ins] In [58]: x.__str__() \nNice object!\n\n# Class monkeypatch\n[ins] In [62]: X.__str__ = lambda _: "From class" \n\n[ins] In [63]: str(x) \nOut[63]: 'From class'\n</code></pre>\n"
},
{
"answer_id": 70662971,
"author": "Gerard G",
"author_id": 7452220,
"author_profile": "https://Stackoverflow.com/users/7452220",
"pm_score": 0,
"selected": false,
"text": "<h1>How to recover a class from an instance of a class</h1>\n<pre><code>class UnderWater:\n def __init__(self):\n self.net = 'underwater'\n\nmarine = UnderWater() # Instantiate the class\n\n# Recover the class from the instance and add attributes to it.\nclass SubMarine(marine.__class__): \n def __init__(self):\n super().__init__()\n self.sound = 'Sonar'\n \nprint(SubMarine, SubMarine.__name__, SubMarine().net, SubMarine().sound)\n\n# Output\n# (__main__.SubMarine,'SubMarine', 'underwater', 'Sonar')\n</code></pre>\n"
},
{
"answer_id": 73486831,
"author": "Hans",
"author_id": 15096247,
"author_profile": "https://Stackoverflow.com/users/15096247",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks to Arturo!\nYour answer got me on the right track!</p>\n<p>Based on Arturo's code, I wrote a little class:</p>\n<pre><code>from types import MethodType\nimport re\nfrom string import ascii_letters\n\n\nclass DynamicAttr:\n def __init__(self):\n self.dict_all_files = {}\n\n def _copy_files(self, *args, **kwargs):\n print(f'copy {args[0]["filename"]} {args[0]["copy_command"]}')\n\n def _delete_files(self, *args, **kwargs):\n print(f'delete {args[0]["filename"]} {args[0]["delete_command"]}')\n\n def _create_properties(self):\n for key, item in self.dict_all_files.items():\n setattr(\n self,\n key,\n self.dict_all_files[key],\n )\n setattr(\n self,\n key + "_delete",\n MethodType(\n self._delete_files,\n {\n "filename": key,\n "delete_command": f'del {item}',\n },\n ),\n )\n setattr(\n self,\n key + "_copy",\n MethodType(\n self._copy_files,\n {\n "filename": key,\n "copy_command": f'copy {item}',\n },\n ),\n )\n def add_files_to_class(self, filelist: list):\n for _ in filelist:\n attr_key = re.sub(rf'[^{ascii_letters}]+', '_', _).strip('_')\n self.dict_all_files[attr_key] = _\n self._create_properties()\ndy = DynamicAttr()\ndy.add_files_to_class([r"C:\\Windows\\notepad.exe", r"C:\\Windows\\regedit.exe"])\n\ndy.add_files_to_class([r"C:\\Windows\\HelpPane.exe", r"C:\\Windows\\win.ini"])\n#output\nprint(dy.C_Windows_HelpPane_exe)\ndy.C_Windows_notepad_exe_delete()\ndy.C_Windows_HelpPane_exe_copy()\nC:\\Windows\\HelpPane.exe\ndelete C_Windows_notepad_exe del C:\\Windows\\notepad.exe\ncopy C_Windows_HelpPane_exe copy C:\\Windows\\HelpPane.exe\n</code></pre>\n<p><img src=\"https://i.imgur.com/d2eX4Lj.png\" alt=\"result\" /></p>\n<p>This class allows you to add new attributes and methods at any time.</p>\n<p><strong>Edit:</strong></p>\n<p>Here is a more generalized solution:</p>\n<pre><code>import inspect\nimport re\nfrom copy import deepcopy\nfrom string import ascii_letters\n\n\ndef copy_func(f):\n if callable(f):\n if inspect.ismethod(f) or inspect.isfunction(f):\n g = lambda *args, **kwargs: f(*args, **kwargs)\n t = list(filter(lambda prop: not ("__" in prop), dir(f)))\n i = 0\n while i < len(t):\n setattr(g, t[i], getattr(f, t[i]))\n i += 1\n return g\n dcoi = deepcopy([f])\n return dcoi[0]\n\n\nclass FlexiblePartial:\n def __init__(self, func, this_args_first, *args, **kwargs):\n\n try:\n self.f = copy_func(func) # create a copy of the function\n except Exception:\n self.f = func\n self.this_args_first = this_args_first # where should the other (optional) arguments be that are passed when the function is called\n try:\n self.modulename = args[0].__class__.__name__ # to make repr look good\n except Exception:\n self.modulename = "self"\n\n try:\n self.functionname = func.__name__ # to make repr look good\n except Exception:\n try:\n self.functionname = func.__qualname__ # to make repr look good\n except Exception:\n self.functionname = "func"\n\n self.args = args\n self.kwargs = kwargs\n\n self.name_to_print = self._create_name() # to make repr look good\n\n def _create_name(self):\n stra = self.modulename + "." + self.functionname + "(self, "\n for _ in self.args[1:]:\n stra = stra + repr(_) + ", "\n for key, item in self.kwargs.items():\n stra = stra + str(key) + "=" + repr(item) + ", "\n stra = stra.rstrip().rstrip(",")\n stra += ")"\n if len(stra) > 100:\n stra = stra[:95] + "...)"\n return stra\n\n def __call__(self, *args, **kwargs):\n newdic = {}\n newdic.update(self.kwargs)\n newdic.update(kwargs)\n if self.this_args_first:\n return self.f(*self.args[1:], *args, **newdic)\n\n else:\n\n return self.f(*args, *self.args[1:], **newdic)\n\n def __str__(self):\n return self.name_to_print\n\n def __repr__(self):\n return self.__str__()\n\n\nclass AddMethodsAndProperties:\n def add_methods(self, dict_to_add):\n for key_, item in dict_to_add.items():\n key = re.sub(rf"[^{ascii_letters}]+", "_", str(key_)).rstrip("_")\n if isinstance(item, dict):\n if "function" in item: # for adding methods\n if not isinstance(\n item["function"], str\n ): # for external functions that are not part of the class\n setattr(\n self,\n key,\n FlexiblePartial(\n item["function"],\n item["this_args_first"],\n self,\n *item["args"],\n **item["kwargs"],\n ),\n )\n\n else:\n setattr(\n self,\n key,\n FlexiblePartial(\n getattr(\n self, item["function"]\n ), # for internal functions - part of the class\n item["this_args_first"],\n self,\n *item["args"],\n **item["kwargs"],\n ),\n )\n else: # for adding props\n setattr(self, key, item)\n</code></pre>\n<p>Let's test it:</p>\n<pre><code>class NewClass(AddMethodsAndProperties): #inherit from AddMethodsAndProperties to add the method add_methods\n def __init__(self):\n self.bubu = 5\n\n def _delete_files(self, file): #some random methods \n print(f"File will be deleted: {file}")\n\n def delete_files(self, file):\n self._delete_files(file)\n\n def _copy_files(self, file, dst):\n print(f"File will be copied: {file} Dest: {dst}")\n\n def copy_files(self, file, dst):\n self._copy_files(file, dst)\n\n def _create_files(self, file, folder):\n print(f"File will be created: {file} {folder}")\n\n def create_files(self, file, folder):\n self._create_files(file, folder)\n\n def method_with_more_kwargs(self, file, folder, one_more):\n print(file, folder, one_more)\n return self\n\n\nnc = NewClass()\ndict_all_files = {\n r"C:\\Windows\\notepad.exe_delete": {\n "function": "delete_files",\n "args": (),\n "kwargs": {"file": r"C:\\Windows\\notepad.exe"},\n "this_args_first": True,\n },\n r"C:\\Windows\\notepad.exe_argsfirst": {\n "function": "delete_files",\n "args": (),\n "kwargs": {"file": r"C:\\Windows\\notepad.exe"},\n "this_args_first": True,\n },\n r"C:\\Windows\\notepad.exe_copy": {\n "function": "copy_files",\n "args": (),\n "kwargs": {\n "file": r"C:\\Windows\\notepad.exe",\n "dst": r"C:\\Windows\\notepad555.exe",\n },\n "this_args_first": True,\n },\n r"C:\\Windows\\notepad.exe_create": {\n "function": "create_files",\n "args": (),\n "kwargs": {"file": r"C:\\Windows\\notepad.exe", "folder": "c:\\\\windows95"},\n "this_args_first": True,\n },\n r"C:\\Windows\\notepad.exe_upper": {\n "function": str.upper,\n "args": (r"C:\\Windows\\notepad.exe",),\n "kwargs": {},\n "this_args_first": True,\n },\n r"C:\\Windows\\notepad.exe_method_with_more_kwargs": {\n "function": "method_with_more_kwargs",\n "args": (),\n "kwargs": {"file": r"C:\\Windows\\notepad.exe", "folder": "c:\\\\windows95"},\n "this_args_first": True,\n },\n r"C:\\Windows\\notepad.exe_method_with_more_kwargs_as_args_first": {\n "function": "method_with_more_kwargs",\n "args": (r"C:\\Windows\\notepad.exe", "c:\\\\windows95"),\n "kwargs": {},\n "this_args_first": True,\n },\n r"C:\\Windows\\notepad.exe_method_with_more_kwargs_as_args_last": {\n "function": "method_with_more_kwargs",\n "args": (r"C:\\Windows\\notepad.exe", "c:\\\\windows95"),\n "kwargs": {},\n "this_args_first": False,\n },\n "this_is_a_list": [55, 3, 3, 1, 4, 43],\n}\n\nnc.add_methods(dict_all_files)\n\n\nprint(nc.C_Windows_notepad_exe_delete)\nprint(nc.C_Windows_notepad_exe_delete(), end="\\n\\n")\nprint(nc.C_Windows_notepad_exe_argsfirst)\nprint(nc.C_Windows_notepad_exe_argsfirst(), end="\\n\\n")\nprint(nc.C_Windows_notepad_exe_copy)\nprint(nc.C_Windows_notepad_exe_copy(), end="\\n\\n")\nprint(nc.C_Windows_notepad_exe_create)\nprint(nc.C_Windows_notepad_exe_create(), end="\\n\\n")\nprint(nc.C_Windows_notepad_exe_upper)\nprint(nc.C_Windows_notepad_exe_upper(), end="\\n\\n")\nprint(nc.C_Windows_notepad_exe_method_with_more_kwargs)\nprint(\n nc.C_Windows_notepad_exe_method_with_more_kwargs(\n one_more="f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs(\n one_more="f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs(\n one_more="f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"\n ),\n end="\\n\\n",\n)\nprint(nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_first)\nprint(\n nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_first(\n "f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa"\n ),\n end="\\n\\n",\n)\nprint(\n nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_first(\n "f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_first(\n "f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_first(\n "f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"\n ),\n end="\\n\\n",\n)\nprint(nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_last)\nprint(\n nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n "f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n "f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n "f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"\n ),\n end="\\n\\n",\n)\nprint(\n nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n "f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n "f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n "f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"\n ),\n end="\\n\\n",\n)\nprint(nc.this_is_a_list)\ncheckit = (\n nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n "f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n "f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n "f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"\n )\n)\nprint(f'nc is checkit? -> {nc is checkit}')\n\n\n#output:\n\n\nNewClass.delete_files(self, file='C:\\\\Windows\\\\notepad.exe')\nFile will be deleted: C:\\Windows\\notepad.exe\nNone\n\n\nNewClass.delete_files(self, file='C:\\\\Windows\\\\notepad.exe')\nFile will be deleted: C:\\Windows\\notepad.exe\nNone\n\n\nNewClass.copy_files(self, file='C:\\\\Windows\\\\notepad.exe', dst='C:\\\\Windows\\\\notepad555.exe')\nFile will be copied: C:\\Windows\\notepad.exe Dest: C:\\Windows\\notepad555.exe\nNone\n\n\nNewClass.create_files(self, file='C:\\\\Windows\\\\notepad.exe', folder='c:\\\\windows95')\nFile will be created: C:\\Windows\\notepad.exe c:\\windows95\nNone\n\n\nNewClass.upper(self, 'C:\\\\Windows\\\\notepad.exe')\nC:\\WINDOWS\\NOTEPAD.EXE\n\n\nNewClass.method_with_more_kwargs(self, file='C:\\\\Windows\\\\notepad.exe', folder='c:\\\\windows95')\nC:\\Windows\\notepad.exe c:\\windows95 f:\\blaaaaaaaaaaaaaaaaaaaaaaaa\nC:\\Windows\\notepad.exe c:\\windows95 f:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ\nC:\\Windows\\notepad.exe c:\\windows95 f:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n<__main__.NewClass object at 0x0000000005F199A0>\n\n\nNewClass.method_with_more_kwargs(self, 'C:\\\\Windows\\\\notepad.exe', 'c:\\\\windows95')\nC:\\Windows\\notepad.exe c:\\windows95 f:\\blaaaaaaaaaaaaaaaaaaaaaaaa\n<__main__.NewClass object at 0x0000000005F199A0>\n\n\nC:\\Windows\\notepad.exe c:\\windows95 f:\\blaaaaaaaaaaaaaaaaaaaaaaaa\nC:\\Windows\\notepad.exe c:\\windows95 f:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ\nC:\\Windows\\notepad.exe c:\\windows95 f:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n<__main__.NewClass object at 0x0000000005F199A0>\n\n\nNewClass.method_with_more_kwargs(self, 'C:\\\\Windows\\\\notepad.exe', 'c:\\\\windows95')\nf:\\blaaaaaaaaaaaaaaaaaaaaaaaa C:\\Windows\\notepad.exe c:\\windows95\nf:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ C:\\Windows\\notepad.exe c:\\windows95\nf:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX C:\\Windows\\notepad.exe c:\\windows95\n<__main__.NewClass object at 0x0000000005F199A0>\n\n\nf:\\blaaaaaaaaaaaaaaaaaaaaaaaa C:\\Windows\\notepad.exe c:\\windows95\nf:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ C:\\Windows\\notepad.exe c:\\windows95\nf:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX C:\\Windows\\notepad.exe c:\\windows95\n<__main__.NewClass object at 0x0000000005F199A0>\n\n\n[55, 3, 3, 1, 4, 43]\n\n\nf:\\blaaaaaaaaaaaaaaaaaaaaaaaa C:\\Windows\\notepad.exe c:\\windows95\nf:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ C:\\Windows\\notepad.exe c:\\windows95\nf:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX C:\\Windows\\notepad.exe c:\\windows95\n\n\nnc is checkit? -> True\n</code></pre>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
] | I've read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python.
I understand that it's not always good to do so. But how might one do this? | In Python, there is a difference between functions and bound methods.
```
>>> def foo():
... print "foo"
...
>>> class A:
... def bar( self ):
... print "bar"
...
>>> a = A()
>>> foo
<function foo at 0x00A98D70>
>>> a.bar
<bound method A.bar of <__main__.A instance at 0x00A9BC88>>
>>>
```
Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called.
Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want:
```
>>> def fooFighters( self ):
... print "fooFighters"
...
>>> A.fooFighters = fooFighters
>>> a2 = A()
>>> a2.fooFighters
<bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>>
>>> a2.fooFighters()
fooFighters
```
Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves):
```
>>> a.fooFighters()
fooFighters
```
The problem comes when you want to attach a method to a single instance:
```
>>> def barFighters( self ):
... print "barFighters"
...
>>> a.barFighters = barFighters
>>> a.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: barFighters() takes exactly 1 argument (0 given)
```
The function is not automatically bound when it's attached directly to an instance:
```
>>> a.barFighters
<function barFighters at 0x00A98EF0>
```
To bind it, we can use the [MethodType function in the types module](https://docs.python.org/3/library/types.html#types.MethodType):
```
>>> import types
>>> a.barFighters = types.MethodType( barFighters, a )
>>> a.barFighters
<bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>>
>>> a.barFighters()
barFighters
```
This time other instances of the class have not been affected:
```
>>> a2.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'barFighters'
```
More information can be found by reading about [descriptors](https://docs.python.org/3/howto/descriptor.html) and [metaclass](https://web.archive.org/web/20090124004817/http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html) [programming](http://www.gnosis.cx/publish/programming/metaclass_2.html). |
1,005 | <p>Often while editing config files, I'll open one with vi and then when I go to save it realize that I didn't type</p>
<pre><code>sudo vi filename
</code></pre>
<p>Is there any way to give vi sudo privileges to save the file? I seem to recall seeing something about this while looking up some stuff about vi a while ago, but now I can't find it.</p>
| [
{
"answer_id": 1006,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 1,
"selected": false,
"text": "<p>A quick Google seems to give this advice:</p>\n\n<ol>\n<li>Don't try to edit if it's read-only.</li>\n<li>You might be able to change the permissions on the file. (Whether or not it will let you save is up to experimentation.)</li>\n<li>If you still edited anyway, save to a temporary file and then move it.</li>\n</ol>\n\n<p><a href=\"http://ubuntuforums.org/showthread.php?t=782136\" rel=\"nofollow noreferrer\">http://ubuntuforums.org/showthread.php?t=782136</a></p>\n"
},
{
"answer_id": 1012,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "<p>Ryan's advice is generally good, however, if following step 3, don't move the temporary file; it'll have the wrong ownership and permissions. Instead, <code>sudoedit</code> the correct file and read in the contents (using <code>:r</code> or the like) of the temporary file.</p>\n\n<p>If following step 2, use <code>:w!</code> to force the file to be written.</p>\n"
},
{
"answer_id": 1065,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": false,
"text": "<p>In general, you can't change the effective user id of the vi process, but you can do this:</p>\n\n<pre><code>:w !sudo tee myfile\n</code></pre>\n"
},
{
"answer_id": 2930,
"author": "num1",
"author_id": 306,
"author_profile": "https://Stackoverflow.com/users/306",
"pm_score": -1,
"selected": false,
"text": "<p>A quick hack you can consider is doing a chmod on the file you're editing, save with vim, and then chmod back to what the file was originally.</p>\n\n<pre><code>ls -l test.file (to see the permissions of the file)\nchmod 777 test.file\n[This is where you save in vim]\nchmod xxx test.file (restore the permissions you found in the first step)\n</code></pre>\n\n<p>Of course I don't recommend this approach in a system where you're worried about security, as for a few seconds anyone can read/change the file without you realizing.</p>\n"
},
{
"answer_id": 9113,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "<p>When you go into insert mode on a file you need sudo access to edit, you get a status message saying</p>\n\n<pre><code>-- INSERT -- W10: Warning: Changing a readonly file\n</code></pre>\n\n<p>If I miss that, generally I do</p>\n\n<pre><code>:w ~/edited_blah.tmp\n:q\n</code></pre>\n\n<p>..then..</p>\n\n<pre><code>sudo \"cat edited_blah.tmp > /etc/blah\"\n</code></pre>\n\n<p>..or..</p>\n\n<pre><code>sudo mv edited_blah.tmp /etc/blah\n</code></pre>\n\n<p>There's probably a less roundabout way to do it, but it works.</p>\n"
},
{
"answer_id": 37042,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": true,
"text": "<p><code>%</code> is replaced with the current file name, thus you can use:</p>\n\n<pre><code>:w !sudo tee %\n</code></pre>\n\n<p>(<code>vim</code> will detect that the file has been changed and ask whether you want to it to be reloaded. Say yes by choosing <code>[L]</code> rather than OK.)</p>\n\n<p>As a shortcut, you can define your own command. Put the following in your <code>.vimrc</code>:</p>\n\n<pre><code>command W w !sudo tee % >/dev/null\n</code></pre>\n\n<p>With the above you can type <code>:W<Enter></code> to save the file. Since I wrote this, I have found a nicer way (in my opinion) to do this:</p>\n\n<pre><code>cmap w!! w !sudo tee >/dev/null %\n</code></pre>\n\n<p>This way you can type <code>:w!!</code> and it will be expanded to the full command line, leaving the cursor at the end, so you can replace the <code>%</code> with a file name of your own, if you like.</p>\n"
},
{
"answer_id": 125383,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 4,
"selected": false,
"text": "<p>If you're using <a href=\"http://www.vim.org/\" rel=\"nofollow noreferrer\">Vim</a>, there is a script available named <a href=\"http://www.vim.org/scripts/script.php?script_id=729\" rel=\"nofollow noreferrer\">sudo.vim</a>. If you find that you've opened a file that you need root access to read, type<pre>:e sudo:%</pre>Vim replaces the % with the name of the current file, and <code>sudo:</code> instructs the sudo.vim script to take over for reading and writing.</p>\n"
},
{
"answer_id": 662081,
"author": "pisswillis",
"author_id": 78414,
"author_profile": "https://Stackoverflow.com/users/78414",
"pm_score": 0,
"selected": false,
"text": "<p>I have this in my ~/.bashrc:</p>\n\n<pre><code>alias svim='sudo vim'\n</code></pre>\n\n<p>Now whenever I need to edit a config file I just open it with svim.</p>\n"
},
{
"answer_id": 2163726,
"author": "James Snyder",
"author_id": 105950,
"author_profile": "https://Stackoverflow.com/users/105950",
"pm_score": 1,
"selected": false,
"text": "<p>Here's another one that has appeared since this question was answered, a plugin called SudoEdit which provides SudoRead and SudoWrite functions, which will by default try to use sudo first and su if that fails: <a href=\"http://www.vim.org/scripts/script.php?script_id=2709\" rel=\"nofollow noreferrer\">http://www.vim.org/scripts/script.php?script_id=2709</a></p>\n"
},
{
"answer_id": 12870763,
"author": "Zenexer",
"author_id": 1188377,
"author_profile": "https://Stackoverflow.com/users/1188377",
"pm_score": 4,
"selected": false,
"text": "<h1>Common Caveats</h1>\n\n<p>The most common method of getting around the read-only file problem is to open a pipe to current file as the super-user using an implementation of <code>sudo tee</code>. However, all of the most popular solutions that I have found around the Internet have a combination of a several potential caveats:</p>\n\n<ul>\n<li>The entire file gets written to the terminal, as well as the file. This can be slow for large files, especially over slow network connections.</li>\n<li>The file loses its modes and similar attributes.</li>\n<li>File paths with unusual characters or spaces might not be handled correctly.</li>\n</ul>\n\n<h1>Solutions</h1>\n\n<p>To get around all of these issues, you can use the following command:</p>\n\n<pre><code>\" On POSIX (Linux/Mac/BSD):\n:silent execute 'write !sudo tee ' . shellescape(@%, 1) . ' >/dev/null'\n\n\" Depending on the implementation, you might need this on Windows:\n:silent execute 'write !sudo tee ' . shellescape(@%, 1) . ' >NUL'\n</code></pre>\n\n<p>These can be shortened, respectfully:</p>\n\n<pre><code>:sil exec 'w !sudo tee ' . shellescape(@%, 1) . ' >/dev/null'\n:sil exec 'w !sudo tee ' . shellescape(@%, 1) . ' >NUL'\n</code></pre>\n\n<h1>Explanation</h1>\n\n<p><code>:</code> begins the command; you will need to type this character in normal mode to start entering a command. It should be omitted in scripts.</p>\n\n<p><code>sil[ent]</code> suppresses output from the command. In this case, we want to stop the <code>Press any key to continue</code>-like prompt that appears after running the <code>:!</code> command.</p>\n\n<p><code>exec[ute]</code> executes a string as a command. We can't just run <code>:write</code> because it won't process the necessary function call.</p>\n\n<p><code>!</code> represents the <code>:!</code> command: the only command that <code>:write</code> accepts. Normally, <code>:write</code> accepts a file path to which to write. <code>:!</code> on its own runs a command in a shell (for example, using <code>bash -c</code>). With <code>:write</code>, it will run the command in the shell, and then write the entire file to <code>stdin</code>.</p>\n\n<p><code>sudo</code> should be obvious, since that's why you're here. Run the command as the super-user. There's plenty of information around the 'net about how that works.</p>\n\n<p><code>tee</code> pipes <code>stdin</code> to the given file. <code>:write</code> will write to <code>stdin</code>, then the super-user <code>tee</code> will receive the file contents and write the file. It won't create a new file--just overwrite the contents--so file modes and attributes will be preserved.</p>\n\n<p><code>shellescape()</code> escapes special characters in the given file path as appropriate for the current shell. With just one parameter, it would typically just enclose the path in quotes as necessary. Since we're sending to a full shell command line, we'll want to pass a non-zero value as the second argument to enable backslash-escaping of other special characters that might otherwise trip up the shell.</p>\n\n<p><code>@%</code> reads the contents of the <code>%</code> register, which contains the current buffer's file name. It's not necessarily an absolute path, so ensure that you haven't changed the current directory. In some solutions, you will see the commercial-at symbol omitted. Depending on the location, <code>%</code> is a valid expression, and has the same effect as reading the <code>%</code> register. Nested inside another expression the shortcut is generally disallowed, however: such as in this case.</p>\n\n<p><code>>NUL</code> and <code>>/dev/null</code> redirect <code>stdout</code> to the platform's null device. Even though we've silenced the command, we don't want all of the overhead associated with piping <code>stdin</code> back to vim--best to dump it as early as possible. <code>NUL</code> is the null device on DOS, MS-DOS, and Windows, not a valid file. As of Windows 8 redirections to NUL don't result in a file named NUL being written. Try creating a file on your desktop named NUL, with or without a file extension: you will be unable to do so. (There are several other device names in Windows that might be worth getting to know.)</p>\n\n<h1>~/.vimrc</h1>\n\n<h2>Platform-Dependent</h2>\n\n<p>Of course, you still don't want to memorize those and type them out each time. It's much easier to map the appropriate command to a simpler user command. To do this on POSIX, you could add the following line to your <code>~/.vimrc</code> file, creating it if it doesn't already exist:</p>\n\n<pre><code>command W silent execute 'write !sudo tee ' . shellescape(@%, 1) . ' >/dev/null'\n</code></pre>\n\n<p>This will allow you to type the :W (case-sensitive) command to write the current file with super-user permissions--much easier.</p>\n\n<h2>Platform-Independent</h2>\n\n<p>I use a platform-independent <code>~/.vimrc</code> file that synchronizes across computers, so I added multi-platform functionality to mine. Here's a <code>~/.vimrc</code> with only the relevant settings:</p>\n\n<pre><code>#!vim\n\" Use za (not a command; the keys) in normal mode to toggle a fold.\n\" META_COMMENT Modeline Definition: {{{1\n\" vim: ts=4 sw=4 sr sts=4 fdm=marker ff=unix fenc=utf-8\n\" ts: Actual tab character stops.\n\" sw: Indentation commands shift by this much.\n\" sr: Round existing indentation when using shift commands.\n\" sts: Virtual tab stops while using tab key.\n\" fdm: Folds are manually defined in file syntax.\n\" ff: Line endings should always be <NL> (line feed #09).\n\" fenc: Should always be UTF-8; #! must be first bytes, so no BOM.\n\n\n\" General Commands: User Ex commands. {{{1\n command W call WriteAsSuperUser(@%) \" Write file as super-user.\n\n\n\" Helper Functions: Used by user Ex commands. {{{1\n function GetNullDevice() \" Gets the path to the null device. {{{2\n if filewritable('/dev/null')\n return '/dev/null'\n else\n return 'NUL'\n endif\n endfunction\n\n function WriteAsSuperUser(file) \" Write buffer to a:file as the super user (on POSIX, root). {{{2\n exec '%write !sudo tee ' . shellescape(a:file, 1) . ' >' . GetNullDevice()\n endfunction\n\n\n\" }}}1\n\" EOF\n</code></pre>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] | Often while editing config files, I'll open one with vi and then when I go to save it realize that I didn't type
```
sudo vi filename
```
Is there any way to give vi sudo privileges to save the file? I seem to recall seeing something about this while looking up some stuff about vi a while ago, but now I can't find it. | `%` is replaced with the current file name, thus you can use:
```
:w !sudo tee %
```
(`vim` will detect that the file has been changed and ask whether you want to it to be reloaded. Say yes by choosing `[L]` rather than OK.)
As a shortcut, you can define your own command. Put the following in your `.vimrc`:
```
command W w !sudo tee % >/dev/null
```
With the above you can type `:W<Enter>` to save the file. Since I wrote this, I have found a nicer way (in my opinion) to do this:
```
cmap w!! w !sudo tee >/dev/null %
```
This way you can type `:w!!` and it will be expanded to the full command line, leaving the cursor at the end, so you can replace the `%` with a file name of your own, if you like. |
1,010 | <p>I need to grab the <code>base64-encoded</code> representation of the <code>ViewState</code>. Obviously, this would not be available until fairly late in the request lifecycle, which is OK.</p>
<p>For example, if the output of the page includes:</p>
<pre><code><input type="hidden" name="__VIEWSTATE"
id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" />
</code></pre>
<p>I need a way on the server-side to get the value <code>"/wEPDwUJODU0Njc5MD...=="</code></p>
<p>To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being <em>sent</em> to the client, not the ViewState I'm getting back from them.</p>
| [
{
"answer_id": 1074,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 5,
"selected": true,
"text": "<p>Rex, I suspect a good place to start looking is solutions that <strong>compress the ViewState</strong> -- they're grabbing ViewState on the server before it's sent down to the client and gzipping it. That's exactly where you want to be.</p>\n\n<ul>\n<li><a href=\"http://www.hanselman.com/blog/CommentView,guid,febce059-7e7c-439e-af3d-c53d250b3e9c.aspx\" rel=\"noreferrer\">Scott Hanselman on ViewState Compression</a> (2005)</li>\n<li><a href=\"http://www.bloggingdeveloper.com/post/How-To-Compress-ViewState-in-ASPNET-20-ViewState-Compression-with-SystemIOCompression.aspx\" rel=\"noreferrer\">ViewState Compression with System.IO.Compression</a> (2007)</li>\n</ul>\n"
},
{
"answer_id": 1093,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 2,
"selected": false,
"text": "<p>See this <a href=\"http://aspguy.wordpress.com/2008/07/09/reducing-the-page-size-by-storing-viewstate-on-server/\" rel=\"nofollow noreferrer\">blog post</a> where the author describes a method for overriding the default behavior for generating the ViewState and instead shows how to save it on the server Session object.</p>\n\n<blockquote>\n <p>In ASP.NET 2.0, ViewState is saved by\n a descendant of PageStatePersister\n class. This class is an abstract class\n for saving and loading ViewsState and\n there are two implemented descendants\n of this class in .Net Framework, named\n HiddenFieldPageStatePersister and\n SessionPageStatePersister. By default\n HiddenFieldPageStatePersister is used\n to save/load ViewState information,\n but we can easily get the\n SessionPageStatePersister to work and\n save ViewState in Session object.</p>\n</blockquote>\n\n<p>Although I did not test his code, it seems to show exactly what you want: a way to gain access to ViewState code while still on the server, before postback. </p>\n"
},
{
"answer_id": 2058,
"author": "Dave Anderson",
"author_id": 371,
"author_profile": "https://Stackoverflow.com/users/371",
"pm_score": 2,
"selected": false,
"text": "<p>I enabled compression following similar articles to those posted above. The key to accessing the ViewState before the application sends it was overriding this method;</p>\n\n<pre><code>protected override void SavePageStateToPersistenceMedium(object viewState)\n</code></pre>\n\n<p>You can call the base method within this override and then add whatever additional logic you require to handle the ViewState.</p>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67/"
] | I need to grab the `base64-encoded` representation of the `ViewState`. Obviously, this would not be available until fairly late in the request lifecycle, which is OK.
For example, if the output of the page includes:
```
<input type="hidden" name="__VIEWSTATE"
id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" />
```
I need a way on the server-side to get the value `"/wEPDwUJODU0Njc5MD...=="`
To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being *sent* to the client, not the ViewState I'm getting back from them. | Rex, I suspect a good place to start looking is solutions that **compress the ViewState** -- they're grabbing ViewState on the server before it's sent down to the client and gzipping it. That's exactly where you want to be.
* [Scott Hanselman on ViewState Compression](http://www.hanselman.com/blog/CommentView,guid,febce059-7e7c-439e-af3d-c53d250b3e9c.aspx) (2005)
* [ViewState Compression with System.IO.Compression](http://www.bloggingdeveloper.com/post/How-To-Compress-ViewState-in-ASPNET-20-ViewState-Compression-with-SystemIOCompression.aspx) (2007) |
1,042 | <p>For instance, my query is like the following using SQL Server 2005:</p>
<pre><code>SELECT * FROM Table WHERE FREETEXT(SearchField, 'c#')
</code></pre>
<p>I have a full text index defined to use the column SearchField which returns results when using:</p>
<pre><code>SELECT * FROM Table WHERE SearchField LIKE '%c#%'
</code></pre>
<p>I believe # is a special letter, so how do I allow FREETEXT to work correctly for the query above?</p>
| [
{
"answer_id": 1047,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 1,
"selected": false,
"text": "<p>Quoting a much-replicated help page about Indexing Service query language:</p>\n\n<blockquote>\n <p>To use specially treated characters such as &, |, ^, #, @, $, (, ), in a query, enclose your query in quotation marks (“).</p>\n</blockquote>\n\n<p>As far as I know, full text search in <code>MSSQL</code> is also done by the Indexing Service, so this might help.</p>\n"
},
{
"answer_id": 1061,
"author": "Jarrod Dixon",
"author_id": 3,
"author_profile": "https://Stackoverflow.com/users/3",
"pm_score": 5,
"selected": true,
"text": "<p>The # char is indexed as punctuation and therefore ignored, so it looks like we'll remove the letter C from our word indexing ignore lists.</p>\n\n<p>Tested it locally after doing that and rebuilding the indexes and I get results!</p>\n\n<p>Looking at using a different word breaker language on the indexed column, so that those special characters aren't ignored.</p>\n\n<p>EDIT: I also found <a href=\"http://www.simple-talk.com/sql/learn-sql-server/sql-server-full-text-search-language-features/\" rel=\"noreferrer\">this information</a>:</p>\n\n<blockquote>\n <p>c# is indexed as c (if c is not in your noise word list, see more on noise word lists later), but C# is indexed as C# (in SQL 2005 and SQL 2000 running on Win2003 regardless if C or c is in your noise word list). It is not only C# that is stored as C#, but any capital letter followed by #. Conversely, c++ ( and any other lower-cased letter followed by a ++) is indexed as c (regardless of whether c is in your noise word list).</p>\n</blockquote>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2/"
] | For instance, my query is like the following using SQL Server 2005:
```
SELECT * FROM Table WHERE FREETEXT(SearchField, 'c#')
```
I have a full text index defined to use the column SearchField which returns results when using:
```
SELECT * FROM Table WHERE SearchField LIKE '%c#%'
```
I believe # is a special letter, so how do I allow FREETEXT to work correctly for the query above? | The # char is indexed as punctuation and therefore ignored, so it looks like we'll remove the letter C from our word indexing ignore lists.
Tested it locally after doing that and rebuilding the indexes and I get results!
Looking at using a different word breaker language on the indexed column, so that those special characters aren't ignored.
EDIT: I also found [this information](http://www.simple-talk.com/sql/learn-sql-server/sql-server-full-text-search-language-features/):
>
> c# is indexed as c (if c is not in your noise word list, see more on noise word lists later), but C# is indexed as C# (in SQL 2005 and SQL 2000 running on Win2003 regardless if C or c is in your noise word list). It is not only C# that is stored as C#, but any capital letter followed by #. Conversely, c++ ( and any other lower-cased letter followed by a ++) is indexed as c (regardless of whether c is in your noise word list).
>
>
> |
1,064 | <p>I'd like to display 100 floating cubes using <code>DirectX</code> or <code>OpenGL</code>.</p>
<p>I'm looking for either some sample source code, or a description of the technique. I have trouble getting more one cube to display correctly.</p>
<p>I've combed the net for a good series of tutorials and although they talk about how to do <code>3D</code> primitives, what I can't find is information on how to do large numbers of <code>3D</code> primitives - <code>cubes</code>, <code>spheres</code>, <code>pyramids</code>, and so forth.</p>
| [
{
"answer_id": 1092,
"author": "Bernard",
"author_id": 61,
"author_profile": "https://Stackoverflow.com/users/61",
"pm_score": 3,
"selected": false,
"text": "<p>Just use glTranslatef (or the DirectX equivalent) to draw a cube using the same code, but moving the relative point where you draw it. Maybe there's a better way to do it though, I'm fairly new to OpenGL. Be sure to set your viewpoint so you can see them all.</p>\n"
},
{
"answer_id": 1096,
"author": "Redbaron",
"author_id": 41,
"author_profile": "https://Stackoverflow.com/users/41",
"pm_score": 4,
"selected": true,
"text": "<p>You say you have enough trouble getting one cube to display... so I am not sure if you have got one to display or not.</p>\n\n<p>Basically... put your code for writing a cube in one function, then just call that function 100 times.</p>\n\n<pre><code>void DrawCube()\n{\n //code to draw the cube\n}\n\nvoid DisplayCubes()\n{\n for(int i = 0; i < 10; ++i)\n { \n for(int j = 0; j < 10; ++j)\n {\n glPushMatrix();\n //alter these values depending on the size of your cubes.\n //This call makes sure that your cubes aren't drawn overtop of each other\n glTranslatef(i*5.0, j*5.0, 0);\n DrawCube();\n glPopMatrix();\n }\n } \n}\n</code></pre>\n\n<p>That is the basic outline for how you could go about doing this. If you want something more efficient take a look into Display Lists sometime once you have the basics figured out :)</p>\n"
},
{
"answer_id": 15989,
"author": "Ali Parr",
"author_id": 1169,
"author_profile": "https://Stackoverflow.com/users/1169",
"pm_score": 3,
"selected": false,
"text": "<p>Yeah, if you were being efficient you'd throw everything into the same vertex buffer, but I don't think drawing 100 cubes will push any GPU produced in the past 5 years, so you should be fine following the suggestions above.</p>\n\n<p>Write a basic pass through vertex shader, shade however you desire in the pixel shader. Either pass in a world matrix and do the translation in the vertex shader, or just compute the world space vertex positions on the CPU side (do this if your cubes are going to stay fixed).</p>\n\n<p>You could get fancy and do <a href=\"http://en.wikipedia.org/wiki/Geometry_instancing\" rel=\"noreferrer\">geometry instancing</a> etc, but just get the basics going first. </p>\n"
},
{
"answer_id": 73391536,
"author": "new QOpenGLWidget",
"author_id": 9194639,
"author_profile": "https://Stackoverflow.com/users/9194639",
"pm_score": -1,
"selected": false,
"text": "<p>This answer isn't just for OP's question. It also answers a more general question - displaying many cubes <em>in general</em>.</p>\n<h3>Drawing many cube meshes</h3>\n<p>This is probably the most naive way of doing things. We draw the same cube mesh with many different transformation matrices:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>prepare();\n\nfor (int i = 0; i < numCubes; i++) {\n setTransformation(matrices[i]);\n drawCube();\n}\n/* and so on... */\n</code></pre>\n<p>The nice thing is that this is SUPER easy to implement, and it's not <em>too</em> slow (at least for 100 cubes). I'd recommend this as a starter.</p>\n<h3>The problem</h3>\nOk, but let's say you want to make a Minecraft clone, or at least some sort of project that requires thousands, if not tens of thousands of cubes to be rendered. That's where the performance starts to go down. The problem is that each drawCube() sends a draw call to the GPU, and the time in each draw call adds up, so that eventually, it's unbearable.\n<p>However, we can fix this. The solution is <em>batching</em>, a way to do only <em>one</em> draw call for all of the cubes.</p>\n<h3>Batching</h3>\n<p>We join all the (transformed) cubes into one single mesh. This means that we will have to deal with only one draw call, instead of thousands. Here is some pseudocode for doing so:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>vector<float> transformedVerts;\n\nfor (int i = 0; i < numCubes; i++) {\n cubeData = cubes[i];\n for (int j = 0; j < numVertsPerCube; j++) {\n vert = verts[j];\n /* We transform the position by the transformation matrix. */\n vec3 vposition = matrices[i] * verts.position; \n transformedVerts.push(vposition);\n\n /* We don't need to transform the colors, so we just directly push them. */\n transformedVerts.push(vert.color);\n }\n}\n\n...\nsendDataToBuffer(transformedVerts); \n</code></pre>\n<p>If the cubes are moving, or one of the cubes is added or deleted, you'll have to recalculate <code>transformedVerts</code> and then resend it to the buffer - but this is minor.</p>\n<p>Then at the end we draw the entire lumped-together mesh in one draw call, instead of many.</p>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'd like to display 100 floating cubes using `DirectX` or `OpenGL`.
I'm looking for either some sample source code, or a description of the technique. I have trouble getting more one cube to display correctly.
I've combed the net for a good series of tutorials and although they talk about how to do `3D` primitives, what I can't find is information on how to do large numbers of `3D` primitives - `cubes`, `spheres`, `pyramids`, and so forth. | You say you have enough trouble getting one cube to display... so I am not sure if you have got one to display or not.
Basically... put your code for writing a cube in one function, then just call that function 100 times.
```
void DrawCube()
{
//code to draw the cube
}
void DisplayCubes()
{
for(int i = 0; i < 10; ++i)
{
for(int j = 0; j < 10; ++j)
{
glPushMatrix();
//alter these values depending on the size of your cubes.
//This call makes sure that your cubes aren't drawn overtop of each other
glTranslatef(i*5.0, j*5.0, 0);
DrawCube();
glPopMatrix();
}
}
}
```
That is the basic outline for how you could go about doing this. If you want something more efficient take a look into Display Lists sometime once you have the basics figured out :) |
1,108 | <p>Given that indexing is so important as your data set increases in size, can someone explain how indexing works at a database-agnostic level?</p>
<p>For information on queries to index a field, check out <a href="https://stackoverflow.com/questions/1156/">How do I index a database column</a>.</p>
| [
{
"answer_id": 1130,
"author": "Xenph Yan",
"author_id": 264,
"author_profile": "https://Stackoverflow.com/users/264",
"pm_score": 13,
"selected": true,
"text": "<p><strong>Why is it needed?</strong></p>\n<p>When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously.</p>\n<p>Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires <code>(N+1)/2</code> block accesses (on average), where <code>N</code> is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire tablespace must be searched at <code>N</code> block accesses.</p>\n<p>Whereas with a sorted field, a Binary Search may be used, which has <code>log2 N</code> block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial.</p>\n<p><strong>What is indexing?</strong></p>\n<p>Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it.</p>\n<p>The downside to indexing is that these indices require additional space on the disk since the indices are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed.</p>\n<p><strong>How does it work?</strong></p>\n<p>Firstly, let’s outline a sample database table schema;</p>\n<pre>\nField name Data type Size on disk\nid (Primary key) Unsigned INT 4 bytes\nfirstName Char(50) 50 bytes\nlastName Char(50) 50 bytes\nemailAddress Char(100) 100 bytes\n</pre>\n<p><strong>Note</strong>: char was used in place of varchar to allow for an accurate size on disk value.\nThis sample database contains five million rows and is unindexed. The performance of several queries will now be analyzed. These are a query using the <em>id</em> (a sorted key field) and one using the <em>firstName</em> (a non-key unsorted field).</p>\n<p><em><strong>Example 1</strong></em> - <em>sorted vs unsorted fields</em></p>\n<p>Given our sample database of <code>r = 5,000,000</code> records of a fixed size giving a record length of <code>R = 204</code> bytes and they are stored in a table using the MyISAM engine which is using the default block size <code>B = 1,024</code> bytes. The blocking factor of the table would be <code>bfr = (B/R) = 1024/204 = 5</code> records per disk block. The total number of blocks required to hold the table is <code>N = (r/bfr) = 5000000/5 = 1,000,000</code> blocks.</p>\n<p>A linear search on the id field would require an average of <code>N/2 = 500,000</code> block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of <code>log2 1000000 = 19.93 = 20</code> block accesses. Instantly we can see this is a drastic improvement.</p>\n<p>Now the <em>firstName</em> field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact <code>N = 1,000,000</code> block accesses. It is this situation that indexing aims to correct.</p>\n<p>Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the <em>firstName</em> field is outlined below;</p>\n<pre>\nField name Data type Size on disk\nfirstName Char(50) 50 bytes\n(record pointer) Special 4 bytes\n</pre>\n<p><strong>Note</strong>: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table.</p>\n<p><em><strong>Example 2</strong></em> - <em>indexing</em></p>\n<p>Given our sample database of <code>r = 5,000,000</code> records with an index record length of <code>R = 54</code> bytes and using the default block size <code>B = 1,024</code> bytes. The blocking factor of the index would be <code>bfr = (B/R) = 1024/54 = 18</code> records per disk block. The total number of blocks required to hold the index is <code>N = (r/bfr) = 5000000/18 = 277,778</code> blocks.</p>\n<p>Now a search using the <em>firstName</em> field can utilize the index to increase performance. This allows for a binary search of the index with an average of <code>log2 277778 = 18.08 = 19</code> block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to <code>19 + 1 = 20</code> block accesses, a far cry from the 1,000,000 block accesses required to find a <em>firstName</em> match in the non-indexed table.</p>\n<p><strong>When should it be used?</strong></p>\n<p>Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indices can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index.</p>\n<p>Since indices are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space.</p>\n"
},
{
"answer_id": 16302431,
"author": "Der U",
"author_id": 2331665,
"author_profile": "https://Stackoverflow.com/users/2331665",
"pm_score": 8,
"selected": false,
"text": "<p>The first time I read this it was very helpful to me. Thank you.</p>\n\n<p>Since then I gained some insight about the downside of creating indexes:\nif you write into a table (<code>UPDATE</code> or <code>INSERT</code>) with one index, you have actually two writing operations in the file system. One for the table data and another one for the index data (and the resorting of it (and - if clustered - the resorting of the table data)). If table and index are located on the same hard disk this costs more time. Thus a table without an index (a heap) , would allow for quicker write operations. (if you had two indexes you would end up with three write operations, and so on)</p>\n\n<p>However, defining two different locations on two different hard disks for index data and table data can decrease/eliminate the problem of increased cost of time. This requires definition of additional file groups with according files on the desired hard disks and definition of table/index location as desired.</p>\n\n<p>Another problem with indexes is their fragmentation over time as data is inserted. <code>REORGANIZE</code> helps, you must write routines to have it done.</p>\n\n<p>In certain scenarios a heap is more helpful than a table with indexes, </p>\n\n<p>e.g:- If you have lots of rivalling writes but only one nightly read outside business hours for reporting.</p>\n\n<p>Also, a differentiation between clustered and non-clustered indexes is rather important. </p>\n\n<p>Helped me:- <a href=\"https://stackoverflow.com/questions/1251636/what-do-clustered-and-non-clustered-index-actually-mean\">What do Clustered and Non clustered index actually mean?</a></p>\n"
},
{
"answer_id": 21911020,
"author": "hcarreras",
"author_id": 1611802,
"author_profile": "https://Stackoverflow.com/users/1611802",
"pm_score": 8,
"selected": false,
"text": "<p>An index is just a data structure that makes the searching faster for a specific column in a database. This structure is usually a b-tree or a hash table but it can be any other logic structure.</p>\n"
},
{
"answer_id": 38710465,
"author": "ProgrammerPanda",
"author_id": 5960393,
"author_profile": "https://Stackoverflow.com/users/5960393",
"pm_score": 7,
"selected": false,
"text": "<h2><strong>Simple Description!</strong></h2>\n\n<p>The index is nothing but a data structure that <strong>stores the values for a specific column</strong> in a table. An index is created on a column of a table. </p>\n\n<p>Example: We have a database table called <code>User</code> with three columns – <code>Name</code>, <code>Age</code> and <code>Address</code>. Assume that the <code>User</code> table has thousands of rows.</p>\n\n<p>Now, let’s say that we want to run a query to find all the details of any users who are named 'John'. \nIf we run the following query: </p>\n\n<pre><code>SELECT * FROM User \nWHERE Name = 'John'\n</code></pre>\n\n<p>The database software would literally have to look at every single row in the <code>User</code> table to see if the <code>Name</code> for that row is ‘John’. This will take a long time.</p>\n\n<p>This is where <code>index</code> helps us: <em>index is used to speed up search queries by essentially cutting down the number of records/rows in a table that needs to be examined</em>. </p>\n\n<p>How to create an index:</p>\n\n<pre><code>CREATE INDEX name_index\nON User (Name)\n</code></pre>\n\n<p>An <code>index</code> consists of <strong>column values(Eg: John) from one table</strong>, and those values are stored in a <strong>data structure</strong>. </p>\n\n<blockquote>\n <p>So now the database will use the index to find employees named John\n because the index will presumably be sorted alphabetically by the\n Users name. And, because it is sorted, it means searching for a name\n is a lot faster because all names starting with a “J” will be right\n next to each other in the index!</p>\n</blockquote>\n"
},
{
"answer_id": 38935815,
"author": "Somnath Muluk",
"author_id": 1045444,
"author_profile": "https://Stackoverflow.com/users/1045444",
"pm_score": 8,
"selected": false,
"text": "<p>Now, let’s say that we want to run a query to find all the details of any employees who are named ‘Abc’?</p>\n\n<pre><code>SELECT * FROM Employee \nWHERE Employee_Name = 'Abc'\n</code></pre>\n\n<p><strong>What would happen without an index?</strong></p>\n\n<p>Database software would literally have to look at every single row in the Employee table to see if the Employee_Name for that row is ‘Abc’. And, because we want every row with the name ‘Abc’ inside it, we can not just stop looking once we find just one row with the name ‘Abc’, because there could be other rows with the name <strong>Abc</strong>. So, every row up until the last row must be searched – which means thousands of rows in this scenario will have to be examined by the database to find the rows with the name ‘Abc’. This is what is called a <strong>full table scan</strong></p>\n\n<p><strong>How a database index can help performance</strong></p>\n\n<p>The whole point of having an index is to speed up search queries by essentially cutting down the number of records/rows in a table that need to be examined. An index is a data structure (most commonly a B- tree) that stores the values for a specific column in a table. </p>\n\n<p><strong>How does B-trees index work?</strong></p>\n\n<p>The reason B- trees are the most popular data structure for indexes is due to the fact that they are time efficient – because look-ups, deletions, and insertions can all be done in logarithmic time. And, another major reason B- trees are more commonly used is because the data that is stored inside the B- tree can be sorted. The RDBMS typically determines which data structure is actually used for an index. But, in some scenarios with certain RDBMS’s, you can actually specify which data structure you want your database to use when you create the index itself.</p>\n\n<p><strong>How does a hash table index work?</strong></p>\n\n<p>The reason hash indexes are used is because hash tables are extremely efficient when it comes to just looking up values. So, queries that compare for equality to a string can retrieve values very fast if they use a hash index. </p>\n\n<p>For instance, the query we discussed earlier could benefit from a hash index created on the Employee_Name column. The way a hash index would work is that the column value will be the key into the hash table and the actual value mapped to that key would just be a pointer to the row data in the table. Since a hash table is basically an associative array, a typical entry would look something like “Abc => 0x28939″, where 0x28939 is a reference to the table row where Abc is stored in memory. Looking up a value like “Abc” in a hash table index and getting back a reference to the row in memory is obviously a lot faster than scanning the table to find all the rows with a value of “Abc” in the Employee_Name column.</p>\n\n<p><strong>The disadvantages of a hash index</strong></p>\n\n<p>Hash tables are not sorted data structures, and there are many types of queries which hash indexes can not even help with. For instance, suppose you want to find out all of the employees who are less than 40 years old. How could you do that with a hash table index? Well, it’s not possible because a hash table is only good for looking up key value pairs – which means queries that check for equality </p>\n\n<p><strong>What exactly is inside a database index?</strong>\nSo, now you know that a database index is created on a column in a table, and that the index stores the values in that specific column. But, it is important to understand that a database index does not store the values in the other columns of the same table. For example, if we create an index on the Employee_Name column, this means that the Employee_Age and Employee_Address column values are not also stored in the index. If we did just store all the other columns in the index, then it would be just like creating another copy of the entire table – which would take up way too much space and would be very inefficient.</p>\n\n<p><strong>How does a database know when to use an index?</strong>\nWhen a query like “SELECT * FROM Employee WHERE Employee_Name = ‘Abc’ ” is run, the database will check to see if there is an index on the column(s) being queried. Assuming the Employee_Name column does have an index created on it, the database will have to decide whether it actually makes sense to use the index to find the values being searched – because there are some scenarios where it is actually less efficient to use the database index, and more efficient just to scan the entire table.</p>\n\n<p><strong>What is the cost of having a database index?</strong></p>\n\n<p>It takes up space – and the larger your table, the larger your index. Another performance hit with indexes is the fact that whenever you add, delete, or update rows in the corresponding table, the same operations will have to be done to your index. Remember that an index needs to contain the same up to the minute data as whatever is in the table column(s) that the index covers.</p>\n\n<p>As a general rule, an index should only be created on a table if the data in the indexed column will be queried frequently.</p>\n\n<p>See also </p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/questions/107132/what-columns-generally-make-good-indexes/8937872#8937872\">What columns generally make good indexes?</a></li>\n<li><a href=\"http://www.programmerinterview.com/index.php/database-sql/what-is-an-index/\" rel=\"noreferrer\">How do database indexes work</a></li>\n</ol>\n"
},
{
"answer_id": 41268376,
"author": "Alf Moh",
"author_id": 5138921,
"author_profile": "https://Stackoverflow.com/users/5138921",
"pm_score": 5,
"selected": false,
"text": "<p>Just think of Database Index as Index of a book.</p>\n\n<p>If you have a book about dogs and you want to find an information about let's say, German Shepherds, you could of course flip through all the pages of the book and find what you are looking for - but this of course is time consuming and not very fast. </p>\n\n<p>Another option is that, you could just go to the Index section of the book and then find what you are looking for by using the Name of the entity you are looking ( in this instance, German Shepherds) and also looking at the page number to quickly find what you are looking for. </p>\n\n<p>In Database, the page number is referred to as a pointer which directs the database to the address on the disk where entity is located. Using the same German Shepherd analogy, we could have something like this (“German Shepherd”, 0x77129) where <code>0x77129</code> is the address on the disk where the row data for German Shepherd is stored. </p>\n\n<p>In short, an index is a data structure that stores the values for a specific column in a table so as to speed up query search.</p>\n"
},
{
"answer_id": 43572540,
"author": "Sankarganesh Eswaran",
"author_id": 2629588,
"author_profile": "https://Stackoverflow.com/users/2629588",
"pm_score": 9,
"selected": false,
"text": "<p>Classic example <strong>\"Index in Books\"</strong></p>\n\n<p>Consider a \"Book\" of 1000 pages, divided by 10 Chapters, each section with 100 pages.</p>\n\n<p>Simple, huh?</p>\n\n<p>Now, imagine you want to find a particular Chapter that contains a word \"<strong>Alchemist</strong>\". Without an index page, you have no other option than scanning through the entire book/Chapters. i.e: 1000 pages. </p>\n\n<p>This analogy is known as <strong>\"Full Table Scan\"</strong> in database world.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Mnuvr.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Mnuvr.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>But with an index page, you know where to go! And more, to lookup any particular Chapter that matters, you just need to look over the index page, again and again, every time. After finding the matching index you can efficiently jump to that chapter by skipping the rest.</p>\n\n<p>But then, in addition to actual 1000 pages, you will need another ~10 pages to show the indices, so totally 1010 pages.</p>\n\n<blockquote>\n <p>Thus, the index is a separate section that stores values of indexed\n column + pointer to the indexed row in a sorted order for efficient\n look-ups.</p>\n</blockquote>\n\n<p>Things are simple in schools, isn't it? :P</p>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264/"
] | Given that indexing is so important as your data set increases in size, can someone explain how indexing works at a database-agnostic level?
For information on queries to index a field, check out [How do I index a database column](https://stackoverflow.com/questions/1156/). | **Why is it needed?**
When data is stored on disk-based storage devices, it is stored as blocks of data. These blocks are accessed in their entirety, making them the atomic disk access operation. Disk blocks are structured in much the same way as linked lists; both contain a section for data, a pointer to the location of the next node (or block), and both need not be stored contiguously.
Due to the fact that a number of records can only be sorted on one field, we can state that searching on a field that isn’t sorted requires a Linear Search which requires `(N+1)/2` block accesses (on average), where `N` is the number of blocks that the table spans. If that field is a non-key field (i.e. doesn’t contain unique entries) then the entire tablespace must be searched at `N` block accesses.
Whereas with a sorted field, a Binary Search may be used, which has `log2 N` block accesses. Also since the data is sorted given a non-key field, the rest of the table doesn’t need to be searched for duplicate values, once a higher value is found. Thus the performance increase is substantial.
**What is indexing?**
Indexing is a way of sorting a number of records on multiple fields. Creating an index on a field in a table creates another data structure which holds the field value, and a pointer to the record it relates to. This index structure is then sorted, allowing Binary Searches to be performed on it.
The downside to indexing is that these indices require additional space on the disk since the indices are stored together in a table using the MyISAM engine, this file can quickly reach the size limits of the underlying file system if many fields within the same table are indexed.
**How does it work?**
Firstly, let’s outline a sample database table schema;
```
Field name Data type Size on disk
id (Primary key) Unsigned INT 4 bytes
firstName Char(50) 50 bytes
lastName Char(50) 50 bytes
emailAddress Char(100) 100 bytes
```
**Note**: char was used in place of varchar to allow for an accurate size on disk value.
This sample database contains five million rows and is unindexed. The performance of several queries will now be analyzed. These are a query using the *id* (a sorted key field) and one using the *firstName* (a non-key unsorted field).
***Example 1*** - *sorted vs unsorted fields*
Given our sample database of `r = 5,000,000` records of a fixed size giving a record length of `R = 204` bytes and they are stored in a table using the MyISAM engine which is using the default block size `B = 1,024` bytes. The blocking factor of the table would be `bfr = (B/R) = 1024/204 = 5` records per disk block. The total number of blocks required to hold the table is `N = (r/bfr) = 5000000/5 = 1,000,000` blocks.
A linear search on the id field would require an average of `N/2 = 500,000` block accesses to find a value, given that the id field is a key field. But since the id field is also sorted, a binary search can be conducted requiring an average of `log2 1000000 = 19.93 = 20` block accesses. Instantly we can see this is a drastic improvement.
Now the *firstName* field is neither sorted nor a key field, so a binary search is impossible, nor are the values unique, and thus the table will require searching to the end for an exact `N = 1,000,000` block accesses. It is this situation that indexing aims to correct.
Given that an index record contains only the indexed field and a pointer to the original record, it stands to reason that it will be smaller than the multi-field record that it points to. So the index itself requires fewer disk blocks than the original table, which therefore requires fewer block accesses to iterate through. The schema for an index on the *firstName* field is outlined below;
```
Field name Data type Size on disk
firstName Char(50) 50 bytes
(record pointer) Special 4 bytes
```
**Note**: Pointers in MySQL are 2, 3, 4 or 5 bytes in length depending on the size of the table.
***Example 2*** - *indexing*
Given our sample database of `r = 5,000,000` records with an index record length of `R = 54` bytes and using the default block size `B = 1,024` bytes. The blocking factor of the index would be `bfr = (B/R) = 1024/54 = 18` records per disk block. The total number of blocks required to hold the index is `N = (r/bfr) = 5000000/18 = 277,778` blocks.
Now a search using the *firstName* field can utilize the index to increase performance. This allows for a binary search of the index with an average of `log2 277778 = 18.08 = 19` block accesses. To find the address of the actual record, which requires a further block access to read, bringing the total to `19 + 1 = 20` block accesses, a far cry from the 1,000,000 block accesses required to find a *firstName* match in the non-indexed table.
**When should it be used?**
Given that creating an index requires additional disk space (277,778 blocks extra from the above example, a ~28% increase), and that too many indices can cause issues arising from the file systems size limits, careful thought must be used to select the correct fields to index.
Since indices are only used to speed up the searching for a matching field within the records, it stands to reason that indexing fields used only for output would be simply a waste of disk space and processing time when doing an insert or delete operation, and thus should be avoided. Also given the nature of a binary search, the cardinality or uniqueness of the data is important. Indexing on a field with a cardinality of 2 would split the data in half, whereas a cardinality of 1,000 would return approximately 1,000 records. With such a low cardinality the effectiveness is reduced to a linear sort, and the query optimizer will avoid using the index if the cardinality is less than 30% of the record number, effectively making the index a waste of space. |
1,145 | <p>I've tried to write a string replace function in C, which works on a <code>char *</code>, which has been allocated using <code>malloc()</code>. It's a little different in that it will find and replace strings, rather than characters in the starting string.</p>
<p>It's trivial to do if the search and replace strings are the same length (or the replace string is shorter than the search string), since I have enough space allocated. If I try to use <code>realloc()</code>, I get an error that tells me I am doing a double free - which I don't see how I am, since I am only using <code>realloc()</code>.</p>
<p>Perhaps a little code will help:</p>
<pre><code>void strrep(char *input, char *search, char *replace) {
int searchLen = strlen(search);
int replaceLen = strlen(replace);
int delta = replaceLen - searchLen;
char *find = input;
while (find = strstr(find, search)) {
if (delta > 0) {
realloc(input, strlen(input) + delta);
find = strstr(input, search);
}
memmove(find + replaceLen, find + searchLen, strlen(input) - (find - input));
memmove(find, replace, replaceLen);
}
}
</code></pre>
<p>The program works, until I try to <code>realloc()</code> in an instance where the replaced string will be longer than the initial string. (It still kind of works, it just spits out errors as well as the result).</p>
<p>If it helps, the calling code looks like:</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void strrep(char *input, char *search, char *replace);
int main(void) {
char *input = malloc(81);
while ((fgets(input, 81, stdin)) != NULL) {
strrep(input, "Noel", "Christmas");
}
}
</code></pre>
| [
{
"answer_id": 1149,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 3,
"selected": false,
"text": "<p>Just a shot in the dark because I haven't tried it yet but when you realloc it returns the pointer much like malloc. Because realloc can move the pointer if needed you are most likely operating on an invalid pointer if you don't do the following:</p>\n\n<pre><code>input = realloc(input, strlen(input) + delta);\n</code></pre>\n"
},
{
"answer_id": 1153,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Note, try to edit your code to get rid of the html escape codes.</strong></p>\n\n<p>Well, though it has been a while since I used C/C++, realloc that grows only reuses the memory pointer value if there is room in memory after your original block.</p>\n\n<p>For instance, consider this:</p>\n\n<p>(xxxxxxxxxx..........)</p>\n\n<p>If your pointer points to the first x, and . means free memory location, and you grow the memory size pointed to by your variable by 5 bytes, it'll succeed. This is of course a simplified example as blocks are rounded up to a certain size for alignment, but anyway.</p>\n\n<p>However, if you subsequently try to grow it by another 10 bytes, and there is only 5 available, it will need to move the block in memory and update your pointer.</p>\n\n<p>However, in your example you are passing the function a pointer to the character, not a pointer to your variable, and thus while the strrep function internally might be able to adjust the variable in use, it is a local variable to the strrep function and your calling code will be left with the original pointer variable value.</p>\n\n<p>This pointer value, however, has been freed.</p>\n\n<p>In your case, input is the culprit.</p>\n\n<p>However, I would make another suggestion. In your case it looks like the <em>input</em> variable is indeed input, and if it is, it shouldn't be modified, at all.</p>\n\n<p>I would thus try to find another way to do what you want to do, without changing <em>input</em>, as side-effects like this can be hard to track down.</p>\n"
},
{
"answer_id": 1154,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 5,
"selected": true,
"text": "<p>As a general rule, you should <strong>never</strong> do a free or realloc on a user provided buffer. You don't know where the user allocated the space (in your module, in another DLL) so you cannot use any of the allocation functions on a user buffer.</p>\n\n<p>Provided that you now cannot do any reallocation within your function, you should change its behavior a little, like doing only one replacement, so the user will be able to compute the resulting string max length and provide you with a buffer long enough for this one replacement to occur.</p>\n\n<p>Then you could create another function to do the multiple replacements, but you will have to allocate the whole space for the resulting string and copy the user input string. Then you must provide a way to delete the string you allocated.</p>\n\n<p>Resulting in:</p>\n\n<pre><code>void strrep(char *input, char *search, char *replace);\nchar* strrepm(char *input, char *search, char *replace);\nvoid strrepmfree(char *input);\n</code></pre>\n"
},
{
"answer_id": 1155,
"author": "Piotr Tyburski",
"author_id": 2090742,
"author_profile": "https://Stackoverflow.com/users/2090742",
"pm_score": 0,
"selected": false,
"text": "<p>My quick hints.</p>\n\n<p>Instead of:<br>\n<code>void strrep(char *input, char *search, char *replace)</code><br>\ntry:<br>\n<code>void strrep(char *&input, char *search, char *replace)</code></p>\n\n<p>and than in the body:<br>\n<code>input = realloc(input, strlen(input) + delta);</code></p>\n\n<p>Generally read about passing function arguments as values/reference and realloc() description :).</p>\n"
},
{
"answer_id": 1163,
"author": "Mark",
"author_id": 263,
"author_profile": "https://Stackoverflow.com/users/263",
"pm_score": 2,
"selected": false,
"text": "<p>This seems to work;</p>\n\n<pre><code>char *strrep(char *string, const char *search, const char *replace) {\n char *p = strstr(string, search);\n\n if (p) {\n int occurrence = p - string;\n int stringlength = strlen(string);\n int searchlength = strlen(search);\n int replacelength = strlen(replace);\n\n if (replacelength > searchlength) {\n string = (char *) realloc(string, strlen(string) \n + replacelength - searchlength + 1);\n }\n\n if (replacelength != searchlength) {\n memmove(string + occurrence + replacelength, \n string + occurrence + searchlength, \n stringlength - occurrence - searchlength + 1);\n }\n\n strncpy(string + occurrence, replace, replacelength);\n }\n\n return string;\n}\n</code></pre>\n\n<p>Sigh, is there anyway to post code without it sucking?</p>\n"
},
{
"answer_id": 6405,
"author": "Tryke",
"author_id": 773,
"author_profile": "https://Stackoverflow.com/users/773",
"pm_score": 4,
"selected": false,
"text": "<p>First off, sorry I'm late to the party. This is my first stackoverflow answer. :)</p>\n\n<p>As has been pointed out, when realloc() is called, you can potentially change the pointer to the memory being reallocated. When this happens, the argument \"string\" becomes invalid. Even if you reassign it, the change goes out of scope once the function ends.</p>\n\n<p>To answer the OP, realloc() returns a pointer to the newly-reallocated memory. The return value needs to be stored somewhere. Generally, you would do this:</p>\n\n<pre><code>data *foo = malloc(SIZE * sizeof(data));\ndata *bar = realloc(foo, NEWSIZE * sizeof(data));\n\n/* Test bar for safety before blowing away foo */\nif (bar != NULL)\n{\n foo = bar;\n bar = NULL;\n}\nelse\n{\n fprintf(stderr, \"Crap. Memory error.\\n\");\n free(foo);\n exit(-1);\n}\n</code></pre>\n\n<p>As TyBoer points out, you guys can't change the value of the pointer being passed in as the input to this function. You can assign whatever you want, but the change will go out of scope at the end of the function. In the following block, \"input\" may or may not be an invalid pointer once the function completes:</p>\n\n<pre><code>void foobar(char *input, int newlength)\n{\n /* Here, I ignore my own advice to save space. Check your return values! */\n input = realloc(input, newlength * sizeof(char));\n}\n</code></pre>\n\n<p>Mark tries to work around this by returning the new pointer as the output of the function. If you do that, the onus is on the caller to never again use the pointer he used for input. If it matches the return value, then you have two pointers to the same spot and only need to call free() on one of them. If they don't match, the input pointer now points to memory that may or may not be owned by the process. Dereferencing it could cause a segmentation fault.</p>\n\n<p>You could use a double pointer for the input, like this:</p>\n\n<pre><code>void foobar(char **input, int newlength)\n{\n *input = realloc(*input, newlength * sizeof(char));\n}\n</code></pre>\n\n<p>If the caller has a duplicate of the input pointer somewhere, that duplicate still might be invalid now.</p>\n\n<p>I think the cleanest solution here is to avoid using realloc() when trying to modify the function caller's input. Just malloc() a new buffer, return that, and let the caller decide whether or not to free the old text. This has the added benefit of letting the caller keep the original string!</p>\n"
},
{
"answer_id": 220594,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "<p>Someone else apologized for being late to the party - two and a half months ago. Oh well, I spend quite a lot of time doing software archaeology.</p>\n\n<p>I'm interested that no-one has commented explicitly on the memory leak in the original design, or the off-by-one error. And it was observing the memory leak that tells me exactly why you are getting the double-free error (because, to be precise, you are freeing the same memory multiple times - and you are doing so after trampling over the already freed memory).</p>\n\n<p>Before conducting the analysis, I'll agree with those who say your interface is less than stellar; however, if you dealt with the memory leak/trampling issues and documented the 'must be allocated memory' requirement, it could be 'OK'.</p>\n\n<p>What are the problems? Well, you pass a buffer to realloc(), and realloc() returns you a new pointer to the area you should use - and you ignore that return value. Consequently, realloc() has probably freed the original memory, and then you pass it the same pointer again, and it complains that you're freeing the same memory twice because you pass the original value to it again. This not only leaks memory, but means that you are continuing to use the original space -- and John Downey's shot in the dark points out that you are misusing realloc(), but doesn't emphasize how severely you are doing so. There's also an off-by-one error because you do not allocate enough space for the NUL '\\0' that terminates the string.</p>\n\n<p>The memory leak occurs because you do not provide a mechanism to tell the caller about the last value of the string. Because you kept trampling over the original string plus the space after it, it looks like the code worked, but if your calling code freed the space, it too would get a double-free error, or it might get a core dump or equivalent because the memory control information is completely scrambled.</p>\n\n<p>Your code also doesn't protect against indefinite growth -- consider replacing 'Noel' with 'Joyeux Noel'. Every time, you would add 7 characters, but you'd find another Noel in the replaced text, and expand it, and so on and so forth. My fixup (below) does not address this issue - the simple solution is probably to check whether the search string appears in the replace string; an alternative is to skip over the replace string and continue the search after it. The second has some non-trivial coding issues to address.</p>\n\n<p>So, my suggested revision of your called function is:</p>\n\n<pre><code>char *strrep(char *input, char *search, char *replace) {\n int searchLen = strlen(search);\n int replaceLen = strlen(replace);\n int delta = replaceLen - searchLen;\n char *find = input;\n\n while ((find = strstr(find, search)) != 0) {\n if (delta > 0) {\n input = realloc(input, strlen(input) + delta + 1);\n find = strstr(input, search); \n }\n\n memmove(find + replaceLen, find + searchLen, strlen(input) + 1 - (find - input));\n memmove(find, replace, replaceLen);\n }\n\n return(input);\n}\n</code></pre>\n\n<p>This code does not detect memory allocation errors - and probably crashes (but if not, leaks memory) if realloc() fails. See Steve Maguire's 'Writing Solid Code' book for an extensive discussion of memory management issues.</p>\n"
},
{
"answer_id": 6024343,
"author": "Tom Andersen",
"author_id": 69948,
"author_profile": "https://Stackoverflow.com/users/69948",
"pm_score": 2,
"selected": false,
"text": "<p>realloc is strange, complicated and should only be used when dealing with lots of memory lots of times per second. i.e. - where it actually makes your code faster. </p>\n\n<p>I have seen code where </p>\n\n<pre><code>realloc(bytes, smallerSize);\n</code></pre>\n\n<p>was used and worked to resize the buffer, making it smaller. Worked about a million times, then for some reason realloc decided that even if you were shortening the buffer, it would give you a nice new copy. So you crash in a random place 1/2 a second after the bad stuff happened. </p>\n\n<p>Always use the return value of realloc. </p>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/188/"
] | I've tried to write a string replace function in C, which works on a `char *`, which has been allocated using `malloc()`. It's a little different in that it will find and replace strings, rather than characters in the starting string.
It's trivial to do if the search and replace strings are the same length (or the replace string is shorter than the search string), since I have enough space allocated. If I try to use `realloc()`, I get an error that tells me I am doing a double free - which I don't see how I am, since I am only using `realloc()`.
Perhaps a little code will help:
```
void strrep(char *input, char *search, char *replace) {
int searchLen = strlen(search);
int replaceLen = strlen(replace);
int delta = replaceLen - searchLen;
char *find = input;
while (find = strstr(find, search)) {
if (delta > 0) {
realloc(input, strlen(input) + delta);
find = strstr(input, search);
}
memmove(find + replaceLen, find + searchLen, strlen(input) - (find - input));
memmove(find, replace, replaceLen);
}
}
```
The program works, until I try to `realloc()` in an instance where the replaced string will be longer than the initial string. (It still kind of works, it just spits out errors as well as the result).
If it helps, the calling code looks like:
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void strrep(char *input, char *search, char *replace);
int main(void) {
char *input = malloc(81);
while ((fgets(input, 81, stdin)) != NULL) {
strrep(input, "Noel", "Christmas");
}
}
``` | As a general rule, you should **never** do a free or realloc on a user provided buffer. You don't know where the user allocated the space (in your module, in another DLL) so you cannot use any of the allocation functions on a user buffer.
Provided that you now cannot do any reallocation within your function, you should change its behavior a little, like doing only one replacement, so the user will be able to compute the resulting string max length and provide you with a buffer long enough for this one replacement to occur.
Then you could create another function to do the multiple replacements, but you will have to allocate the whole space for the resulting string and copy the user input string. Then you must provide a way to delete the string you allocated.
Resulting in:
```
void strrep(char *input, char *search, char *replace);
char* strrepm(char *input, char *search, char *replace);
void strrepmfree(char *input);
``` |
1,156 | <p>Hopefully, I can get answers for each database server.</p>
<p>For an outline of how indexing works check out: <a href="https://stackoverflow.com/questions/1108/how-does-database-indexing-work">How does database indexing work?</a></p>
| [
{
"answer_id": 1157,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 7,
"selected": true,
"text": "<p>The following is SQL92 standard so should be supported by the majority of RDMBS that use SQL:</p>\n\n<pre><code>CREATE INDEX [index name] ON [table name] ( [column name] )\n</code></pre>\n"
},
{
"answer_id": 9853,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 3,
"selected": false,
"text": "<p><code>Sql Server 2005</code> gives you the ability to specify a covering index. This is an index that includes data from other columns at the leaf level, so you don't have to go back to the table to get columns that aren't included in the index keys.</p>\n\n<pre><code>create nonclustered index my_idx on my_table (my_col1 asc, my_col2 asc) include (my_col3);\n</code></pre>\n\n<p>This is invaluable for a query that has <code>my_col3</code> in the select list, and <code>my_col1</code> and <code>my_col2</code> in the where clause.</p>\n"
},
{
"answer_id": 8973833,
"author": "tdc",
"author_id": 1038264,
"author_profile": "https://Stackoverflow.com/users/1038264",
"pm_score": 2,
"selected": false,
"text": "<p>For python pytables, indexes don't have names and they are bound to single columns:</p>\n\n<pre><code>tables.columns.column_name.createIndex()\n</code></pre>\n"
},
{
"answer_id": 11055918,
"author": "David Manheim",
"author_id": 1132642,
"author_profile": "https://Stackoverflow.com/users/1132642",
"pm_score": 2,
"selected": false,
"text": "<p>In SQL Server, you can do the following: (<a href=\"http://msdn.microsoft.com/en-us/library/ms188783.aspx\" rel=\"nofollow\">MSDN Link</a> to full list of options.)</p>\n\n<pre><code>CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name \n ON <object> ( column [ ASC | DESC ] [ ,...n ] ) \n [ INCLUDE ( column_name [ ,...n ] ) ]\n [ WHERE <filter_predicate> ]\n</code></pre>\n\n<p>(ignoring some more advanced options...)</p>\n\n<p>The name of each Index must be unique database wide.</p>\n\n<p>All indexes can have multiple columns, and each column can be ordered in whatever order you want.</p>\n\n<p>Clustered indexes are unique - one per table. They can't have <code>INCLUDE</code>d columns.</p>\n\n<p>Nonclustered indexes are not unique, and can have up to 999 per table. They can have included columns, and where clauses.</p>\n"
},
{
"answer_id": 30597765,
"author": "Sharvari",
"author_id": 4010493,
"author_profile": "https://Stackoverflow.com/users/4010493",
"pm_score": 2,
"selected": false,
"text": "<p>To create indexes following stuff can be used:</p>\n\n<ol>\n<li><p>Creates an index on a table. Duplicate values are allowed:\n<code>CREATE INDEX index_name\nON table_name (column_name)</code></p></li>\n<li><p>Creates a unique index on a table. Duplicate values are not allowed:\n<code>CREATE UNIQUE INDEX index_name ON table_name (column_name)</code></p></li>\n<li><p>Clustered Index: <code>CREATE CLUSTERED INDEX CL_ID ON SALES(ID);</code></p></li>\n<li>Non-clustered index:<br>\n<code>CREATE NONCLUSTERED INDEX NONCI_PC ON SALES(ProductCode);</code></li>\n</ol>\n\n<p>Refer: <a href=\"http://www.codeproject.com/Articles/190263/Indexes-in-MS-SQL-Server\" rel=\"nofollow noreferrer\">http://www.codeproject.com/Articles/190263/Indexes-in-MS-SQL-Server</a> for details.</p>\n"
},
{
"answer_id": 41695102,
"author": "Looking_for_answers",
"author_id": 6920172,
"author_profile": "https://Stackoverflow.com/users/6920172",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li><p><code>CREATE INDEX name_index ON Employee (Employee_Name)</code></p></li>\n<li><p>On a multi column: <code>CREATE INDEX name_index ON Employee (Employee_Name, Employee_Age)</code></p></li>\n</ol>\n"
},
{
"answer_id": 50649693,
"author": "mdeora",
"author_id": 1269201,
"author_profile": "https://Stackoverflow.com/users/1269201",
"pm_score": 0,
"selected": false,
"text": "<p>Since most of the answers are given for SQL databases, I am writing this for NOSQL databases, specifically for MongoDB.</p>\n\n<p>Below is the syntax to create an index in the MongoDB using mongo shell.</p>\n\n<pre><code>db.collection.createIndex( <key and index type specification>, <options> )\n</code></pre>\n\n<p>example - <code>db.collection.createIndex( { name: -1 } )</code></p>\n\n<p>In the above example an single key descending index is created on the name \nfield. </p>\n\n<p>Keep in mind MongoDB indexes uses B-tree data structure.</p>\n\n<p>There are multiple types of indexes we can create in mongodb, for more information refer to below link - <a href=\"https://docs.mongodb.com/manual/indexes/\" rel=\"nofollow noreferrer\">https://docs.mongodb.com/manual/indexes/</a></p>\n"
},
{
"answer_id": 50697793,
"author": "SriniV",
"author_id": 2772061,
"author_profile": "https://Stackoverflow.com/users/2772061",
"pm_score": 0,
"selected": false,
"text": "<p>An index is not always needed for all the databases. For eg: Kognitio aka WX2 engine doesn't offer a syntax for indexing as the database engine takes care of it implicitly. Data goes on via round-robin partitioning and Kognitio WX2 gets data on and off disk in the simplest possible way.</p>\n"
},
{
"answer_id": 57400894,
"author": "krishna kirti",
"author_id": 2826658,
"author_profile": "https://Stackoverflow.com/users/2826658",
"pm_score": 0,
"selected": false,
"text": "<p>We can use following syntax to create index.</p>\n\n<pre><code>CREATE INDEX <index_name> ON <table_name>(<column_name>)\n</code></pre>\n\n<p>If we do not want duplicate value to be allowed then we can add <strong>UNIQUE</strong> while creating index as follow </p>\n\n<pre><code>CREATE UNIQUE INDEX <index_name> ON <table_name>(<column_name>)\n</code></pre>\n\n<p>We can create index on multiple column by giving multiple column name separated by '<strong>,</strong>'</p>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264/"
] | Hopefully, I can get answers for each database server.
For an outline of how indexing works check out: [How does database indexing work?](https://stackoverflow.com/questions/1108/how-does-database-indexing-work) | The following is SQL92 standard so should be supported by the majority of RDMBS that use SQL:
```
CREATE INDEX [index name] ON [table name] ( [column name] )
``` |
1,160 | <p>I am using CCNET on a sample project with SVN as my source control. CCNET is configured to create a build on every check in. CCNET uses MSBuild to build the source code.</p>
<p>I would like to use the latest revision number to generate <code>AssemblyInfo.cs</code> while compiling.
How can I retrieve the latest revision from subversion and use the value in CCNET?</p>
<p>Edit: I'm not using NAnt - only MSBuild.</p>
| [
{
"answer_id": 1164,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 2,
"selected": false,
"text": "<p>I am currently \"manually\" doing it through a prebuild-exec Task, using my <a href=\"http://www.stum.de/various-tools/cmdtools/\" rel=\"nofollow noreferrer\">cmdnetsvnrev</a> tool, but if someone knows a better ccnet-integrated way of doing it, i'd be happy to hear :-)</p>\n"
},
{
"answer_id": 1168,
"author": "hitec",
"author_id": 120,
"author_profile": "https://Stackoverflow.com/users/120",
"pm_score": 2,
"selected": false,
"text": "<p>I found <a href=\"http://code.google.com/p/svnrevisionlabeller\" rel=\"nofollow noreferrer\">this</a> project on google code. This is <code>CCNET</code> plugin to generate the label in <code>CCNET</code>.</p>\n\n<p>The <code>DLL</code> is tested with <code>CCNET 1.3</code> but it works with <code>CCNET 1.4</code> for me. I'm successfully using this plugin to label my build.</p>\n\n<p>Now onto passing it to <code>MSBuild</code>...</p>\n"
},
{
"answer_id": 1169,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 4,
"selected": false,
"text": "<p>You have basically two options. Either you write a simple script that will start and parse output from</p>\n\n<p><strong>svn.exe info --revision HEAD</strong></p>\n\n<p>to obtain revision number (then generating AssemblyInfo.cs is pretty much straight forward) or just use plugin for CCNET. Here it is:</p>\n\n<blockquote>\n <p><strong>SVN Revision Labeller</strong> is a plugin for\n CruiseControl.NET that allows you to\n generate CruiseControl labels for your\n builds, based upon the revision number\n of your Subversion working copy. This\n can be customised with a prefix and/or\n major/minor version numbers.</p>\n \n <p><a href=\"http://code.google.com/p/svnrevisionlabeller/\" rel=\"nofollow noreferrer\">http://code.google.com/p/svnrevisionlabeller/</a></p>\n</blockquote>\n\n<p>I prefer the first option because it's only roughly 20 lines of code:</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\n\nnamespace SvnRevisionNumberParserSample\n{\n class Program\n {\n static void Main()\n {\n Process p = Process.Start(new ProcessStartInfo()\n {\n FileName = @\"C:\\Program Files\\SlikSvn\\bin\\svn.exe\", // path to your svn.exe\n UseShellExecute = false,\n RedirectStandardOutput = true,\n Arguments = \"info --revision HEAD\",\n WorkingDirectory = @\"C:\\MyProject\" // path to your svn working copy\n });\n\n // command \"svn.exe info --revision HEAD\" will produce a few lines of output\n p.WaitForExit();\n\n // our line starts with \"Revision: \"\n while (!p.StandardOutput.EndOfStream)\n {\n string line = p.StandardOutput.ReadLine();\n if (line.StartsWith(\"Revision: \"))\n {\n string revision = line.Substring(\"Revision: \".Length);\n Console.WriteLine(revision); // show revision number on screen \n break;\n }\n }\n\n Console.Read();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1172,
"author": "Rytmis",
"author_id": 266,
"author_profile": "https://Stackoverflow.com/users/266",
"pm_score": 2,
"selected": false,
"text": "<p>If you prefer doing it on the <code>MSBuild</code> side over the <code>CCNet</code> config, looks like the <code>MSBuild</code> Community Tasks extension's <a href=\"http://msbuildtasks.tigris.org/\" rel=\"nofollow noreferrer\"><code>SvnVersion</code></a> task might do the trick.</p>\n"
},
{
"answer_id": 1216,
"author": "hitec",
"author_id": 120,
"author_profile": "https://Stackoverflow.com/users/120",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p><strong>Customizing csproj files to autogenerate AssemblyInfo.cs</strong><br>\n <a href=\"http://www.codeproject.com/KB/dotnet/Customizing_csproj_files.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/dotnet/Customizing_csproj_files.aspx</a></p>\n \n <p>Every time we create a new C# project,\n Visual Studio puts there the\n AssemblyInfo.cs file for us. The file\n defines the assembly meta-data like\n its version, configuration, or\n producer.</p>\n</blockquote>\n\n<p>Found the above technique to auto-gen AssemblyInfo.cs using MSBuild. Will post sample shortly.</p>\n"
},
{
"answer_id": 1235,
"author": "Justin Walgran",
"author_id": 173,
"author_profile": "https://Stackoverflow.com/users/173",
"pm_score": 2,
"selected": false,
"text": "<p>I have written a NAnt build file that handles parsing SVN information and creating properties. I then use those property values for a variety of build tasks, including setting the label on the build. I use this target combined with the SVN Revision Labeller mentioned by lubos hasko with great results.</p>\n\n<pre><code><target name=\"svninfo\" description=\"get the svn checkout information\">\n <property name=\"svn.infotempfile\" value=\"${build.directory}\\svninfo.txt\" />\n <exec program=\"${svn.executable}\" output=\"${svn.infotempfile}\">\n <arg value=\"info\" />\n </exec>\n <loadfile file=\"${svn.infotempfile}\" property=\"svn.info\" />\n <delete file=\"${svn.infotempfile}\" />\n\n <property name=\"match\" value=\"\" />\n\n <regex pattern=\"URL: (?'match'.*)\" input=\"${svn.info}\" />\n <property name=\"svn.info.url\" value=\"${match}\"/>\n\n <regex pattern=\"Repository Root: (?'match'.*)\" input=\"${svn.info}\" />\n <property name=\"svn.info.repositoryroot\" value=\"${match}\"/>\n\n <regex pattern=\"Revision: (?'match'\\d+)\" input=\"${svn.info}\" />\n <property name=\"svn.info.revision\" value=\"${match}\"/>\n\n <regex pattern=\"Last Changed Author: (?'match'\\w+)\" input=\"${svn.info}\" />\n <property name=\"svn.info.lastchangedauthor\" value=\"${match}\"/>\n\n <echo message=\"URL: ${svn.info.url}\" />\n <echo message=\"Repository Root: ${svn.info.repositoryroot}\" />\n <echo message=\"Revision: ${svn.info.revision}\" />\n <echo message=\"Last Changed Author: ${svn.info.lastchangedauthor}\" />\n</target>\n</code></pre>\n"
},
{
"answer_id": 505990,
"author": "R. Martinho Fernandes",
"author_id": 46642,
"author_profile": "https://Stackoverflow.com/users/46642",
"pm_score": 2,
"selected": false,
"text": "<p>My approach is to use the aforementioned plugin for ccnet and a nant echo task to generate a <code>VersionInfo.cs</code> file containing nothing but the version attributes. I only have to include the <code>VersionInfo.cs</code> file into the build</p>\n\n<p>The echo task simply outputs the string I give it to a file.</p>\n\n<p>If there is a similar MSBuild task, you can use the same approach. Here's the small nant task I use:</p>\n\n<pre><code><target name=\"version\" description=\"outputs version number to VersionInfo.cs\">\n <echo file=\"${projectdir}/Properties/VersionInfo.cs\">\n [assembly: System.Reflection.AssemblyVersion(\"$(CCNetLabel)\")]\n [assembly: System.Reflection.AssemblyFileVersion(\"$(CCNetLabel)\")]\n </echo>\n</target>\n</code></pre>\n\n<p>Try this:</p>\n\n<pre><code><ItemGroup>\n <VersionInfoFile Include=\"VersionInfo.cs\"/>\n <VersionAttributes>\n [assembly: System.Reflection.AssemblyVersion(\"${CCNetLabel}\")]\n [assembly: System.Reflection.AssemblyFileVersion(\"${CCNetLabel}\")]\n </VersionAttributes>\n</ItemGroup>\n<Target Name=\"WriteToFile\">\n <WriteLinesToFile\n File=\"@(VersionInfoFile)\"\n Lines=\"@(VersionAttributes)\"\n Overwrite=\"true\"/>\n</Target>\n</code></pre>\n\n<p>Please note that I'm not very intimate with MSBuild, so my script will probably not work out-of-the-box and need corrections...</p>\n"
},
{
"answer_id": 508342,
"author": "Dan",
"author_id": 54852,
"author_profile": "https://Stackoverflow.com/users/54852",
"pm_score": 1,
"selected": false,
"text": "<p>Be careful. The structure used for build numbers is only a short so you have a ceiling on how high your revision can go.</p>\n\n<p>In our case, we've already exceeded the limit.</p>\n\n<p>If you attempt to put in the build number 99.99.99.599999, the file version property will actually come out as 99.99.99.10175.</p>\n"
},
{
"answer_id": 975299,
"author": "skolima",
"author_id": 3205,
"author_profile": "https://Stackoverflow.com/users/3205",
"pm_score": 7,
"selected": true,
"text": "<p>CruiseControl.Net 1.4.4 has now an <a href=\"http://confluence.public.thoughtworks.org/display/CCNET/Assembly+Version+Labeller\" rel=\"noreferrer\">Assembly Version Labeller</a>, which generates version numbers compatible with .Net assembly properties.</p>\n\n<p>In my project I have it configured as:</p>\n\n<pre><code><labeller type=\"assemblyVersionLabeller\" incrementOnFailure=\"true\" major=\"1\" minor=\"2\"/>\n</code></pre>\n\n<p>(Caveat: <code>assemblyVersionLabeller</code> won't start generating svn revision based labels until an actual commit-triggered build occurs.)</p>\n\n<p>and then consume this from my MSBuild projects with <a href=\"http://msbuildtasks.tigris.org/\" rel=\"noreferrer\">MSBuildCommunityTasks.AssemblyInfo</a> :</p>\n\n<pre><code><Import Project=\"$(MSBuildExtensionsPath)\\MSBuildCommunityTasks\\MSBuild.Community.Tasks.Targets\"/>\n<Target Name=\"BeforeBuild\">\n <AssemblyInfo Condition=\"'$(CCNetLabel)' != ''\" CodeLanguage=\"CS\" OutputFile=\"Properties\\AssemblyInfo.cs\" \n AssemblyTitle=\"MyTitle\" AssemblyCompany=\"MyCompany\" AssemblyProduct=\"MyProduct\"\n AssemblyCopyright=\"Copyright © 2009\" ComVisible=\"false\" Guid=\"some-random-guid\"\n AssemblyVersion=\"$(CCNetLabel)\" AssemblyFileVersion=\"$(CCNetLabel)\"/>\n</Target>\n</code></pre>\n\n<p>For sake of completness, it's just as easy for projects using NAnt instead of MSBuild:</p>\n\n<pre><code><target name=\"setversion\" description=\"Sets the version number to CruiseControl.Net label.\">\n <script language=\"C#\">\n <references>\n <include name=\"System.dll\" />\n </references>\n <imports>\n <import namespace=\"System.Text.RegularExpressions\" />\n </imports>\n <code><![CDATA[\n [TaskName(\"setversion-task\")]\n public class SetVersionTask : Task\n {\n protected override void ExecuteTask()\n {\n StreamReader reader = new StreamReader(Project.Properties[\"filename\"]);\n string contents = reader.ReadToEnd();\n reader.Close();\n string replacement = \"[assembly: AssemblyVersion(\\\"\" + Project.Properties[\"CCNetLabel\"] + \"\\\")]\";\n string newText = Regex.Replace(contents, @\"\\[assembly: AssemblyVersion\\(\"\".*\"\"\\)\\]\", replacement);\n StreamWriter writer = new StreamWriter(Project.Properties[\"filename\"], false);\n writer.Write(newText);\n writer.Close();\n }\n }\n ]]>\n </code>\n </script>\n <foreach item=\"File\" property=\"filename\">\n <in>\n <items basedir=\"..\">\n <include name=\"**\\AssemblyInfo.cs\"></include>\n </items>\n </in>\n <do>\n <setversion-task />\n </do>\n </foreach>\n</target>\n</code></pre>\n"
},
{
"answer_id": 1414774,
"author": "galaktor",
"author_id": 140607,
"author_profile": "https://Stackoverflow.com/users/140607",
"pm_score": 2,
"selected": false,
"text": "<p>Based on skolimas solution I updated the NAnt script to also update the AssemblyFileVersion. Thanks to skolima for the code!</p>\n\n<pre><code><target name=\"setversion\" description=\"Sets the version number to current label.\">\n <script language=\"C#\">\n <references>\n <include name=\"System.dll\" />\n </references>\n <imports>\n <import namespace=\"System.Text.RegularExpressions\" />\n </imports>\n <code><![CDATA[\n [TaskName(\"setversion-task\")]\n public class SetVersionTask : Task\n {\n protected override void ExecuteTask()\n {\n StreamReader reader = new StreamReader(Project.Properties[\"filename\"]);\n string contents = reader.ReadToEnd();\n reader.Close(); \n // replace assembly version\n string replacement = \"[assembly: AssemblyVersion(\\\"\" + Project.Properties[\"label\"] + \"\\\")]\";\n contents = Regex.Replace(contents, @\"\\[assembly: AssemblyVersion\\(\"\".*\"\"\\)\\]\", replacement); \n // replace assembly file version\n replacement = \"[assembly: AssemblyFileVersion(\\\"\" + Project.Properties[\"label\"] + \"\\\")]\";\n contents = Regex.Replace(contents, @\"\\[assembly: AssemblyFileVersion\\(\"\".*\"\"\\)\\]\", replacement); \n StreamWriter writer = new StreamWriter(Project.Properties[\"filename\"], false);\n writer.Write(contents);\n writer.Close();\n }\n }\n ]]>\n </code>\n </script>\n <foreach item=\"File\" property=\"filename\">\n <in>\n <items basedir=\"${srcDir}\">\n <include name=\"**\\AssemblyInfo.cs\"></include>\n </items>\n </in>\n <do>\n <setversion-task />\n </do>\n </foreach>\n </target>\n</code></pre>\n"
},
{
"answer_id": 2619371,
"author": "grimus",
"author_id": 74346,
"author_profile": "https://Stackoverflow.com/users/74346",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure if this work with CCNET or not, but I've created an <a href=\"http://happyturtle.codeplex.com/\" rel=\"nofollow noreferrer\">SVN version plug-in</a> for the <a href=\"http://autobuildversion.codeplex.com/\" rel=\"nofollow noreferrer\">Build Version Increment</a> project on CodePlex. This tool is pretty flexible and can be set to automatically create a version number for you using the svn revision. It doesn't require writing any code or editing xml, so yay!</p>\n\n<p>I hope this is helps!</p>\n"
},
{
"answer_id": 12481921,
"author": "granadaCoder",
"author_id": 214977,
"author_profile": "https://Stackoverflow.com/users/214977",
"pm_score": 2,
"selected": false,
"text": "<p>No idea where I found this. But I found this on the internet \"somewhere\".</p>\n\n<p>This updates all the AssemblyInfo.cs files before the build takes place.</p>\n\n<p>Works like a charm. All my exe's and dll's show up as 1.2.3.333 (If \"333\" were the SVN revision at the time.) (And the original version in the AssemblyInfo.cs file was listed as \"1.2.3.0\")</p>\n\n<hr>\n\n<p>$(ProjectDir) (Where my .sln file resides)</p>\n\n<p>$(SVNToolPath) (points to svn.exe)</p>\n\n<p>are my custom variables, their declarations/definitions are not defined below.</p>\n\n<hr>\n\n<p><a href=\"http://msbuildtasks.tigris.org/\" rel=\"nofollow noreferrer\">http://msbuildtasks.tigris.org/</a>\nand/or\n<a href=\"https://github.com/loresoft/msbuildtasks\" rel=\"nofollow noreferrer\">https://github.com/loresoft/msbuildtasks</a>\nhas the ( FileUpdate and SvnVersion ) tasks.</p>\n\n<hr>\n\n<pre><code> <Target Name=\"SubVersionBeforeBuildVersionTagItUp\">\n\n <ItemGroup>\n <AssemblyInfoFiles Include=\"$(ProjectDir)\\**\\*AssemblyInfo.cs\" />\n </ItemGroup>\n\n <SvnVersion LocalPath=\"$(MSBuildProjectDirectory)\" ToolPath=\"$(SVNToolPath)\">\n <Output TaskParameter=\"Revision\" PropertyName=\"MySubVersionRevision\" />\n </SvnVersion>\n\n <FileUpdate Files=\"@(AssemblyInfoFiles)\"\n Regex=\"(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\"\n ReplacementText=\"$1.$2.$3.$(MySubVersionRevision)\" />\n </Target>\n</code></pre>\n\n<p>EDIT --------------------------------------------------</p>\n\n<p>The above may start failing after your SVN revision number reaches 65534 or higher.</p>\n\n<p>See:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/13414409/turn-off-warning-cs1607/13751833#13751833\">Turn off warning CS1607</a></p>\n\n<p>Here is the workaround.</p>\n\n<pre><code><FileUpdate Files=\"@(AssemblyInfoFiles)\"\nRegex=\"AssemblyFileVersion\\(&quot;(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\"\nReplacementText=\"AssemblyFileVersion(&quot;$1.$2.$3.$(SubVersionRevision)\" />\n</code></pre>\n\n<p>The result of this should be:</p>\n\n<p>In Windows/Explorer//File/Properties…….</p>\n\n<p>Assembly Version will be 1.0.0.0. </p>\n\n<p>File Version will be 1.0.0.333 if 333 is the SVN revision.</p>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/120/"
] | I am using CCNET on a sample project with SVN as my source control. CCNET is configured to create a build on every check in. CCNET uses MSBuild to build the source code.
I would like to use the latest revision number to generate `AssemblyInfo.cs` while compiling.
How can I retrieve the latest revision from subversion and use the value in CCNET?
Edit: I'm not using NAnt - only MSBuild. | CruiseControl.Net 1.4.4 has now an [Assembly Version Labeller](http://confluence.public.thoughtworks.org/display/CCNET/Assembly+Version+Labeller), which generates version numbers compatible with .Net assembly properties.
In my project I have it configured as:
```
<labeller type="assemblyVersionLabeller" incrementOnFailure="true" major="1" minor="2"/>
```
(Caveat: `assemblyVersionLabeller` won't start generating svn revision based labels until an actual commit-triggered build occurs.)
and then consume this from my MSBuild projects with [MSBuildCommunityTasks.AssemblyInfo](http://msbuildtasks.tigris.org/) :
```
<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
<Target Name="BeforeBuild">
<AssemblyInfo Condition="'$(CCNetLabel)' != ''" CodeLanguage="CS" OutputFile="Properties\AssemblyInfo.cs"
AssemblyTitle="MyTitle" AssemblyCompany="MyCompany" AssemblyProduct="MyProduct"
AssemblyCopyright="Copyright © 2009" ComVisible="false" Guid="some-random-guid"
AssemblyVersion="$(CCNetLabel)" AssemblyFileVersion="$(CCNetLabel)"/>
</Target>
```
For sake of completness, it's just as easy for projects using NAnt instead of MSBuild:
```
<target name="setversion" description="Sets the version number to CruiseControl.Net label.">
<script language="C#">
<references>
<include name="System.dll" />
</references>
<imports>
<import namespace="System.Text.RegularExpressions" />
</imports>
<code><![CDATA[
[TaskName("setversion-task")]
public class SetVersionTask : Task
{
protected override void ExecuteTask()
{
StreamReader reader = new StreamReader(Project.Properties["filename"]);
string contents = reader.ReadToEnd();
reader.Close();
string replacement = "[assembly: AssemblyVersion(\"" + Project.Properties["CCNetLabel"] + "\")]";
string newText = Regex.Replace(contents, @"\[assembly: AssemblyVersion\("".*""\)\]", replacement);
StreamWriter writer = new StreamWriter(Project.Properties["filename"], false);
writer.Write(newText);
writer.Close();
}
}
]]>
</code>
</script>
<foreach item="File" property="filename">
<in>
<items basedir="..">
<include name="**\AssemblyInfo.cs"></include>
</items>
</in>
<do>
<setversion-task />
</do>
</foreach>
</target>
``` |
1,171 | <p>I need to be able to manipulate a large (10^7 nodes) graph in python. The data corresponding to each node/edge is minimal, say, a small number of strings. What is the most efficient, in terms of <strong><em>memory and speed</em></strong>, way of doing this? </p>
<p>A dict of dicts is more flexible and simpler to implement, but I intuitively expect a list of lists to be faster. The list option would also require that I keep the data separate from the structure, while dicts would allow for something of the sort:</p>
<pre><code>graph[I][J]["Property"]="value"
</code></pre>
<p>What would you suggest?</p>
<hr>
<p>Yes, I should have been a bit clearer on what I mean by efficiency. In this particular case I mean it in terms of random access retrieval.</p>
<p>Loading the data in to memory isn't a huge problem. That's done once and for all. The time consuming part is visiting the nodes so I can extract the information and measure the metrics I'm interested in.</p>
<p>I hadn't considered making each node a class (properties are the same for all nodes) but it seems like that would add an extra layer of overhead? I was hoping someone would have some direct experience with a similar case that they could share. After all, graphs are one of the most common abstractions in CS.</p>
| [
{
"answer_id": 1174,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p>A dictionary may also contain overhead, depending on the actual implementation. A hashtable usually contain some prime number of available nodes to begin with, even though you might only use a couple of the nodes.</p>\n\n<p>Judging by your example, \"Property\", would you be better of with a class approach for the final level and real properties? Or is the names of the properties changing a lot from node to node?</p>\n\n<p>I'd say that what \"efficient\" means depends on a lot of things, like:</p>\n\n<ul>\n<li>speed of updates (insert, update, delete)</li>\n<li>speed of random access retrieval</li>\n<li>speed of sequential retrieval</li>\n<li>memory used</li>\n</ul>\n\n<p>I think that you'll find that a data structure that is speedy will generally consume more memory than one that is slow. This isn't always the case, but most data structures seems to follow this.</p>\n\n<p>A dictionary might be easy to use, and give you relatively uniformly fast access, it will most likely use more memory than, as you suggest, lists. Lists, however, generally tend to contain more overhead when you insert data into it, unless they preallocate X nodes, in which they will again use more memory.</p>\n\n<p>My suggestion, in general, would be to just use the method that seems the most natural to you, and then do a \"stress test\" of the system, adding a substantial amount of data to it and see if it becomes a problem.</p>\n\n<p>You might also consider adding a layer of abstraction to your system, so that you don't have to change the programming interface if you later on need to change the internal data structure.</p>\n"
},
{
"answer_id": 1191,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 2,
"selected": false,
"text": "<p>Making a class-based structure would probably have more overhead than the dict-based structure, since in python classes actually use dicts when they are implemented.</p>\n"
},
{
"answer_id": 3107,
"author": "Peter Burns",
"author_id": 101,
"author_profile": "https://Stackoverflow.com/users/101",
"pm_score": 2,
"selected": false,
"text": "<p>As I understand it, random access is in constant time for both Python's dicts and lists, the difference is that you can only do random access of integer indexes with lists. I'm assuming that you need to lookup a node by its label, so you want a dict of dicts.</p>\n\n<p>However, on the performance front, loading it into memory may not be a problem, but if you use too much you'll end up swapping to disk, which will kill the performance of even Python's highly efficient dicts. Try to keep memory usage down as much as possible. Also, RAM is amazingly cheap right now; if you do this kind of thing a lot, there's no reason not to have at least 4GB.</p>\n\n<p>If you'd like advice on keeping memory usage down, give some more information about the kind of information you're tracking for each node.</p>\n"
},
{
"answer_id": 28705,
"author": "Ryan Cox",
"author_id": 620,
"author_profile": "https://Stackoverflow.com/users/620",
"pm_score": 7,
"selected": true,
"text": "<p>I would strongly advocate you look at <a href=\"http://networkx.github.com/\" rel=\"noreferrer\">NetworkX</a>. It's a battle-tested war horse and the first tool most 'research' types reach for when they need to do analysis of network based data. I have manipulated graphs with 100s of thousands of edges without problem on a notebook. Its feature rich and very easy to use. You will find yourself focusing more on the problem at hand rather than the details in the underlying implementation.</p>\n\n<p><strong>Example of <a href=\"http://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93R%C3%A9nyi_model\" rel=\"noreferrer\">Erdős-Rényi</a> random graph generation and analysis</strong></p>\n\n<pre><code>\n\"\"\"\nCreate an G{n,m} random graph with n nodes and m edges\nand report some properties.\n\nThis graph is sometimes called the Erd##[m~Qs-Rényi graph\nbut is different from G{n,p} or binomial_graph which is also\nsometimes called the Erd##[m~Qs-Rényi graph.\n\"\"\"\n__author__ = \"\"\"Aric Hagberg (hagberg@lanl.gov)\"\"\"\n__credits__ = \"\"\"\"\"\"\n# Copyright (C) 2004-2006 by \n# Aric Hagberg \n# Dan Schult \n# Pieter Swart \n# Distributed under the terms of the GNU Lesser General Public License\n# http://www.gnu.org/copyleft/lesser.html\n\nfrom networkx import *\nimport sys\n\nn=10 # 10 nodes\nm=20 # 20 edges\n\nG=gnm_random_graph(n,m)\n\n# some properties\nprint \"node degree clustering\"\nfor v in nodes(G):\n print v,degree(G,v),clustering(G,v)\n\n# print the adjacency list to terminal \nwrite_adjlist(G,sys.stdout)\n</code></pre>\n\n<p>Visualizations are also straightforward:</p>\n\n<p><img src=\"https://i.stack.imgur.com/5biM9.jpg\" alt=\"enter image description here\"></p>\n\n<p>More visualization: <a href=\"http://jonschull.blogspot.com/2008/08/graph-visualization.html\" rel=\"noreferrer\">http://jonschull.blogspot.com/2008/08/graph-visualization.html</a></p>\n"
},
{
"answer_id": 29836,
"author": "Kai",
"author_id": 2963,
"author_profile": "https://Stackoverflow.com/users/2963",
"pm_score": 3,
"selected": false,
"text": "<p>As already mentioned, NetworkX is very good, with another option being <a href=\"http://cneurocvs.rmki.kfki.hu/igraph/\" rel=\"noreferrer\">igraph</a>. Both modules will have most (if not all) the analysis tools you're likely to need, and both libraries are routinely used with large networks.</p>\n"
},
{
"answer_id": 4292022,
"author": "Tiago Peixoto",
"author_id": 180962,
"author_profile": "https://Stackoverflow.com/users/180962",
"pm_score": 4,
"selected": false,
"text": "<p>Even though this question is now quite old, I think it is worthwhile to mention my own python module for graph manipulation called <a href=\"http://graph-tool.skewed.de\" rel=\"noreferrer\">graph-tool</a>. It is very efficient, since the data structures and algorithms are implemented in C++, with template metaprograming, using the Boost Graph Library. Therefore its performance (both in memory usage and runtime) is comparable to a pure C++ library, and can be orders of magnitude better than typical python code, without sacrificing ease of use. I use it myself constantly to work with very large graphs.</p>\n"
},
{
"answer_id": 34850877,
"author": "Pranav Waila",
"author_id": 2639344,
"author_profile": "https://Stackoverflow.com/users/2639344",
"pm_score": 1,
"selected": false,
"text": "<p>No doubt NetworkX is the best data structure till now for graph. It comes with utilities like Helper Functions, Data Structures and Algorithms, Random Sequence Generators, Decorators, Cuthill-Mckee Ordering, Context Managers</p>\n\n<p>NetworkX is great because it wowrs for graphs, digraphs, and multigraphs. It can write graph with multiple ways: Adjacency List, Multiline Adjacency List,\nEdge List, GEXF, GML. It works with Pickle, GraphML, JSON, SparseGraph6 etc. </p>\n\n<p>It has implimentation of various radimade algorithms including:\nApproximation, Bipartite, Boundary, Centrality, Clique, Clustering, Coloring, Components, Connectivity, Cycles, Directed Acyclic Graphs,\nDistance Measures, Dominating Sets, Eulerian, Isomorphism, Link Analysis, Link Prediction, Matching, Minimum Spanning Tree, Rich Club, Shortest Paths, Traversal, Tree.</p>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/280/"
] | I need to be able to manipulate a large (10^7 nodes) graph in python. The data corresponding to each node/edge is minimal, say, a small number of strings. What is the most efficient, in terms of ***memory and speed***, way of doing this?
A dict of dicts is more flexible and simpler to implement, but I intuitively expect a list of lists to be faster. The list option would also require that I keep the data separate from the structure, while dicts would allow for something of the sort:
```
graph[I][J]["Property"]="value"
```
What would you suggest?
---
Yes, I should have been a bit clearer on what I mean by efficiency. In this particular case I mean it in terms of random access retrieval.
Loading the data in to memory isn't a huge problem. That's done once and for all. The time consuming part is visiting the nodes so I can extract the information and measure the metrics I'm interested in.
I hadn't considered making each node a class (properties are the same for all nodes) but it seems like that would add an extra layer of overhead? I was hoping someone would have some direct experience with a similar case that they could share. After all, graphs are one of the most common abstractions in CS. | I would strongly advocate you look at [NetworkX](http://networkx.github.com/). It's a battle-tested war horse and the first tool most 'research' types reach for when they need to do analysis of network based data. I have manipulated graphs with 100s of thousands of edges without problem on a notebook. Its feature rich and very easy to use. You will find yourself focusing more on the problem at hand rather than the details in the underlying implementation.
**Example of [Erdős-Rényi](http://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93R%C3%A9nyi_model) random graph generation and analysis**
```
"""
Create an G{n,m} random graph with n nodes and m edges
and report some properties.
This graph is sometimes called the Erd##[m~Qs-Rényi graph
but is different from G{n,p} or binomial_graph which is also
sometimes called the Erd##[m~Qs-Rényi graph.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__credits__ = """"""
# Copyright (C) 2004-2006 by
# Aric Hagberg
# Dan Schult
# Pieter Swart
# Distributed under the terms of the GNU Lesser General Public License
# http://www.gnu.org/copyleft/lesser.html
from networkx import *
import sys
n=10 # 10 nodes
m=20 # 20 edges
G=gnm_random_graph(n,m)
# some properties
print "node degree clustering"
for v in nodes(G):
print v,degree(G,v),clustering(G,v)
# print the adjacency list to terminal
write_adjlist(G,sys.stdout)
```
Visualizations are also straightforward:
![enter image description here](https://i.stack.imgur.com/5biM9.jpg)
More visualization: <http://jonschull.blogspot.com/2008/08/graph-visualization.html> |
1,180 | <p>I am looking to allow users to control of subdomain of an app I am toying with, much like Basecamp where it is <code>customusername.seework.com</code>.</p>
<p>What is required on the <code>DNS</code> end to allow these to be created dynamically and be available instantly. </p>
<p>And how do you recommend dealing with this in the logic of the site? <code>Htaccess</code> rule to lookup the subdomain in the <code>DB</code>?</p>
| [
{
"answer_id": 1185,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 2,
"selected": false,
"text": "<p>The trick to that is to use URL rewriting so that <strong>name.domain.com</strong> transparently maps to something like <strong>domain.com/users/name</strong> on your server. Once you start down that path, it's fairly trivial to implement.</p>\n"
},
{
"answer_id": 1187,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Don't worry about DNS and URL rewriting</strong></p>\n\n<p>Your DNS record will be static, something like:</p>\n\n<pre><code>*.YOURDOMAIN.COM A 123.123.123.123\n</code></pre>\n\n<p>Ask your DNS provider to do it for you (if it's not done already) or do it by yourself if you have control over your DNS records. This will automatically point all your subdomains (current and future ones) into the same HTTP server.</p>\n\n<p>Once it's done, you will only need to parse HOST header on every single http request to detect what hostname was used to access your server-side scripts on your http server.</p>\n\n<p>Assuming you're using ASP.NET, this is kind of silly example I came up with but works and demonstrates simplicity of this approach:</p>\n\n<pre><code><%@ Language=\"C#\" %>\n<%\nstring subDomain = Request.Url.Host.Split('.')[0].ToUpper();\nif (subDomain == \"CLIENTXXX\") Response.Write(\"Hello CLIENTXXX, your secret number is 33\");\nelse if (subDomain == \"CLIENTYYY\") Response.Write(\"Hello CLIENTYYY, your secret number is 44\");\nelse Response.Write(subDomain+\" doesn't exist\");\n%>\n</code></pre>\n"
},
{
"answer_id": 1232,
"author": "Mat",
"author_id": 48,
"author_profile": "https://Stackoverflow.com/users/48",
"pm_score": 5,
"selected": true,
"text": "<p>The way we do this is to have a 'catch all' for our domain name registered in DNS so that anything.ourdomain.com will point to our server.</p>\n\n<p>With Apache you can set up a similar catch-all for your vhosts. The ServerName must be a single static name but the ServerAlias directive can contain a pattern.</p>\n\n<pre><code>Servername www.ourdomain.com\nServerAlias *.ourdomain.com\n</code></pre>\n\n<p>Now all of the domains will trigger the vhost for our project. The final part is to decode the domain name actually used so that you can work out the username in your code, something like (PHP):</p>\n\n<pre><code>list( $username ) = explode( \".\", $_SERVER[ \"HTTP_HOST\" ] );\n</code></pre>\n\n<p>or a RewriteRule as already suggested that silently maps user.ourdomain.com/foo/bar to www.ourdomain.com/foo/bar?user=user or whatever you prefer.</p>\n"
},
{
"answer_id": 1555232,
"author": "Jamie",
"author_id": 188511,
"author_profile": "https://Stackoverflow.com/users/188511",
"pm_score": 0,
"selected": false,
"text": "<p>I was looking to do something similar (<code>www.mysite.com/SomeUser</code>).</p>\n\n<p>What I did was I edited <code>404.shtml</code> to include this server side include (SSI) code:</p>\n\n<pre><code><!--#include virtual=\"404.php\" -- >\n</code></pre>\n\n<p>Then I created the file <code>404.php</code>, where I parsed the URL to check for a user's name and showed their info from the database.</p>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281/"
] | I am looking to allow users to control of subdomain of an app I am toying with, much like Basecamp where it is `customusername.seework.com`.
What is required on the `DNS` end to allow these to be created dynamically and be available instantly.
And how do you recommend dealing with this in the logic of the site? `Htaccess` rule to lookup the subdomain in the `DB`? | The way we do this is to have a 'catch all' for our domain name registered in DNS so that anything.ourdomain.com will point to our server.
With Apache you can set up a similar catch-all for your vhosts. The ServerName must be a single static name but the ServerAlias directive can contain a pattern.
```
Servername www.ourdomain.com
ServerAlias *.ourdomain.com
```
Now all of the domains will trigger the vhost for our project. The final part is to decode the domain name actually used so that you can work out the username in your code, something like (PHP):
```
list( $username ) = explode( ".", $_SERVER[ "HTTP_HOST" ] );
```
or a RewriteRule as already suggested that silently maps user.ourdomain.com/foo/bar to www.ourdomain.com/foo/bar?user=user or whatever you prefer. |
1,237 | <p>I have a file in the following format:</p>
<pre>
Data Data
Data
[Start]
Data I want
[End]
Data
</pre>
<p>I'd like to grab the <code>Data I want</code> from between the <code>[Start]</code> and <code>[End]</code> tags using a Regex. Can anyone show me how this might be done?</p>
| [
{
"answer_id": 1240,
"author": "Karl Seguin",
"author_id": 34,
"author_profile": "https://Stackoverflow.com/users/34",
"pm_score": 6,
"selected": false,
"text": "<pre><code>\\[start\\](.*?)\\[end\\]\n</code></pre>\n\n<p>Zhich'll put the text in the middle within a capture.</p>\n"
},
{
"answer_id": 1243,
"author": "Xenph Yan",
"author_id": 264,
"author_profile": "https://Stackoverflow.com/users/264",
"pm_score": 6,
"selected": true,
"text": "<pre><code>\\[start\\]\\s*(((?!\\[start\\]|\\[end\\]).)+)\\s*\\[end\\]\n</code></pre>\n\n<p>This should hopefully drop the <code>[start]</code> and <code>[end]</code> markers as well.</p>\n"
},
{
"answer_id": 1252,
"author": "Grant",
"author_id": 30,
"author_profile": "https://Stackoverflow.com/users/30",
"pm_score": 1,
"selected": false,
"text": "<p>With Perl you can surround the data you want with ()'s and pull it out later, perhaps other languages have a similar feature.</p>\n\n<pre><code>if ($s_output =~ /(data data data data START(data data data)END (data data)/) \n{\n $dataAllOfIt = $1; # 1 full string\n $dataInMiddle = $2; # 2 Middle Data\n $dataAtEnd = $3; # 3 End Data\n}\n</code></pre>\n"
},
{
"answer_id": 18612,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 2,
"selected": false,
"text": "<p>A more complete discussion of the pitfalls of using a regex to find matching tags can be found at: <a href=\"http://faq.perl.org/perlfaq4.html#How_do_I_find_matchi\" rel=\"noreferrer\">http://faq.perl.org/perlfaq4.html#How_do_I_find_matchi</a>. In particular, be aware that nesting tags really need a full-fledged parser in order to be interpreted correctly.</p>\n\n<p>Note that case sensitivity will need to be turned off in order to answer the question as stated. In perl, that's the <strong>i</strong> modifier:</p>\n\n<pre><code>$ echo \"Data Data Data [Start] Data i want [End] Data\" \\\n | perl -ne '/\\[start\\](.*?)\\[end\\]/i; print \"$1\\n\"'\n Data i want \n</code></pre>\n\n<p>The other trick is to use the <strong>*?</strong> quantifier which turns off the greediness of the captured match. For instance, if you have a non-matching <strong>[end]</strong> tag:</p>\n\n<pre><code>Data Data [Start] Data i want [End] Data [end]\n</code></pre>\n\n<p>you probably don't want to capture:</p>\n\n<pre><code> Data i want [End] Data\n</code></pre>\n"
},
{
"answer_id": 63313,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 2,
"selected": false,
"text": "<p>While you can use a regular expression to parse the data between opening and closing tags, you need to think long and hard as to whether this is a path you want to go down. The reason for it is the potential of tags to nest: if nesting tags could ever happen or may ever happen, the language is said to no longer be regular, and regular expressions cease to be the proper tool for parsing it.</p>\n\n<p>Many regular expression implementations, such as PCRE or perl's regular expressions, support backtracking which can be used to achieve this rough effect. But PCRE (unlike perl) doesn't support unlimited backtracking, and this can actually cause things to break in weird ways as soon as you have too many tags. </p>\n\n<p>There's a very commonly cited blog post that discusses this more, <a href=\"http://kore-nordmann.de/blog/do_NOT_parse_using_regexp.html\" rel=\"nofollow noreferrer\">http://kore-nordmann.de/blog/do_NOT_parse_using_regexp.html</a> (google for it and check the cache currently, they seem to be having some downtime)</p>\n"
},
{
"answer_id": 849859,
"author": "un33k",
"author_id": 103734,
"author_profile": "https://Stackoverflow.com/users/103734",
"pm_score": 2,
"selected": false,
"text": "<p>Well, if you guarantee that each start tag is followed by an end tag then the following would work.</p>\n\n<pre><code>\\[start\\](.*?)\\[end\\]\n</code></pre>\n\n<p>However, If you have complex text such as the follwoing:</p>\n\n<pre><code>[start] sometext [start] sometext2 [end] sometext [end]\n</code></pre>\n\n<p>then you would run into problems with regex.</p>\n\n<p>Now the following example will pull out all the hot links in a page:</p>\n\n<pre><code>'/<a(.*?)a>/i'\n</code></pre>\n\n<p>In the above case we can guarantee that there would not be any nested cases of:</p>\n\n<pre><code>'<a></a>'\n</code></pre>\n\n<p>So, this is a complex question and can't just be solved with a simple answer.</p>\n"
},
{
"answer_id": 12761781,
"author": "PhaZe",
"author_id": 1725440,
"author_profile": "https://Stackoverflow.com/users/1725440",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$text =\"Data Data Data start Data i want end Data\";\n($content) = $text =~ m/ start (.*) end /;\nprint $content;\n</code></pre>\n\n<p>I had a similar problem for a while & I can tell you this method works...</p>\n"
},
{
"answer_id": 18498275,
"author": "ankitkpd",
"author_id": 1713298,
"author_profile": "https://Stackoverflow.com/users/1713298",
"pm_score": 0,
"selected": false,
"text": "<p>Refer to this question to pull out text between tags with space characters and dots (<code>.</code>)</p>\n\n<p><code>[\\S\\s]</code> is the one I used </p>\n\n<p><a href=\"https://stackoverflow.com/questions/8303488/regex-to-match-any-character-including-new-lines\">Regex to match any character including new lines</a></p>\n"
},
{
"answer_id": 25803893,
"author": "N Murali Mohan",
"author_id": 4033971,
"author_profile": "https://Stackoverflow.com/users/4033971",
"pm_score": 0,
"selected": false,
"text": "<p>Reading the text with in the square brackets [] i.e.[Start] and [End] and validate the array with a list of values. <b><em>jsfiddle</em></b> <a href=\"http://jsfiddle.net/muralinarisetty/r4s4wxj4/1/\" rel=\"nofollow\">http://jsfiddle.net/muralinarisetty/r4s4wxj4/1/</a></p>\n\n<pre><code>var mergeFields = [\"[sitename]\",\n \"[daystoholdquote]\",\n \"[expires]\",\n \"[firstname]\",\n \"[lastname]\",\n \"[sitephonenumber]\",\n \"[hoh_firstname]\",\n \"[hoh_lastname]\"]; \n\nvar str = \"fee [sitename] [firstname] \\\nsdfasd [lastname] \";\nvar res = validateMeargeFileds(str);\nconsole.log(res);\n\nfunction validateMeargeFileds(input) {\n var re = /\\[\\w+]/ig;\n var isValid;\n var myArray = input.match(re);\n\n try{\n if (myArray.length > 0) {\n myArray.forEach(function (field) {\n\n isValid = isMergeField(field);\n\n if (!isValid){\n throw e; \n }\n });\n }\n }\n catch(e) { \n }\n\n return isValid;\n}\n\nfunction isMergeField(mergefield) {\n return mergeFields.indexOf(mergefield.toLowerCase()) > -1;\n}\n</code></pre>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] | I have a file in the following format:
```
Data Data
Data
[Start]
Data I want
[End]
Data
```
I'd like to grab the `Data I want` from between the `[Start]` and `[End]` tags using a Regex. Can anyone show me how this might be done? | ```
\[start\]\s*(((?!\[start\]|\[end\]).)+)\s*\[end\]
```
This should hopefully drop the `[start]` and `[end]` markers as well. |
1,292 | <p>I have a Queue<T> object that I have initialised to a capacity of 2, but obviously that is just the capacity and it keeps expanding as I add items. Is there already an object that automatically dequeues an item when the limit is reached, or is the best solution to create my own inherited class?</p>
| [
{
"answer_id": 1297,
"author": "CodingWithoutComments",
"author_id": 25,
"author_profile": "https://Stackoverflow.com/users/25",
"pm_score": 2,
"selected": false,
"text": "<p>Why wouldn't you just use an array with a size of 2? A Queue is supposed to be able to dynamically grow and shrink.</p>\n\n<p>Or create a wrapper class around an instance of <code>Queue<T></code> instance and each time one enqueues a <code><T></code> object, check the size of the queue. If larger than 2, dequeue the first item.</p>\n"
},
{
"answer_id": 1303,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "<p>You should create your own class, a ringbuffer would probably fit your needs.</p>\n\n<p>The data structures in .NET that allows you to specify capacity, except for array, uses this to build the internal data structure used to hold the internal data.</p>\n\n<p>For instance, for a list, capacity is used to size an internal array. When you start adding elements to the list, it'll start filling this array from index 0 and up, and when it reaches your capacity, it increases the capacity to a new higher capacity, and continues filling it up.</p>\n"
},
{
"answer_id": 1305,
"author": "tags2k",
"author_id": 192,
"author_profile": "https://Stackoverflow.com/users/192",
"pm_score": 6,
"selected": true,
"text": "<p>I've knocked up a basic version of what I'm looking for, it's not perfect but it'll do the job until something better comes along.</p>\n\n<pre><code>public class LimitedQueue<T> : Queue<T>\n{\n public int Limit { get; set; }\n\n public LimitedQueue(int limit) : base(limit)\n {\n Limit = limit;\n }\n\n public new void Enqueue(T item)\n {\n while (Count >= Limit)\n {\n Dequeue();\n }\n base.Enqueue(item);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 233606,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 4,
"selected": false,
"text": "<p>I would recommend that you pull up the <a href=\"http://www.itu.dk/research/c5\" rel=\"noreferrer\">C5 Library</a>. Unlike SCG (System.Collections.Generic), C5 is programmed to interface and designed to be subclassed. Most public methods are virtual and none of the classes are sealed. This way, you won't have to use that icky \"new\" keyword which wouldn't trigger if your <code>LimitedQueue<T></code> were cast to a <code>SCG.Queue<T></code>. With C5 and using close to the same code as you had before, you would derive from the <code>CircularQueue<T></code>. The <code>CircularQueue<T></code> actually implements both a stack and a queue, so you can get both options with a limit nearly for free. I've rewritten it below with some 3.5 constructs:</p>\n\n<pre><code>using C5;\n\npublic class LimitedQueue<T> : CircularQueue<T>\n{\n public int Limit { get; set; }\n\n public LimitedQueue(int limit) : base(limit)\n {\n this.Limit = limit;\n }\n\n public override void Push(T item)\n {\n CheckLimit(false);\n base.Push(item);\n }\n\n public override void Enqueue(T item)\n {\n CheckLimit(true);\n base.Enqueue(item);\n }\n\n protected virtual void CheckLimit(bool enqueue)\n {\n while (this.Count >= this.Limit)\n {\n if (enqueue)\n {\n this.Dequeue();\n }\n else\n {\n this.Pop();\n }\n }\n }\n}\n</code></pre>\n\n<p>I think that this code should do exactly what you were looking for.</p>\n"
},
{
"answer_id": 8136476,
"author": "Robel.E",
"author_id": 1047575,
"author_profile": "https://Stackoverflow.com/users/1047575",
"pm_score": 3,
"selected": false,
"text": "<p>Well I hope this class will helps You:<br>\nInternally the Circular FIFO Buffer use a Queue<T> with the specified size. \nOnce the size of the buffer is reached, it will replaces older items with new ones.</p>\n\n<p>NOTE: You can't remove items randomly. I set the method Remove(T item) to return false.\nif You want You can modify to remove items randomly</p>\n\n<pre><code>public class CircularFIFO<T> : ICollection<T> , IDisposable\n{\n public Queue<T> CircularBuffer;\n\n /// <summary>\n /// The default initial capacity.\n /// </summary>\n private int capacity = 32;\n\n /// <summary>\n /// Gets the actual capacity of the FIFO.\n /// </summary>\n public int Capacity\n {\n get { return capacity; } \n }\n\n /// <summary>\n /// Initialize a new instance of FIFO class that is empty and has the default initial capacity.\n /// </summary>\n public CircularFIFO()\n { \n CircularBuffer = new Queue<T>();\n }\n\n /// <summary>\n /// Initialize a new instance of FIFO class that is empty and has the specified initial capacity.\n /// </summary>\n /// <param name=\"size\"> Initial capacity of the FIFO. </param>\n public CircularFIFO(int size)\n {\n capacity = size;\n CircularBuffer = new Queue<T>(capacity);\n }\n\n /// <summary>\n /// Adds an item to the end of the FIFO.\n /// </summary>\n /// <param name=\"item\"> The item to add to the end of the FIFO. </param>\n public void Add(T item)\n {\n if (this.Count >= this.Capacity)\n Remove();\n\n CircularBuffer.Enqueue(item);\n }\n\n /// <summary>\n /// Adds array of items to the end of the FIFO.\n /// </summary>\n /// <param name=\"item\"> The array of items to add to the end of the FIFO. </param>\n public void Add(T[] item)\n { \n int enqueuedSize = 0;\n int remainEnqueueSize = this.Capacity - this.Count;\n\n for (; (enqueuedSize < item.Length && enqueuedSize < remainEnqueueSize); enqueuedSize++)\n CircularBuffer.Enqueue(item[enqueuedSize]);\n\n if ((item.Length - enqueuedSize) != 0)\n {\n Remove((item.Length - enqueuedSize));//remaining item size\n\n for (; enqueuedSize < item.Length; enqueuedSize++)\n CircularBuffer.Enqueue(item[enqueuedSize]);\n } \n }\n\n /// <summary>\n /// Removes and Returns an item from the FIFO.\n /// </summary>\n /// <returns> Item removed. </returns>\n public T Remove()\n {\n T removedItem = CircularBuffer.Peek();\n CircularBuffer.Dequeue();\n\n return removedItem;\n }\n\n /// <summary>\n /// Removes and Returns the array of items form the FIFO.\n /// </summary>\n /// <param name=\"size\"> The size of item to be removed from the FIFO. </param>\n /// <returns> Removed array of items </returns>\n public T[] Remove(int size)\n {\n if (size > CircularBuffer.Count)\n size = CircularBuffer.Count;\n\n T[] removedItems = new T[size];\n\n for (int i = 0; i < size; i++)\n {\n removedItems[i] = CircularBuffer.Peek();\n CircularBuffer.Dequeue();\n }\n\n return removedItems;\n }\n\n /// <summary>\n /// Returns the item at the beginning of the FIFO with out removing it.\n /// </summary>\n /// <returns> Item Peeked. </returns>\n public T Peek()\n {\n return CircularBuffer.Peek();\n }\n\n /// <summary>\n /// Returns the array of item at the beginning of the FIFO with out removing it.\n /// </summary>\n /// <param name=\"size\"> The size of the array items. </param>\n /// <returns> Array of peeked items. </returns>\n public T[] Peek(int size)\n {\n T[] arrayItems = new T[CircularBuffer.Count];\n CircularBuffer.CopyTo(arrayItems, 0);\n\n if (size > CircularBuffer.Count)\n size = CircularBuffer.Count;\n\n T[] peekedItems = new T[size];\n\n Array.Copy(arrayItems, 0, peekedItems, 0, size);\n\n return peekedItems;\n }\n\n /// <summary>\n /// Gets the actual number of items presented in the FIFO.\n /// </summary>\n public int Count\n {\n get\n {\n return CircularBuffer.Count;\n }\n }\n\n /// <summary>\n /// Removes all the contents of the FIFO.\n /// </summary>\n public void Clear()\n {\n CircularBuffer.Clear();\n }\n\n /// <summary>\n /// Resets and Initialize the instance of FIFO class that is empty and has the default initial capacity.\n /// </summary>\n public void Reset()\n {\n Dispose();\n CircularBuffer = new Queue<T>(capacity);\n }\n\n #region ICollection<T> Members\n\n /// <summary>\n /// Determines whether an element is in the FIFO.\n /// </summary>\n /// <param name=\"item\"> The item to locate in the FIFO. </param>\n /// <returns></returns>\n public bool Contains(T item)\n {\n return CircularBuffer.Contains(item);\n }\n\n /// <summary>\n /// Copies the FIFO elements to an existing one-dimensional array. \n /// </summary>\n /// <param name=\"array\"> The one-dimensional array that have at list a size of the FIFO </param>\n /// <param name=\"arrayIndex\"></param>\n public void CopyTo(T[] array, int arrayIndex)\n {\n if (array.Length >= CircularBuffer.Count)\n CircularBuffer.CopyTo(array, 0); \n }\n\n public bool IsReadOnly\n {\n get { return false; }\n }\n\n public bool Remove(T item)\n {\n return false; \n }\n\n #endregion\n\n #region IEnumerable<T> Members\n\n public IEnumerator<T> GetEnumerator()\n {\n return CircularBuffer.GetEnumerator();\n }\n\n #endregion\n\n #region IEnumerable Members\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return CircularBuffer.GetEnumerator();\n }\n\n #endregion\n\n #region IDisposable Members\n\n /// <summary>\n /// Releases all the resource used by the FIFO.\n /// </summary>\n public void Dispose()\n { \n CircularBuffer.Clear();\n CircularBuffer = null;\n GC.Collect();\n }\n\n #endregion\n}\n</code></pre>\n"
},
{
"answer_id": 8867737,
"author": "mpen",
"author_id": 65387,
"author_profile": "https://Stackoverflow.com/users/65387",
"pm_score": 2,
"selected": false,
"text": "<p>If it's of any use to anyone, I made a <code>LimitedStack<T></code>.</p>\n\n<pre><code>public class LimitedStack<T>\n{\n public readonly int Limit;\n private readonly List<T> _stack;\n\n public LimitedStack(int limit = 32)\n {\n Limit = limit;\n _stack = new List<T>(limit);\n }\n\n public void Push(T item)\n {\n if (_stack.Count == Limit) _stack.RemoveAt(0);\n _stack.Add(item);\n }\n\n public T Peek()\n {\n return _stack[_stack.Count - 1];\n }\n\n public void Pop()\n {\n _stack.RemoveAt(_stack.Count - 1);\n }\n\n public int Count\n {\n get { return _stack.Count; }\n }\n}\n</code></pre>\n\n<p>It removes the oldest item (bottom of stack) when it gets too big.</p>\n\n<p>(This question was the top Google result for \"C# limit stack size\")</p>\n"
},
{
"answer_id": 50261664,
"author": "SwiftArchitect",
"author_id": 218152,
"author_profile": "https://Stackoverflow.com/users/218152",
"pm_score": 3,
"selected": false,
"text": "<h3>Concurrent Solution</h3>\n<pre><code>public class LimitedConcurrentQueue<ELEMENT> : ConcurrentQueue<ELEMENT>\n{\n public readonly int Limit;\n\n public LimitedConcurrentQueue(int limit)\n {\n Limit = limit;\n }\n\n public new void Enqueue(ELEMENT element)\n {\n base.Enqueue(element);\n if (Count > Limit)\n {\n TryDequeue(out ELEMENT discard);\n }\n }\n}\n</code></pre>\n<p>Note: Since <code>Enqueue</code> controls the addition of elements, and does so one at a time, there is no need to execute a <code>while</code> for <code>TryDequeue</code>.</p>\n"
},
{
"answer_id": 62108498,
"author": "Brandon",
"author_id": 674237,
"author_profile": "https://Stackoverflow.com/users/674237",
"pm_score": 1,
"selected": false,
"text": "<p>You can use a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1?view=netcore-3.1\" rel=\"nofollow noreferrer\"><code>LinkedList<T></code></a> and add thread safety:</p>\n\n<pre><code>public class Buffer<T> : LinkedList<T>\n{\n private int capacity;\n\n public Buffer(int capacity)\n {\n this.capacity = capacity; \n }\n\n public void Enqueue(T item)\n {\n // todo: add synchronization mechanism\n if (Count == capacity) RemoveLast();\n AddFirst(item);\n }\n\n public T Dequeue()\n {\n // todo: add synchronization mechanism\n var last = Last.Value;\n RemoveLast();\n return last;\n }\n}\n</code></pre>\n\n<p>One thing to note is the default enumeration order will be LIFO in this example. But that can be overridden if necessary.</p>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] | I have a Queue<T> object that I have initialised to a capacity of 2, but obviously that is just the capacity and it keeps expanding as I add items. Is there already an object that automatically dequeues an item when the limit is reached, or is the best solution to create my own inherited class? | I've knocked up a basic version of what I'm looking for, it's not perfect but it'll do the job until something better comes along.
```
public class LimitedQueue<T> : Queue<T>
{
public int Limit { get; set; }
public LimitedQueue(int limit) : base(limit)
{
Limit = limit;
}
public new void Enqueue(T item)
{
while (Count >= Limit)
{
Dequeue();
}
base.Enqueue(item);
}
}
``` |
1,304 | <p>Is there any way to check whether a file is locked without using a try/catch block? </p>
<p>Right now, the only way I know of is to just open the file and catch any <code>System.IO.IOException</code>.</p>
| [
{
"answer_id": 1309,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 8,
"selected": true,
"text": "<p>No, unfortunately, and if you think about it, that information would be worthless anyway since the file could become locked the very next second (read: short timespan).</p>\n\n<p>Why specifically do you need to know if the file is locked anyway? Knowing that might give us some other way of giving you good advice.</p>\n\n<p>If your code would look like this:</p>\n\n<pre><code>if not locked then\n open and update file\n</code></pre>\n\n<p>Then between the two lines, another process could easily lock the file, giving you the same problem you were trying to avoid to begin with: exceptions.</p>\n"
},
{
"answer_id": 13789,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Then between the two lines, another process could easily lock the file, giving you the same problem you were trying to avoid to begin with: exceptions.</p>\n</blockquote>\n\n<p>However, this way, you would know that the problem is temporary, and to retry later. (E.g., you could write a thread that, if encountering a lock while trying to write, keeps retrying until the lock is gone.)</p>\n\n<p>The IOException, on the other hand, is not by itself specific enough that locking is the cause of the IO failure. There could be reasons that aren't temporary.</p>\n"
},
{
"answer_id": 626095,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 2,
"selected": false,
"text": "<p>You can see if the file is locked by trying to read or lock it yourself first. </p>\n\n<p><a href=\"https://stackoverflow.com/questions/203837/can-i-simply-read-a-file-that-is-in-use/203839#203839\">Please see my answer here for more information</a>.</p>\n"
},
{
"answer_id": 1176082,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 3,
"selected": false,
"text": "<p>You could call <a href=\"http://msdn.microsoft.com/en-us/library/aa365202%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">LockFile</a> via interop on the region of file you are interested in. This will not throw an exception, if it succeeds you will have a lock on that portion of the file (which is held by your process), that lock will be held until you call <a href=\"http://msdn.microsoft.com/en-us/library/aa365715%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">UnlockFile</a> or your process dies. </p>\n"
},
{
"answer_id": 2403108,
"author": "Sergio Vicente",
"author_id": 198152,
"author_profile": "https://Stackoverflow.com/users/198152",
"pm_score": 4,
"selected": false,
"text": "<p>Instead of using interop you can use the .NET FileStream class methods Lock and Unlock:</p>\n\n<p>FileStream.Lock\n<a href=\"http://msdn.microsoft.com/en-us/library/system.io.filestream.lock.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.io.filestream.lock.aspx</a></p>\n\n<p>FileStream.Unlock\n<a href=\"http://msdn.microsoft.com/en-us/library/system.io.filestream.unlock.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.io.filestream.unlock.aspx</a></p>\n"
},
{
"answer_id": 3202085,
"author": "DixonD",
"author_id": 213725,
"author_profile": "https://Stackoverflow.com/users/213725",
"pm_score": 8,
"selected": false,
"text": "<p>When I faced with a similar problem, I finished with the following code:</p>\n<pre><code>public class FileManager\n{\n private string _fileName;\n\n private int _numberOfTries;\n\n private int _timeIntervalBetweenTries;\n\n private FileStream GetStream(FileAccess fileAccess)\n {\n var tries = 0;\n while (true)\n {\n try\n {\n return File.Open(_fileName, FileMode.Open, fileAccess, Fileshare.None); \n }\n catch (IOException e)\n {\n if (!IsFileLocked(e))\n throw;\n if (++tries > _numberOfTries)\n throw new MyCustomException("The file is locked too long: " + e.Message, e);\n Thread.Sleep(_timeIntervalBetweenTries);\n }\n }\n }\n\n private static bool IsFileLocked(IOException exception)\n {\n int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);\n return errorCode == 32 || errorCode == 33;\n }\n\n // other code\n\n}\n</code></pre>\n"
},
{
"answer_id": 5512640,
"author": "Aralmo",
"author_id": 687466,
"author_profile": "https://Stackoverflow.com/users/687466",
"pm_score": 4,
"selected": false,
"text": "<p>You can also check if any process is using this file and show a list of programs you must close to continue like an installer does.</p>\n\n<pre><code>public static string GetFileProcessName(string filePath)\n{\n Process[] procs = Process.GetProcesses();\n string fileName = Path.GetFileName(filePath);\n\n foreach (Process proc in procs)\n {\n if (proc.MainWindowHandle != new IntPtr(0) && !proc.HasExited)\n {\n ProcessModule[] arr = new ProcessModule[proc.Modules.Count];\n\n foreach (ProcessModule pm in proc.Modules)\n {\n if (pm.ModuleName == fileName)\n return proc.ProcessName;\n }\n }\n }\n\n return null;\n}\n</code></pre>\n"
},
{
"answer_id": 14132721,
"author": "Tristan",
"author_id": 642282,
"author_profile": "https://Stackoverflow.com/users/642282",
"pm_score": 3,
"selected": false,
"text": "<p>A variation of DixonD's excellent answer (above).</p>\n\n<pre><code>public static bool TryOpen(string path,\n FileMode fileMode,\n FileAccess fileAccess,\n FileShare fileShare,\n TimeSpan timeout,\n out Stream stream)\n{\n var endTime = DateTime.Now + timeout;\n\n while (DateTime.Now < endTime)\n {\n if (TryOpen(path, fileMode, fileAccess, fileShare, out stream))\n return true;\n }\n\n stream = null;\n return false;\n}\n\npublic static bool TryOpen(string path,\n FileMode fileMode,\n FileAccess fileAccess,\n FileShare fileShare,\n out Stream stream)\n{\n try\n {\n stream = File.Open(path, fileMode, fileAccess, fileShare);\n return true;\n }\n catch (IOException e)\n {\n if (!FileIsLocked(e))\n throw;\n\n stream = null;\n return false;\n }\n}\n\nprivate const uint HRFileLocked = 0x80070020;\nprivate const uint HRPortionOfFileLocked = 0x80070021;\n\nprivate static bool FileIsLocked(IOException ioException)\n{\n var errorCode = (uint)Marshal.GetHRForException(ioException);\n return errorCode == HRFileLocked || errorCode == HRPortionOfFileLocked;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>private void Sample(string filePath)\n{\n Stream stream = null;\n\n try\n {\n var timeOut = TimeSpan.FromSeconds(1);\n\n if (!TryOpen(filePath,\n FileMode.Open,\n FileAccess.ReadWrite,\n FileShare.ReadWrite,\n timeOut,\n out stream))\n return;\n\n // Use stream...\n }\n finally\n {\n if (stream != null)\n stream.Close();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18989377,
"author": "live-love",
"author_id": 436341,
"author_profile": "https://Stackoverflow.com/users/436341",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a variation of DixonD's code that adds number of seconds to wait for file to unlock, and try again:</p>\n\n<pre><code>public bool IsFileLocked(string filePath, int secondsToWait)\n{\n bool isLocked = true;\n int i = 0;\n\n while (isLocked && ((i < secondsToWait) || (secondsToWait == 0)))\n {\n try\n {\n using (File.Open(filePath, FileMode.Open)) { }\n return false;\n }\n catch (IOException e)\n {\n var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);\n isLocked = errorCode == 32 || errorCode == 33;\n i++;\n\n if (secondsToWait !=0)\n new System.Threading.ManualResetEvent(false).WaitOne(1000);\n }\n }\n\n return isLocked;\n}\n\n\nif (!IsFileLocked(file, 10))\n{\n ...\n}\nelse\n{\n throw new Exception(...);\n}\n</code></pre>\n"
},
{
"answer_id": 20619061,
"author": "Bart Calixto",
"author_id": 826568,
"author_profile": "https://Stackoverflow.com/users/826568",
"pm_score": -1,
"selected": false,
"text": "<p>What I ended up doing is:</p>\n\n<pre><code>internal void LoadExternalData() {\n FileStream file;\n\n if (TryOpenRead(\"filepath/filename\", 5, out file)) {\n using (file)\n using (StreamReader reader = new StreamReader(file)) {\n // do something \n }\n }\n}\n\n\ninternal bool TryOpenRead(string path, int timeout, out FileStream file) {\n bool isLocked = true;\n bool condition = true;\n\n do {\n try {\n file = File.OpenRead(path);\n return true;\n }\n catch (IOException e) {\n var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);\n isLocked = errorCode == 32 || errorCode == 33;\n condition = (isLocked && timeout > 0);\n\n if (condition) {\n // we only wait if the file is locked. If the exception is of any other type, there's no point on keep trying. just return false and null;\n timeout--;\n new System.Threading.ManualResetEvent(false).WaitOne(1000);\n }\n }\n }\n while (condition);\n\n file = null;\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 20623302,
"author": "Eric J.",
"author_id": 141172,
"author_profile": "https://Stackoverflow.com/users/141172",
"pm_score": 7,
"selected": false,
"text": "<p><strong>The other answers rely on old information. This one provides a better solution.</strong></p>\n\n<p>Long ago it was impossible to reliably get the list of processes locking a file because Windows simply did not track that information. To support the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa373656%28v=vs.85%29.aspx\" rel=\"noreferrer\">Restart Manager API</a>, that information is now tracked. The Restart Manager API is available beginning with Windows Vista and Windows Server 2008 (<a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/cc948910(v=vs.85).aspx\" rel=\"noreferrer\">Restart Manager: Run-time Requirements</a>).</p>\n\n<p>I put together code that takes the path of a file and returns a <code>List<Process></code> of all processes that are locking that file.</p>\n\n<pre><code>static public class FileUtil\n{\n [StructLayout(LayoutKind.Sequential)]\n struct RM_UNIQUE_PROCESS\n {\n public int dwProcessId;\n public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;\n }\n\n const int RmRebootReasonNone = 0;\n const int CCH_RM_MAX_APP_NAME = 255;\n const int CCH_RM_MAX_SVC_NAME = 63;\n\n enum RM_APP_TYPE\n {\n RmUnknownApp = 0,\n RmMainWindow = 1,\n RmOtherWindow = 2,\n RmService = 3,\n RmExplorer = 4,\n RmConsole = 5,\n RmCritical = 1000\n }\n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\n struct RM_PROCESS_INFO\n {\n public RM_UNIQUE_PROCESS Process;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]\n public string strAppName;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]\n public string strServiceShortName;\n\n public RM_APP_TYPE ApplicationType;\n public uint AppStatus;\n public uint TSSessionId;\n [MarshalAs(UnmanagedType.Bool)]\n public bool bRestartable;\n }\n\n [DllImport(\"rstrtmgr.dll\", CharSet = CharSet.Unicode)]\n static extern int RmRegisterResources(uint pSessionHandle,\n UInt32 nFiles,\n string[] rgsFilenames,\n UInt32 nApplications,\n [In] RM_UNIQUE_PROCESS[] rgApplications,\n UInt32 nServices,\n string[] rgsServiceNames);\n\n [DllImport(\"rstrtmgr.dll\", CharSet = CharSet.Auto)]\n static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);\n\n [DllImport(\"rstrtmgr.dll\")]\n static extern int RmEndSession(uint pSessionHandle);\n\n [DllImport(\"rstrtmgr.dll\")]\n static extern int RmGetList(uint dwSessionHandle,\n out uint pnProcInfoNeeded,\n ref uint pnProcInfo,\n [In, Out] RM_PROCESS_INFO[] rgAffectedApps,\n ref uint lpdwRebootReasons);\n\n /// <summary>\n /// Find out what process(es) have a lock on the specified file.\n /// </summary>\n /// <param name=\"path\">Path of the file.</param>\n /// <returns>Processes locking the file</returns>\n /// <remarks>See also:\n /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx\n /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)\n /// \n /// </remarks>\n static public List<Process> WhoIsLocking(string path)\n {\n uint handle;\n string key = Guid.NewGuid().ToString();\n List<Process> processes = new List<Process>();\n\n int res = RmStartSession(out handle, 0, key);\n\n if (res != 0)\n throw new Exception(\"Could not begin restart session. Unable to determine file locker.\");\n\n try\n {\n const int ERROR_MORE_DATA = 234;\n uint pnProcInfoNeeded = 0,\n pnProcInfo = 0,\n lpdwRebootReasons = RmRebootReasonNone;\n\n string[] resources = new string[] { path }; // Just checking on one resource.\n\n res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);\n\n if (res != 0) \n throw new Exception(\"Could not register resource.\"); \n\n //Note: there's a race condition here -- the first call to RmGetList() returns\n // the total number of process. However, when we call RmGetList() again to get\n // the actual processes this number may have increased.\n res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);\n\n if (res == ERROR_MORE_DATA)\n {\n // Create an array to store the process results\n RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];\n pnProcInfo = pnProcInfoNeeded;\n\n // Get the list\n res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);\n\n if (res == 0)\n {\n processes = new List<Process>((int)pnProcInfo);\n\n // Enumerate all of the results and add them to the \n // list to be returned\n for (int i = 0; i < pnProcInfo; i++)\n {\n try\n {\n processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));\n }\n // catch the error -- in case the process is no longer running\n catch (ArgumentException) { }\n }\n }\n else\n throw new Exception(\"Could not list processes locking resource.\"); \n }\n else if (res != 0)\n throw new Exception(\"Could not list processes locking resource. Failed to get size of result.\"); \n }\n finally\n {\n RmEndSession(handle);\n }\n\n return processes;\n }\n}\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Here is another <a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20120217-00/?p=8283\" rel=\"noreferrer\">discussion with sample code</a> on how to use the Restart Manager API.</p>\n"
},
{
"answer_id": 34437734,
"author": "Thom Schumacher",
"author_id": 4991132,
"author_profile": "https://Stackoverflow.com/users/4991132",
"pm_score": 0,
"selected": false,
"text": "<p>Same thing but in Powershell</p>\n\n<pre><code>function Test-FileOpen\n{\n Param\n ([string]$FileToOpen)\n try\n {\n $openFile =([system.io.file]::Open($FileToOpen,[system.io.filemode]::Open))\n $open =$true\n $openFile.close()\n }\n catch\n {\n $open = $false\n }\n $open\n}\n</code></pre>\n"
}
] | 2008/08/04 | [
"https://Stackoverflow.com/questions/1304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121/"
] | Is there any way to check whether a file is locked without using a try/catch block?
Right now, the only way I know of is to just open the file and catch any `System.IO.IOException`. | No, unfortunately, and if you think about it, that information would be worthless anyway since the file could become locked the very next second (read: short timespan).
Why specifically do you need to know if the file is locked anyway? Knowing that might give us some other way of giving you good advice.
If your code would look like this:
```
if not locked then
open and update file
```
Then between the two lines, another process could easily lock the file, giving you the same problem you were trying to avoid to begin with: exceptions. |