qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
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 &quot;home&quot; is at 111,111 and apparently M428 can only be used at a maximum of 20 mm from 0, I get a &quot;too far from reference&quot; 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 -&gt; Motion -&gt; 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 &quot;Z offset means the distance between your nozzle and bed, and here is how to adjust it&quot;. 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 (&quot;effectively shifts the coordinate space&quot;) - so you ...
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 causin...
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 ...
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>C...
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...
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 &amp; 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 ...
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 &amp; 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 irre...
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 ...
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> &amp; <code>G29</code> in my G-code file, and the printer &amp; 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 &amp; 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&lt;print_accel&gt; R&lt;retract_accel&gt; T&lt;travel_accel&gt; echo: M204 P500.00 R500.00 T500.00 echo:; Advanced: B&lt;min_segment_time_us&gt; S&lt;min_feedrate&gt; T&lt;min_travel_feedrate&gt; X&lt;max_x_jerk&gt; Y&lt;max_y_jerk&gt; Z&lt;max_z_jerk&gt; E&lt;max_e_jerk&gt; 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&lt;length&gt; F&lt;units/m&gt; Z&lt;lift&gt; echo: M207 S3.00 W13.00 F4800.00 Z0.30 echo:; Recover: S&lt;length&gt; F&lt;units/m&gt; 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 fo...
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&quot; 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&quot;.</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 &quot;skew&quot; 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 y...
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 lai...
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 &quot;outer&quot; 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, yo...
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 &lt;= 250 °C but when I set temperature above 200 °C to print to PLA+, I get an error message &quot;Nozzle is too lowperature&quot; 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 &quot;thermal runaway&quot;.</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 t...
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 &quot;read&quot; the printers, it's like they aren't even there. Makerbot Print (latest version) doesn't seem to &quot;see&quot; 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...
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 =&gt; TMC2208<br /> 4.2.3 =&gt; ?<br /> 4.2.7 =&gt; 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&amp;X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20211215%2Fus-east-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20211215T153407Z&amp;X-Amz-Expires=300&amp;X-Amz-Signature=43dfe1ff5518c5003cf55ade1554caeb5953c733a599db07fb153cc976cebb45&amp;X-Amz-SignedHeaders=host&amp;actor_id=0&amp;key_id=0&amp;repo_id=139231738&amp;response-content-disposition=attachment%3Bfilename%3D1623133432-Creality422-Schematic-2.pdf&amp;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=\...
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=\...
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=\...
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=\...
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 plas...
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 sin...
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'...
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 f...
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 ---&gt; 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 chemi...
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>) fo...
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...
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 cov...
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 cov...
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=&quot;center&quot;, halign=&quot;center&quot;); translate([0, dh * i + h0, 0]) cube([text_width, dh, text_width], center=true); } } } bend_text(&quot;test&quot;, 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>...
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 &quot;Generated with Cura_SteamEngine&quot; 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> -&gt; <code>Printers</code> menu from the top menu,</p>\n<p><a href=\"https://i.s...
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 &quot;trans&quot; to the double variable &quot;this.Opacity&quot;.</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 / 5...
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\"><cod...
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 - d...
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 = &quot;...&quot;; 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" },...
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 &lt;math.h&gt; #include &lt;stdio.h&gt; #include &lt;time.h&gt; #define ITERS 10000000 #define TESTWITH(x) { \ diff = 0.0; \ time1 = clock(); \ for (i = 0; i &lt; ITERS; ++i) \ diff += (x) - M_PI; \ time2 = clock(); \ printf("%s\t=&gt; %e, time =&gt; %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__) &amp;&amp; (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 be...
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 &quot;type&quot; 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 &lt;sys/socket.h&gt; int main() { return AF_INET; } </code></pre> <p>Compile/Link Output:</p> <pre><code>cxx -Wc,xplink -Wl,xplink -o inet_test inet.C &quot;./inet.C&quot;, line 5.16: CCN5274 (S) The name lookup for &quot;AF_INET&quot; 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 &quot;C&quot; { #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>#incl...
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 &lt; 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...
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 r...
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 WordPr...
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>&lt;form&gt; &lt;!-- Put your cursor in this field and press Enter --&gt; &lt;input type="text" name="field1" /&gt; &lt;!-- This is the button that will submit --&gt; &lt;input type="submit" name="prev" value="Previous Page" /&gt; &lt;!-- But this is the button that I WANT to submit --&gt; &lt;input type="submit" name="next" value="Next Page" /&gt; &lt;/form&gt;</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>&lt;input type=\"submit\" name=\"submitButton\" value=\"Prev...
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></...
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 i...
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 ...
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 w...
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(&amp;currentTimeVal, NULL); performanceCount-&gt;QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec); performanceCount-&gt;QuadPart *= (1000 * 1000); performanceCount-&gt;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 de...
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(&currentTimeVal, 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&nbsp; 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 &lt; 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...
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-&gt;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-&gt;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 w...
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 ...
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>&lt;video&gt;</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>&lt;![if !IE]&gt;\n&lt;p&gt; Fir...
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 o...
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...
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 &amp; 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\">Javascrip...
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>&lt;Location&gt;</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>&lt;Virtua...
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. T...
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 mor...
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 &quot;set as default email client&quot;.</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>...
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\Associati‌​ons\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...
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>\...
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(&amp;gtkArgc, &amp;gtkArgv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(G_OBJECT(window), &quot;delete_event&quot;, G_CALLBACK(delete_event), NULL); g_signal_connect(G_OBJECT(window), &quot;destroy&quot;, G_CALLBACK(destroy), NULL); // gcallback calls gtk_main_quit() gtk_init_add((GtkFunction)gcallback, NULL); if (type &amp; 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 &amp; 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 ...
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(&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; } ``` 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...
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 &amp; 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&lt;string,int&gt; item in...
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 &lt; 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...
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 pr...
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 b...
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 &lt; 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 specif...
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&lt;string&gt; myitems = new List&lt;string&gt; { "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...
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/2012041...
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 ha...
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...
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 differe...
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 d...
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 elega...
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 targetStrin...
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...
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(\"(?&lt;!m)m(?!m)\");\nRegex s...
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...
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 &quot;prerequisite&quot; 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,...
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>\nSu...
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'...
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&lt;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...
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>&lt;buildArgs&gt; /noconsolelogger /p:OutputPath=$(CCNetArtifactDirectory)\test &lt;/buildArgs&gt; </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 bui...
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...
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", ...
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>&lt;div&gt; 12333-2333-233-23339392-332332323 &lt;/div&gt;</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>&amp;shy;\n</code></pre>\n\n<p>It's called a \"soft\" hyphen.</p>\n\n<p><div c...
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: ``` &shy; ``` It's called a "soft" hyphen. ```css div { width: 150px; } ``` ```html <div> 12333&shy;2333&shy;233&shy;23339392&shy;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 OleDbC...
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 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\">doc...
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...
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...
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>&lt;input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" /&gt; </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 Vie...
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 treate...
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 d...
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 dat...
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 &gt; 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 &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; 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. Beca...
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 IND...
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/cmd...
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 pri...
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 <stro...
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" }, ...
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&lt;T&gt; 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 shri...
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 ...
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.