qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
17,015
I have moved into a house with a nice Wolf-range griddle, and I would like to know what the primary advantages of the griddle are over a cast-iron skillet, including, is there anything I can do with a griddle that can not be done with a skillet? I have found that the primary downside to using the griddle is the time it takes to heat up, so when cooking for one, I would choose the skillet. The primary advantage of the griddle is that it provides a larger, easier cooking space. Am I missing other major advantages of having a griddle?
2011/08/21
[ "https://cooking.stackexchange.com/questions/17015", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/3418/" ]
Surface area is the biggest difference. You can do a much larger job on a griddle than in a skillet. Even 2 or 3 jobs at time, and when you are done there is just the griddle to clean and not several items. You will also want to pick up a '[bacon press](http://rads.stackoverflow.com/amzn/click/B00004UE7B)' to minimize splatter when you put bacon on your griddle.
I'm going to just use to frying pans ('skillets'). The lack of sides allows stuff to fall off too easily - I fried chopped onions today - and there's no carrying handle - so you can't move the griddle to plate up. The other downer - my griddle's cast iron and it's just cracked while heating it !
17,015
I have moved into a house with a nice Wolf-range griddle, and I would like to know what the primary advantages of the griddle are over a cast-iron skillet, including, is there anything I can do with a griddle that can not be done with a skillet? I have found that the primary downside to using the griddle is the time it takes to heat up, so when cooking for one, I would choose the skillet. The primary advantage of the griddle is that it provides a larger, easier cooking space. Am I missing other major advantages of having a griddle?
2011/08/21
[ "https://cooking.stackexchange.com/questions/17015", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/3418/" ]
Yes, you don't have the edge of a pan in the way when going to flip things, but it also means that you don't have a mass of metal there to add as a heat sink, which can help dramatically when pre-heating your pans, as they'll be evenly heated across their bottom more quickly (at least, compared to something of the same material, such as a cast iron skillet) More importantly, in my opinion, is that without the sides, you don't hold in moist air, so when cooking things like hash browns, you can get a better crust on 'em without steaming them.
I'm going to just use to frying pans ('skillets'). The lack of sides allows stuff to fall off too easily - I fried chopped onions today - and there's no carrying handle - so you can't move the griddle to plate up. The other downer - my griddle's cast iron and it's just cracked while heating it !
11,368,204
I followed a tutorial/instructions online to make a sidebar fixed position by making the sidebars position "fixed" and it worked fine. Now I realize that since my page has a min-width attribute, when the user scrolls sideways the content that doesn't move moves into the sidebar. So basically, I'm looking for a way to produce a fixed sidebar when your scrolling down, but when you move sideways the content doesn't jump into the sidebar. My code is kind of like the following: CSS ``` #sidebar { position:fixed; height:500px; width: 100px; background-color: blue; } #content { width:100%; box-sizing:border-box; margin-left:100px; background-color:purple; } ``` ​ Html ``` <div id="sidebar"> </div> <div id="content"> </div> ​ ``` JSFiddle: <http://jsfiddle.net/znCF3/1/> NOTE: This is not my actually code but a minified version of it because my code is really complex. Also, I can't just use a fluid layout.
2012/07/06
[ "https://Stackoverflow.com/questions/11368204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218699/" ]
Check out this fiddle: <http://jsfiddle.net/NfKca/> Modified css as: ``` #sidebar { position:fixed; height:500px; width: 100px; background-color: blue; } #content { box-sizing:border-box; background-color:purple; position:absolute; left:100px; } ```
You could set the `z-index: 1;` on the sidebar. If this doesn't help, it would be great if you could make a jsfiddle to illustrate what you mean more.
11,368,204
I followed a tutorial/instructions online to make a sidebar fixed position by making the sidebars position "fixed" and it worked fine. Now I realize that since my page has a min-width attribute, when the user scrolls sideways the content that doesn't move moves into the sidebar. So basically, I'm looking for a way to produce a fixed sidebar when your scrolling down, but when you move sideways the content doesn't jump into the sidebar. My code is kind of like the following: CSS ``` #sidebar { position:fixed; height:500px; width: 100px; background-color: blue; } #content { width:100%; box-sizing:border-box; margin-left:100px; background-color:purple; } ``` ​ Html ``` <div id="sidebar"> </div> <div id="content"> </div> ​ ``` JSFiddle: <http://jsfiddle.net/znCF3/1/> NOTE: This is not my actually code but a minified version of it because my code is really complex. Also, I can't just use a fluid layout.
2012/07/06
[ "https://Stackoverflow.com/questions/11368204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218699/" ]
As said by others, not possible with only css and html. However, you can do this with javascript/jquery. Just encase you want to use jquery to do this, first as watson said, change index of side bar (I had to make negative), just encase it jquery doesn't work for whatever reason for someone. Then add to your `<head>`: ``` <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> <!-- $(document).ready(function() { $(window).scroll(function(){ var offSet = - ($(this).scrollLeft()); $('#sidebar').css('left', offSet); }); }); //--> </script> ``` [Example](http://jsfiddle.net/znCF3/3/)
You could set the `z-index: 1;` on the sidebar. If this doesn't help, it would be great if you could make a jsfiddle to illustrate what you mean more.
11,368,204
I followed a tutorial/instructions online to make a sidebar fixed position by making the sidebars position "fixed" and it worked fine. Now I realize that since my page has a min-width attribute, when the user scrolls sideways the content that doesn't move moves into the sidebar. So basically, I'm looking for a way to produce a fixed sidebar when your scrolling down, but when you move sideways the content doesn't jump into the sidebar. My code is kind of like the following: CSS ``` #sidebar { position:fixed; height:500px; width: 100px; background-color: blue; } #content { width:100%; box-sizing:border-box; margin-left:100px; background-color:purple; } ``` ​ Html ``` <div id="sidebar"> </div> <div id="content"> </div> ​ ``` JSFiddle: <http://jsfiddle.net/znCF3/1/> NOTE: This is not my actually code but a minified version of it because my code is really complex. Also, I can't just use a fluid layout.
2012/07/06
[ "https://Stackoverflow.com/questions/11368204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218699/" ]
As said by others, not possible with only css and html. However, you can do this with javascript/jquery. Just encase you want to use jquery to do this, first as watson said, change index of side bar (I had to make negative), just encase it jquery doesn't work for whatever reason for someone. Then add to your `<head>`: ``` <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> <!-- $(document).ready(function() { $(window).scroll(function(){ var offSet = - ($(this).scrollLeft()); $('#sidebar').css('left', offSet); }); }); //--> </script> ``` [Example](http://jsfiddle.net/znCF3/3/)
Check out this fiddle: <http://jsfiddle.net/NfKca/> Modified css as: ``` #sidebar { position:fixed; height:500px; width: 100px; background-color: blue; } #content { box-sizing:border-box; background-color:purple; position:absolute; left:100px; } ```
9,453,761
I am debugging a website using firebug. The website opens a window, performs some operations and than closes it. This causes me to lose all of the firebug net history. Is there any way to prevent javastript from closing the window after its done, except changing the code?
2012/02/26
[ "https://Stackoverflow.com/questions/9453761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/847200/" ]
I haven't tried to use it, but there's a settings in FF which supposedly lets you do what you wish. Type about:config in the url bar and press enter. After a warning you'll see the list of config options. Search for dom.allow\_scripts\_to\_close\_windows and set its value to false.
You can rewrite the `open` method, which adds a `beforeunload` event. Have a look at the annotated code + bookmarklet below: Code: ``` javascript:(function(w){ var o = w.open; /* Stores original `window.open` method */ w.open = function() { /* Catches all window.open calls*/ var x = o.apply(w, arguments); /* Calls original window.open */ /* Bind beforeunload event */ x.addEventListener('beforeunload',function(e){e.preventDefault()},true); return x; } })(window); ``` Bookmarklet: ``` javascript:(function(w){var o=w.open;w.open=function(){var x=o.apply(w,arguments);x.addEventListener('beforeunload',function(e){e.preventDefault()},true);return x;}})(window); ```
35,047,356
I have a problem with a post\_save function. The function is correctly triggered but the instance doesn't contains the value insereted. I checked the function using ipdb and there is nothing wrong. Simply the ManyToManyField is empty. The code: ``` @receiver(post_save, sender=Supplier) def set_generic_locations(sender, instance, **kwargs): """ Set the generic locations for the NEW created supplier. """ created = kwargs.get('created') if created: glocations = LocationAddress.get_generic_locations() for location in glocations: instance.locations.add(location) instance.save() ``` The field used in the instance: ``` locations = models.ManyToManyField(LocationAddress, blank=True)​ ``` I don't understand why, but the locations is always empty. I use django 1.8.8 UPDATE ------ The problem is the django admin. I found an explanation here: <http://timonweb.com/posts/many-to-many-field-save-method-and-the-django-admin/> The code that solve the problem in the django admin ``` def save_related(self, request, form, formsets, change): super(SupplierAdmin, self).save_related(request, form, formsets, change) form.instance.set_generic_locations() ```
2016/01/27
[ "https://Stackoverflow.com/questions/35047356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1640213/" ]
ManyToManyFields work a little bit differently with signals because of the difference in database structures. Instead of using the post\_save signal, you need to use the [m2m\_changed](https://docs.djangoproject.com/en/1.9/ref/signals/#m2m-changed) signal
For manytomanyfield, you have to save first your parent object () and then add your
69,617,819
When I search the internet for `react-native` optimizations / best practices (**Especially for `FlatLists` which are often greedy**), I always find the advice not to use the arrow functions `<Component onPress={() => ... }`. *Example 1 :* <https://reactnative.dev/docs/optimizing-flatlist-configuration#avoid-anonymous-function-on-renderitem> : > > Move out the renderItem function to the outside of render function, so it won't recreate itself each time render function called. (...) > > > *Example 2 :* <https://blog.codemagic.io/improve-react-native-app-performance/> : > > Avoid Arrow Functions : Arrow functions are a common culprit for wasteful re-renders. Don’t use arrow functions as callbacks in your functions to render views (...) > > > *Example 3 :* <https://medium.com/wix-engineering/dealing-with-performance-issues-in-react-native-b181d0012cfa> : > > Arrow functions is another usual suspect for wasteful re-renders. Don’t use arrow functions as callbacks (such as click/tap) in your render functions (...) > > > I understand that it is recommended not to use arrow function (especially in `onPress` button and `FlatList`), and to put the components outside of the render if possible. **Good practice example :** ``` const IndexScreen = () => { const onPress = () => console.log('PRESS, change state, etc...') return ( <> <Button onPress={onPress} /> <FlatList ... renderItem={renderItem} ListFooterComponent={renderFooter} /> </> ) } const renderItem = ({ item: data }) => <Item data={data} ... /> const renderFooter = () => <Footer ... /> export default IndexScreen ``` But, often, I have other properties to integrate into my child components. The arrow function is therefore mandatory: ``` const IndexScreen = () => { const otherData = ...(usually it comes from a useContext())... <FlatList ... renderItem={({ item: data }) => renderItem(data, otherData)} /> } const renderItem = (data, otherData) => <Item data={data} otherData={otherData} /> export default IndexScreen ``` In the latter situation, are good practices followed despite the presence of an arrow function ? In summary, if I remove `otherData` (for simplicity), are these two situations strictly identical and are good practices followed ? **Situation 1 :** ``` const IndexScreen = () => { return ( <FlatList ... renderItem={renderItem} /> ) } const renderItem = ({ item: data }) => <Item data={data} ... /> export default IndexScreen ``` **=== Situation 2 ?** ``` const IndexScreen = () => { return ( <FlatList ... renderItem={({ item: data }) => renderItem(data)} /> ) } const renderItem = (data) => <Item data={data} ... /> export default IndexScreen ```
2021/10/18
[ "https://Stackoverflow.com/questions/69617819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3197378/" ]
The answer has nothing to do with arrow functions, but rather understanding reference equality why react might decide to rerender a component. You can use useCallback to wrap your function. This will cause the reference to renderItem to only update when one of your callback dependencies updates. ``` const renderItem = useCallback(()=>{ ... }, [otherdata]); ```
The first situation is ideal, because when your app code runs it will create only one `renderItem` function. In the second situation, even if it doesn't have otherProps, you're not following the good practice because a new function is created every render in this line ``` renderItem={({ item: data }) => renderItem(data)} ``` Hence, making the FlatList rerender every time. To fix it, you need to memoize the function you pass in the `renderItem` prop with `useCallback` ``` const renderItem = useCallback(({ item: data }) => { return (<Item data={data} />) }, []); ... <FlatList ... renderItem={renderItem} /> ``` so the memoized version will be created only once when the component mounts. And, if you need to inject more data in the render function, you define that data as a dependency of the `useCallback` hook to create the function only when that data changes, reducing rerenders down the tree. ``` const renderItem = useCallback(({ item: data }) => { return (<Item data={data} otherData={otherData} />) }, [otherData]); ```
69,617,819
When I search the internet for `react-native` optimizations / best practices (**Especially for `FlatLists` which are often greedy**), I always find the advice not to use the arrow functions `<Component onPress={() => ... }`. *Example 1 :* <https://reactnative.dev/docs/optimizing-flatlist-configuration#avoid-anonymous-function-on-renderitem> : > > Move out the renderItem function to the outside of render function, so it won't recreate itself each time render function called. (...) > > > *Example 2 :* <https://blog.codemagic.io/improve-react-native-app-performance/> : > > Avoid Arrow Functions : Arrow functions are a common culprit for wasteful re-renders. Don’t use arrow functions as callbacks in your functions to render views (...) > > > *Example 3 :* <https://medium.com/wix-engineering/dealing-with-performance-issues-in-react-native-b181d0012cfa> : > > Arrow functions is another usual suspect for wasteful re-renders. Don’t use arrow functions as callbacks (such as click/tap) in your render functions (...) > > > I understand that it is recommended not to use arrow function (especially in `onPress` button and `FlatList`), and to put the components outside of the render if possible. **Good practice example :** ``` const IndexScreen = () => { const onPress = () => console.log('PRESS, change state, etc...') return ( <> <Button onPress={onPress} /> <FlatList ... renderItem={renderItem} ListFooterComponent={renderFooter} /> </> ) } const renderItem = ({ item: data }) => <Item data={data} ... /> const renderFooter = () => <Footer ... /> export default IndexScreen ``` But, often, I have other properties to integrate into my child components. The arrow function is therefore mandatory: ``` const IndexScreen = () => { const otherData = ...(usually it comes from a useContext())... <FlatList ... renderItem={({ item: data }) => renderItem(data, otherData)} /> } const renderItem = (data, otherData) => <Item data={data} otherData={otherData} /> export default IndexScreen ``` In the latter situation, are good practices followed despite the presence of an arrow function ? In summary, if I remove `otherData` (for simplicity), are these two situations strictly identical and are good practices followed ? **Situation 1 :** ``` const IndexScreen = () => { return ( <FlatList ... renderItem={renderItem} /> ) } const renderItem = ({ item: data }) => <Item data={data} ... /> export default IndexScreen ``` **=== Situation 2 ?** ``` const IndexScreen = () => { return ( <FlatList ... renderItem={({ item: data }) => renderItem(data)} /> ) } const renderItem = (data) => <Item data={data} ... /> export default IndexScreen ```
2021/10/18
[ "https://Stackoverflow.com/questions/69617819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3197378/" ]
The answer has nothing to do with arrow functions, but rather understanding reference equality why react might decide to rerender a component. You can use useCallback to wrap your function. This will cause the reference to renderItem to only update when one of your callback dependencies updates. ``` const renderItem = useCallback(()=>{ ... }, [otherdata]); ```
to me as pointed out previously in other answers the issue is mainly due to the fact that if you use arrow functions inside the code, the function get redefined every time. Also this way of defining a function make this function unnamed so this is harder to track while debugging: on error stack trace you can see the name of a named function directly in the code. ``` const renderItem = useCallback( function renderItemFunction ({ item: data }) { return (<Item data={data} otherData={otherData} />) }, [otherData]); ``` this way in the stack trace of errors you should see `renderItemFunction` indication
69,617,819
When I search the internet for `react-native` optimizations / best practices (**Especially for `FlatLists` which are often greedy**), I always find the advice not to use the arrow functions `<Component onPress={() => ... }`. *Example 1 :* <https://reactnative.dev/docs/optimizing-flatlist-configuration#avoid-anonymous-function-on-renderitem> : > > Move out the renderItem function to the outside of render function, so it won't recreate itself each time render function called. (...) > > > *Example 2 :* <https://blog.codemagic.io/improve-react-native-app-performance/> : > > Avoid Arrow Functions : Arrow functions are a common culprit for wasteful re-renders. Don’t use arrow functions as callbacks in your functions to render views (...) > > > *Example 3 :* <https://medium.com/wix-engineering/dealing-with-performance-issues-in-react-native-b181d0012cfa> : > > Arrow functions is another usual suspect for wasteful re-renders. Don’t use arrow functions as callbacks (such as click/tap) in your render functions (...) > > > I understand that it is recommended not to use arrow function (especially in `onPress` button and `FlatList`), and to put the components outside of the render if possible. **Good practice example :** ``` const IndexScreen = () => { const onPress = () => console.log('PRESS, change state, etc...') return ( <> <Button onPress={onPress} /> <FlatList ... renderItem={renderItem} ListFooterComponent={renderFooter} /> </> ) } const renderItem = ({ item: data }) => <Item data={data} ... /> const renderFooter = () => <Footer ... /> export default IndexScreen ``` But, often, I have other properties to integrate into my child components. The arrow function is therefore mandatory: ``` const IndexScreen = () => { const otherData = ...(usually it comes from a useContext())... <FlatList ... renderItem={({ item: data }) => renderItem(data, otherData)} /> } const renderItem = (data, otherData) => <Item data={data} otherData={otherData} /> export default IndexScreen ``` In the latter situation, are good practices followed despite the presence of an arrow function ? In summary, if I remove `otherData` (for simplicity), are these two situations strictly identical and are good practices followed ? **Situation 1 :** ``` const IndexScreen = () => { return ( <FlatList ... renderItem={renderItem} /> ) } const renderItem = ({ item: data }) => <Item data={data} ... /> export default IndexScreen ``` **=== Situation 2 ?** ``` const IndexScreen = () => { return ( <FlatList ... renderItem={({ item: data }) => renderItem(data)} /> ) } const renderItem = (data) => <Item data={data} ... /> export default IndexScreen ```
2021/10/18
[ "https://Stackoverflow.com/questions/69617819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3197378/" ]
The first situation is ideal, because when your app code runs it will create only one `renderItem` function. In the second situation, even if it doesn't have otherProps, you're not following the good practice because a new function is created every render in this line ``` renderItem={({ item: data }) => renderItem(data)} ``` Hence, making the FlatList rerender every time. To fix it, you need to memoize the function you pass in the `renderItem` prop with `useCallback` ``` const renderItem = useCallback(({ item: data }) => { return (<Item data={data} />) }, []); ... <FlatList ... renderItem={renderItem} /> ``` so the memoized version will be created only once when the component mounts. And, if you need to inject more data in the render function, you define that data as a dependency of the `useCallback` hook to create the function only when that data changes, reducing rerenders down the tree. ``` const renderItem = useCallback(({ item: data }) => { return (<Item data={data} otherData={otherData} />) }, [otherData]); ```
to me as pointed out previously in other answers the issue is mainly due to the fact that if you use arrow functions inside the code, the function get redefined every time. Also this way of defining a function make this function unnamed so this is harder to track while debugging: on error stack trace you can see the name of a named function directly in the code. ``` const renderItem = useCallback( function renderItemFunction ({ item: data }) { return (<Item data={data} otherData={otherData} />) }, [otherData]); ``` this way in the stack trace of errors you should see `renderItemFunction` indication
49,170,893
i am creating an angular table using this example from angular material <https://material.angular.io/components/table/overview> is there anyway to export it in excel or pdf?
2018/03/08
[ "https://Stackoverflow.com/questions/49170893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6280170/" ]
In your table component.ts declare a value called `renderedData: any;` Then in your constructor subscribe to the data that has been changed in your material table. I am guessing you are using a filterable table. ``` constructor(){ this.dataSource = new MatTableDataSource(TableData); this.dataSource.connect().subscribe(d => this.renderedData = d); } ``` `npm install --save angular5-csv` In your HTML create a button `<button class="btn btn-primary" (click)="exportCsv()">Export to CSV</button>` Finally, export the changed data to a CSV ``` exportCsv(){ new Angular5Csv(this.renderedData,'Test Report'); } ``` More details about the exporter can be found here: <https://www.npmjs.com/package/angular5-csv> I hope this helps :)
You can use ngx-csv for Angular 7 works fine "<https://www.npmjs.com/package/ngx-csv>." Get the data from the table with "this.dataSource.connect().subscribe(data=>this.renderedData=data);" and then use export function.
49,170,893
i am creating an angular table using this example from angular material <https://material.angular.io/components/table/overview> is there anyway to export it in excel or pdf?
2018/03/08
[ "https://Stackoverflow.com/questions/49170893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6280170/" ]
In your table component.ts declare a value called `renderedData: any;` Then in your constructor subscribe to the data that has been changed in your material table. I am guessing you are using a filterable table. ``` constructor(){ this.dataSource = new MatTableDataSource(TableData); this.dataSource.connect().subscribe(d => this.renderedData = d); } ``` `npm install --save angular5-csv` In your HTML create a button `<button class="btn btn-primary" (click)="exportCsv()">Export to CSV</button>` Finally, export the changed data to a CSV ``` exportCsv(){ new Angular5Csv(this.renderedData,'Test Report'); } ``` More details about the exporter can be found here: <https://www.npmjs.com/package/angular5-csv> I hope this helps :)
You can use [mat-table-exporter](https://www.npmjs.com/package/mat-table-exporter) package to export in excel, csv, json or txt formats. It supports paginated tables too. Stackblitz demo: <https://stackblitz.com/edit/mte-demo>
49,170,893
i am creating an angular table using this example from angular material <https://material.angular.io/components/table/overview> is there anyway to export it in excel or pdf?
2018/03/08
[ "https://Stackoverflow.com/questions/49170893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6280170/" ]
In your table component.ts declare a value called `renderedData: any;` Then in your constructor subscribe to the data that has been changed in your material table. I am guessing you are using a filterable table. ``` constructor(){ this.dataSource = new MatTableDataSource(TableData); this.dataSource.connect().subscribe(d => this.renderedData = d); } ``` `npm install --save angular5-csv` In your HTML create a button `<button class="btn btn-primary" (click)="exportCsv()">Export to CSV</button>` Finally, export the changed data to a CSV ``` exportCsv(){ new Angular5Csv(this.renderedData,'Test Report'); } ``` More details about the exporter can be found here: <https://www.npmjs.com/package/angular5-csv> I hope this helps :)
You can use mat-table-exporter. To access the "export" method in the typescript code: ``` @ViewChild("exporter") exporter! : MatTableExporterDirective; <table mat-table matTableExporter [dataSource]="dataSource" #exporter="matTableExporter"> ```
49,170,893
i am creating an angular table using this example from angular material <https://material.angular.io/components/table/overview> is there anyway to export it in excel or pdf?
2018/03/08
[ "https://Stackoverflow.com/questions/49170893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6280170/" ]
In your table component.ts declare a value called `renderedData: any;` Then in your constructor subscribe to the data that has been changed in your material table. I am guessing you are using a filterable table. ``` constructor(){ this.dataSource = new MatTableDataSource(TableData); this.dataSource.connect().subscribe(d => this.renderedData = d); } ``` `npm install --save angular5-csv` In your HTML create a button `<button class="btn btn-primary" (click)="exportCsv()">Export to CSV</button>` Finally, export the changed data to a CSV ``` exportCsv(){ new Angular5Csv(this.renderedData,'Test Report'); } ``` More details about the exporter can be found here: <https://www.npmjs.com/package/angular5-csv> I hope this helps :)
It can be done with out using any library. For dynamic functionality do not convert html element in to csv. Such as, If would like to implement pagination etc. Then It can be done as follow: ``` exportCsv(): void { let csv = ''; for (let column = 0; column < this.columns.length; column++) { csv += this.columns[column] + ';'; csv = csv.replace(/\n/g, ''); } csv = csv.substring(0, csv.length - 1) + '\n'; const rows = this.filterdRows; for (let row = 0; row < rows.length; row++) { for (let rowElement = 0; rowElement < rows[row].length; rowElement++) { csv += rows[row][rowElement] + ';'; } csv = csv.substring(0, csv.length - 1) + '\n'; } csv = csv.substring(0, csv.length - 1) + '\n'; const docElement = document.createElement('a'); const universalBOM = '\uFEFF'; //You can edit the code for the file name according to your requirements let filename = this.filename + '_'; filename = filename.concat(this.currentDateString.toString()); const fileNameWithType = filename.concat('.csv'); docElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(universalBOM + csv); docElement.target = '_blank'; docElement.download = fileNameWithType; docElement.click(); } ```
49,170,893
i am creating an angular table using this example from angular material <https://material.angular.io/components/table/overview> is there anyway to export it in excel or pdf?
2018/03/08
[ "https://Stackoverflow.com/questions/49170893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6280170/" ]
You can use [mat-table-exporter](https://www.npmjs.com/package/mat-table-exporter) package to export in excel, csv, json or txt formats. It supports paginated tables too. Stackblitz demo: <https://stackblitz.com/edit/mte-demo>
You can use ngx-csv for Angular 7 works fine "<https://www.npmjs.com/package/ngx-csv>." Get the data from the table with "this.dataSource.connect().subscribe(data=>this.renderedData=data);" and then use export function.
49,170,893
i am creating an angular table using this example from angular material <https://material.angular.io/components/table/overview> is there anyway to export it in excel or pdf?
2018/03/08
[ "https://Stackoverflow.com/questions/49170893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6280170/" ]
You can use ngx-csv for Angular 7 works fine "<https://www.npmjs.com/package/ngx-csv>." Get the data from the table with "this.dataSource.connect().subscribe(data=>this.renderedData=data);" and then use export function.
It can be done with out using any library. For dynamic functionality do not convert html element in to csv. Such as, If would like to implement pagination etc. Then It can be done as follow: ``` exportCsv(): void { let csv = ''; for (let column = 0; column < this.columns.length; column++) { csv += this.columns[column] + ';'; csv = csv.replace(/\n/g, ''); } csv = csv.substring(0, csv.length - 1) + '\n'; const rows = this.filterdRows; for (let row = 0; row < rows.length; row++) { for (let rowElement = 0; rowElement < rows[row].length; rowElement++) { csv += rows[row][rowElement] + ';'; } csv = csv.substring(0, csv.length - 1) + '\n'; } csv = csv.substring(0, csv.length - 1) + '\n'; const docElement = document.createElement('a'); const universalBOM = '\uFEFF'; //You can edit the code for the file name according to your requirements let filename = this.filename + '_'; filename = filename.concat(this.currentDateString.toString()); const fileNameWithType = filename.concat('.csv'); docElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(universalBOM + csv); docElement.target = '_blank'; docElement.download = fileNameWithType; docElement.click(); } ```
49,170,893
i am creating an angular table using this example from angular material <https://material.angular.io/components/table/overview> is there anyway to export it in excel or pdf?
2018/03/08
[ "https://Stackoverflow.com/questions/49170893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6280170/" ]
You can use [mat-table-exporter](https://www.npmjs.com/package/mat-table-exporter) package to export in excel, csv, json or txt formats. It supports paginated tables too. Stackblitz demo: <https://stackblitz.com/edit/mte-demo>
You can use mat-table-exporter. To access the "export" method in the typescript code: ``` @ViewChild("exporter") exporter! : MatTableExporterDirective; <table mat-table matTableExporter [dataSource]="dataSource" #exporter="matTableExporter"> ```
49,170,893
i am creating an angular table using this example from angular material <https://material.angular.io/components/table/overview> is there anyway to export it in excel or pdf?
2018/03/08
[ "https://Stackoverflow.com/questions/49170893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6280170/" ]
You can use [mat-table-exporter](https://www.npmjs.com/package/mat-table-exporter) package to export in excel, csv, json or txt formats. It supports paginated tables too. Stackblitz demo: <https://stackblitz.com/edit/mte-demo>
It can be done with out using any library. For dynamic functionality do not convert html element in to csv. Such as, If would like to implement pagination etc. Then It can be done as follow: ``` exportCsv(): void { let csv = ''; for (let column = 0; column < this.columns.length; column++) { csv += this.columns[column] + ';'; csv = csv.replace(/\n/g, ''); } csv = csv.substring(0, csv.length - 1) + '\n'; const rows = this.filterdRows; for (let row = 0; row < rows.length; row++) { for (let rowElement = 0; rowElement < rows[row].length; rowElement++) { csv += rows[row][rowElement] + ';'; } csv = csv.substring(0, csv.length - 1) + '\n'; } csv = csv.substring(0, csv.length - 1) + '\n'; const docElement = document.createElement('a'); const universalBOM = '\uFEFF'; //You can edit the code for the file name according to your requirements let filename = this.filename + '_'; filename = filename.concat(this.currentDateString.toString()); const fileNameWithType = filename.concat('.csv'); docElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(universalBOM + csv); docElement.target = '_blank'; docElement.download = fileNameWithType; docElement.click(); } ```
49,170,893
i am creating an angular table using this example from angular material <https://material.angular.io/components/table/overview> is there anyway to export it in excel or pdf?
2018/03/08
[ "https://Stackoverflow.com/questions/49170893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6280170/" ]
You can use mat-table-exporter. To access the "export" method in the typescript code: ``` @ViewChild("exporter") exporter! : MatTableExporterDirective; <table mat-table matTableExporter [dataSource]="dataSource" #exporter="matTableExporter"> ```
It can be done with out using any library. For dynamic functionality do not convert html element in to csv. Such as, If would like to implement pagination etc. Then It can be done as follow: ``` exportCsv(): void { let csv = ''; for (let column = 0; column < this.columns.length; column++) { csv += this.columns[column] + ';'; csv = csv.replace(/\n/g, ''); } csv = csv.substring(0, csv.length - 1) + '\n'; const rows = this.filterdRows; for (let row = 0; row < rows.length; row++) { for (let rowElement = 0; rowElement < rows[row].length; rowElement++) { csv += rows[row][rowElement] + ';'; } csv = csv.substring(0, csv.length - 1) + '\n'; } csv = csv.substring(0, csv.length - 1) + '\n'; const docElement = document.createElement('a'); const universalBOM = '\uFEFF'; //You can edit the code for the file name according to your requirements let filename = this.filename + '_'; filename = filename.concat(this.currentDateString.toString()); const fileNameWithType = filename.concat('.csv'); docElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(universalBOM + csv); docElement.target = '_blank'; docElement.download = fileNameWithType; docElement.click(); } ```
20,932,644
I have the following [example](http://jsbin.com/ohonaYu/1/edit): ``` <div class="container"> <div class="left"></div> <div class="right"> <span class="number">1</span> <span class="number">2</span> </div> </div> ``` As you can see in the code above left div in not vertically aligned:![enter image description here](https://i.stack.imgur.com/tXM3j.png) But if I remove float: right then left div gets vertically aligned well: [example](http://jsbin.com/ohonaYu/2/edit) ![enter image description here](https://i.stack.imgur.com/Wu5CH.png) Please help me how could I make vertical align left div with right float right div? **EDIT**: Could you provide a solution without padding, margin, top, left etc?
2014/01/05
[ "https://Stackoverflow.com/questions/20932644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1006884/" ]
How about ``` select * from `post_plus` left join `post` on `post`.`id` = `post_plus`.`news_id` where `post`.`id` IS NULL ```
You can do this with a left join ``` SELECT p.id, pp.id FROM post p LEFT JOIN post_plus pp ON (pp.news_id = p.id) ``` you will get all rows from post and pp.id will be null on those rows that don't match. if you append a where clause you will get only the ones that do not match ``` SELECT p.id, pp.id FROM post p LEFT JOIN post_plus pp ON (pp.news_id = p.id) where pp.id is null ``` (tested)
20,932,644
I have the following [example](http://jsbin.com/ohonaYu/1/edit): ``` <div class="container"> <div class="left"></div> <div class="right"> <span class="number">1</span> <span class="number">2</span> </div> </div> ``` As you can see in the code above left div in not vertically aligned:![enter image description here](https://i.stack.imgur.com/tXM3j.png) But if I remove float: right then left div gets vertically aligned well: [example](http://jsbin.com/ohonaYu/2/edit) ![enter image description here](https://i.stack.imgur.com/Wu5CH.png) Please help me how could I make vertical align left div with right float right div? **EDIT**: Could you provide a solution without padding, margin, top, left etc?
2014/01/05
[ "https://Stackoverflow.com/questions/20932644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1006884/" ]
How about ``` select * from `post_plus` left join `post` on `post`.`id` = `post_plus`.`news_id` where `post`.`id` IS NULL ```
Or you can also use this ``` select * from post t1 join post_plus t2 on t1.id <> t2.news_id ```
20,932,644
I have the following [example](http://jsbin.com/ohonaYu/1/edit): ``` <div class="container"> <div class="left"></div> <div class="right"> <span class="number">1</span> <span class="number">2</span> </div> </div> ``` As you can see in the code above left div in not vertically aligned:![enter image description here](https://i.stack.imgur.com/tXM3j.png) But if I remove float: right then left div gets vertically aligned well: [example](http://jsbin.com/ohonaYu/2/edit) ![enter image description here](https://i.stack.imgur.com/Wu5CH.png) Please help me how could I make vertical align left div with right float right div? **EDIT**: Could you provide a solution without padding, margin, top, left etc?
2014/01/05
[ "https://Stackoverflow.com/questions/20932644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1006884/" ]
You can do this with a left join ``` SELECT p.id, pp.id FROM post p LEFT JOIN post_plus pp ON (pp.news_id = p.id) ``` you will get all rows from post and pp.id will be null on those rows that don't match. if you append a where clause you will get only the ones that do not match ``` SELECT p.id, pp.id FROM post p LEFT JOIN post_plus pp ON (pp.news_id = p.id) where pp.id is null ``` (tested)
Or you can also use this ``` select * from post t1 join post_plus t2 on t1.id <> t2.news_id ```
28,318,912
I need to write several formulas in CSS (or is there some other way?) and integrate it on my quiz website for students. I already found some interesting examples in here: <http://www.periodni.com/mathematical_and_chemical_equations_on_web.html> But I need one more, as can be seen in this picture: [![](https://i.stack.imgur.com/u7deK.gif)](http://www.docbrown.info/page15/Image166.gif)
2015/02/04
[ "https://Stackoverflow.com/questions/28318912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4527585/" ]
I upvoted Nplay comment, easychem seems really fun. Filthy, dirty way to achieve it with HTML (don't try this at home please) : ```html <p> <span style="visibility: hidden;">CH<sub>3</sub> - </span>CH<sub>3</sub><br/> <span style="visibility: hidden;">CH<sub>3</sub> - </span>|<br/> CH<sub>3</sub> - C - CH<sub>3</sub><br/> <span style="visibility: hidden;">CH<sub>3</sub> - </span>|<br/> <span style="visibility: hidden;">CH<sub>3</sub> - </span>CH<sub>3</sub><br/> </p> ```
``` CO<sub>2</sub><br> H<sub>2</sub> + O --->H<sub>2</sub>O ``` CO2 H2 + O --->H2O
60,553,264
I need to compare the roman letters and get the correct integer out of it. If I'm correct, there should be a way to compare the hashmap key with the arraylist element and if they match, get the associated value from the key. The return 2020 is there just for test purposes, since I wrote a JUnit test in a different class. It can be ignored for now. I hope someone could give me a hint, since I wouldn't like to use the solutions from the web, because I need to get better with algorithms. ``` package com.company; import java.util.*; public class Main { static HashMap<String, Integer> romanNumbers = new HashMap<String, Integer>(); static { romanNumbers.put("I", 1); romanNumbers.put("V", 5); romanNumbers.put("X", 10); romanNumbers.put("L", 50); romanNumbers.put("C", 100); romanNumbers.put("D", 500); romanNumbers.put("M", 1000); } public static void main(String[] args) { romanToArabic("MMXX"); } static int romanToArabic(String roman) { ArrayList romanLetters = new ArrayList(); roman = roman.toUpperCase(); for (int i = 0; i < roman.length(); i++) { char c = roman.charAt(i); romanLetters.add(c); } // [M, M, X, X] System.out.println(romanLetters); // iterates over the romanLetters for (int i = 0; i < romanLetters.size(); i++) { System.out.println(romanLetters.get(i)); } // retrive keys and values for (Map.Entry romanNumbersKey : romanNumbers.entrySet()) { String key = (String) romanNumbersKey.getKey(); Object value = romanNumbersKey.getValue(); System.out.println(key + " " + value); } return 2020; } } ```
2020/03/05
[ "https://Stackoverflow.com/questions/60553264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13014882/" ]
As you said Apple does not provide a clear answer in the documentation. But, from the Apple WWDC 2019 conference video: <https://developer.apple.com/videos/play/wwdc2019/302/?time=637> > > "However, should you not return a 200 response, we will retry up to > three times to resend the notification to you" > > > Some manual testing suggests that they retry message for one hour.
Apple will attempt to retry 3 times over 3 days.
60,553,264
I need to compare the roman letters and get the correct integer out of it. If I'm correct, there should be a way to compare the hashmap key with the arraylist element and if they match, get the associated value from the key. The return 2020 is there just for test purposes, since I wrote a JUnit test in a different class. It can be ignored for now. I hope someone could give me a hint, since I wouldn't like to use the solutions from the web, because I need to get better with algorithms. ``` package com.company; import java.util.*; public class Main { static HashMap<String, Integer> romanNumbers = new HashMap<String, Integer>(); static { romanNumbers.put("I", 1); romanNumbers.put("V", 5); romanNumbers.put("X", 10); romanNumbers.put("L", 50); romanNumbers.put("C", 100); romanNumbers.put("D", 500); romanNumbers.put("M", 1000); } public static void main(String[] args) { romanToArabic("MMXX"); } static int romanToArabic(String roman) { ArrayList romanLetters = new ArrayList(); roman = roman.toUpperCase(); for (int i = 0; i < roman.length(); i++) { char c = roman.charAt(i); romanLetters.add(c); } // [M, M, X, X] System.out.println(romanLetters); // iterates over the romanLetters for (int i = 0; i < romanLetters.size(); i++) { System.out.println(romanLetters.get(i)); } // retrive keys and values for (Map.Entry romanNumbersKey : romanNumbers.entrySet()) { String key = (String) romanNumbersKey.getKey(); Object value = romanNumbersKey.getValue(); System.out.println(key + " " + value); } return 2020; } } ```
2020/03/05
[ "https://Stackoverflow.com/questions/60553264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13014882/" ]
The retry policy for App Store server notifications depends on the version of the server notification. It retries as follows: > > * For version 1 notifications, it retries three times; at 6, 24, and 48 hours after the previous attempt. > * For version 2 notifications, it retries five times; at 1, 12, 24, 48, and 72 hours after the previous attempt. > > > See [here](https://developer.apple.com/documentation/appstoreservernotifications/responding_to_app_store_server_notifications) for details.
As you said Apple does not provide a clear answer in the documentation. But, from the Apple WWDC 2019 conference video: <https://developer.apple.com/videos/play/wwdc2019/302/?time=637> > > "However, should you not return a 200 response, we will retry up to > three times to resend the notification to you" > > > Some manual testing suggests that they retry message for one hour.
60,553,264
I need to compare the roman letters and get the correct integer out of it. If I'm correct, there should be a way to compare the hashmap key with the arraylist element and if they match, get the associated value from the key. The return 2020 is there just for test purposes, since I wrote a JUnit test in a different class. It can be ignored for now. I hope someone could give me a hint, since I wouldn't like to use the solutions from the web, because I need to get better with algorithms. ``` package com.company; import java.util.*; public class Main { static HashMap<String, Integer> romanNumbers = new HashMap<String, Integer>(); static { romanNumbers.put("I", 1); romanNumbers.put("V", 5); romanNumbers.put("X", 10); romanNumbers.put("L", 50); romanNumbers.put("C", 100); romanNumbers.put("D", 500); romanNumbers.put("M", 1000); } public static void main(String[] args) { romanToArabic("MMXX"); } static int romanToArabic(String roman) { ArrayList romanLetters = new ArrayList(); roman = roman.toUpperCase(); for (int i = 0; i < roman.length(); i++) { char c = roman.charAt(i); romanLetters.add(c); } // [M, M, X, X] System.out.println(romanLetters); // iterates over the romanLetters for (int i = 0; i < romanLetters.size(); i++) { System.out.println(romanLetters.get(i)); } // retrive keys and values for (Map.Entry romanNumbersKey : romanNumbers.entrySet()) { String key = (String) romanNumbersKey.getKey(); Object value = romanNumbersKey.getValue(); System.out.println(key + " " + value); } return 2020; } } ```
2020/03/05
[ "https://Stackoverflow.com/questions/60553264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13014882/" ]
Refer: <https://developer.apple.com/documentation/appstoreservernotifications/your_server> Upon receiving a server notification, respond to the App Store with an HTTP status code of 200 if the post was successful. If the post was unsuccessful, send HTTP 50x or 40x to have the App Store retry the notification. If the App Store server doesn’t receive a 200 response from your server after the initial notification attempt, it retries three times. App Store retries at 6, 24, and 48 hours after its initial attempt. While App Store server notifications report state changes in real-time, you can always initiate receipt validation to get an up-to-date receipt. For more information
Apple will attempt to retry 3 times over 3 days.
60,553,264
I need to compare the roman letters and get the correct integer out of it. If I'm correct, there should be a way to compare the hashmap key with the arraylist element and if they match, get the associated value from the key. The return 2020 is there just for test purposes, since I wrote a JUnit test in a different class. It can be ignored for now. I hope someone could give me a hint, since I wouldn't like to use the solutions from the web, because I need to get better with algorithms. ``` package com.company; import java.util.*; public class Main { static HashMap<String, Integer> romanNumbers = new HashMap<String, Integer>(); static { romanNumbers.put("I", 1); romanNumbers.put("V", 5); romanNumbers.put("X", 10); romanNumbers.put("L", 50); romanNumbers.put("C", 100); romanNumbers.put("D", 500); romanNumbers.put("M", 1000); } public static void main(String[] args) { romanToArabic("MMXX"); } static int romanToArabic(String roman) { ArrayList romanLetters = new ArrayList(); roman = roman.toUpperCase(); for (int i = 0; i < roman.length(); i++) { char c = roman.charAt(i); romanLetters.add(c); } // [M, M, X, X] System.out.println(romanLetters); // iterates over the romanLetters for (int i = 0; i < romanLetters.size(); i++) { System.out.println(romanLetters.get(i)); } // retrive keys and values for (Map.Entry romanNumbersKey : romanNumbers.entrySet()) { String key = (String) romanNumbersKey.getKey(); Object value = romanNumbersKey.getValue(); System.out.println(key + " " + value); } return 2020; } } ```
2020/03/05
[ "https://Stackoverflow.com/questions/60553264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13014882/" ]
The retry policy for App Store server notifications depends on the version of the server notification. It retries as follows: > > * For version 1 notifications, it retries three times; at 6, 24, and 48 hours after the previous attempt. > * For version 2 notifications, it retries five times; at 1, 12, 24, 48, and 72 hours after the previous attempt. > > > See [here](https://developer.apple.com/documentation/appstoreservernotifications/responding_to_app_store_server_notifications) for details.
Apple will attempt to retry 3 times over 3 days.
60,553,264
I need to compare the roman letters and get the correct integer out of it. If I'm correct, there should be a way to compare the hashmap key with the arraylist element and if they match, get the associated value from the key. The return 2020 is there just for test purposes, since I wrote a JUnit test in a different class. It can be ignored for now. I hope someone could give me a hint, since I wouldn't like to use the solutions from the web, because I need to get better with algorithms. ``` package com.company; import java.util.*; public class Main { static HashMap<String, Integer> romanNumbers = new HashMap<String, Integer>(); static { romanNumbers.put("I", 1); romanNumbers.put("V", 5); romanNumbers.put("X", 10); romanNumbers.put("L", 50); romanNumbers.put("C", 100); romanNumbers.put("D", 500); romanNumbers.put("M", 1000); } public static void main(String[] args) { romanToArabic("MMXX"); } static int romanToArabic(String roman) { ArrayList romanLetters = new ArrayList(); roman = roman.toUpperCase(); for (int i = 0; i < roman.length(); i++) { char c = roman.charAt(i); romanLetters.add(c); } // [M, M, X, X] System.out.println(romanLetters); // iterates over the romanLetters for (int i = 0; i < romanLetters.size(); i++) { System.out.println(romanLetters.get(i)); } // retrive keys and values for (Map.Entry romanNumbersKey : romanNumbers.entrySet()) { String key = (String) romanNumbersKey.getKey(); Object value = romanNumbersKey.getValue(); System.out.println(key + " " + value); } return 2020; } } ```
2020/03/05
[ "https://Stackoverflow.com/questions/60553264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13014882/" ]
The retry policy for App Store server notifications depends on the version of the server notification. It retries as follows: > > * For version 1 notifications, it retries three times; at 6, 24, and 48 hours after the previous attempt. > * For version 2 notifications, it retries five times; at 1, 12, 24, 48, and 72 hours after the previous attempt. > > > See [here](https://developer.apple.com/documentation/appstoreservernotifications/responding_to_app_store_server_notifications) for details.
Refer: <https://developer.apple.com/documentation/appstoreservernotifications/your_server> Upon receiving a server notification, respond to the App Store with an HTTP status code of 200 if the post was successful. If the post was unsuccessful, send HTTP 50x or 40x to have the App Store retry the notification. If the App Store server doesn’t receive a 200 response from your server after the initial notification attempt, it retries three times. App Store retries at 6, 24, and 48 hours after its initial attempt. While App Store server notifications report state changes in real-time, you can always initiate receipt validation to get an up-to-date receipt. For more information
41,433,932
I'm interested in instantiating a pool of workers, `the_pool`, using `multiprocessing.Pool` that uses a `Queue` for communication. However, each worker has an argument, `role`, that is unique to that worker and needs to be provided during worker initialization. This constraint is imposed by an API I'm interfacing with, and so cannot be worked around. If I didn't need a Queue, I could just iterate over a list of `role` values and invoke `apply_async`, like so: ``` [the_pool.apply_async(worker_main, role) for role in roles] ``` Unfortunately, `Queue` object can only be passed to pools during pool instantiation, as in: ``` the_pool = multiprocessing.Pool(3, worker_main, (the_queue,)) ``` Attempting to pass a `Queue` via the arguments to `apply_async` causes a runtime error. In the following example, adapted from [this question](https://stackoverflow.com/questions/41413055/how-might-i-launch-each-worker-in-a-multiprocessing-pool-in-a-new-shell), we attempt to instantiate a pool of three workers. But the example fails, because there is no way to get a role element from `roles` into the `initargs` for the pool. ``` import os import time import multiprocessing # A dummy function representing some fixed functionality. def do_something(x): print('I got a thing:', x) # A main function, run by our workers. (Remove role arg for working example) def worker_main(queue, role): print('The worker at', os.getpid(), 'has role', role, ' and is initialized.') # Use role in some way. (Comment out for working example) do_something(role) while True: # Block until something is in the queue. item = queue.get(True) print(item) time.sleep(0.5) if __name__ == '__main__': # Define some roles for our workers. roles = [1, 2, 3] # Instantiate a Queue for communication. the_queue = multiprocessing.Queue() # Build a Pool of workers, each running worker_main. # PROBLEM: Next line breaks - how do I pass one element of roles to each worker? the_pool = multiprocessing.Pool(3, worker_main, (the_queue,)) # Iterate, sending data via the Queue. [the_queue.put('Insert useful message here') for _ in range(5)] worker_pool.close() worker_pool.join() time.sleep(10) ``` One trivial work-around is to include a second `Queue` in `initargs` which only serves to communicate the role of each worker, and block the workers execution until it receives a role via that queue. This, however, introduces an additional queue that should not be necessary. Relevant documentation is [here](https://docs.python.org/2/library/multiprocessing.html). Guidance and advice is greatly appreciated.
2017/01/02
[ "https://Stackoverflow.com/questions/41433932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3417688/" ]
Why not use two worker functions, one for just for initialization? Like: ``` def worker_init(q): global queue queue = q def worker_main(role): # use the global `queue` freely here ``` Initialization is much the same as what you showed, except call `worker_init`: ``` the_pool = multiprocessing.Pool(3, worker_init, (the_queue,)) ``` Initialization is done exactly once per worker process, and each process persists until the `Pool` terminates. To get work done, do exactly what you wanted to do: ``` [the_pool.apply_async(worker_main, role) for role in roles] ``` There's no need to pass `the_queue` too - each worker process already learned about it during initialization.
You can just create queue with roles: ``` import os import time import multiprocessing # A dummy function representing some fixed functionality. def do_something(x): print('I got a thing:', x) # A main function, run by our workers. (Remove role arg for working example) def worker_main(queue, roles): role = roles.get() print('The worker at', os.getpid(), 'has role', role, ' and is initialized.') # Use role in some way. (Comment out for working example) do_something(role) while True: # Block until something is in the queue. item = queue.get(True) print(item) time.sleep(0.5) if __name__ == '__main__': # Define some roles for our workers. roles = [1, 2, 3] # Instantiate a Queue for communication. the_queue = multiprocessing.Queue() roles_queue = multiprocessing.Queue() for role in roles: roles_queue.put(role) # Build a Pool of workers, each running worker_main. # PROBLEM: Next line breaks - how do I pass one element of roles to each worker? the_pool = multiprocessing.Pool(3, worker_main, (the_queue, roles_queue)) # Iterate, sending data via the Queue. [the_queue.put('Insert useful message here') for _ in range(5)] worker_pool.close() worker_pool.join() time.sleep(10) ```
74,378,006
I do host a gitea server and access git via https. The certificate is **not** self-signed, but from a proper CA, User Trust (<https://www.tbs-certificates.co.uk/FAQ/en/racine-USERTrustRSACertificationAuthority.html>). I'm using the latest git client for windows (2.38.1, 64bit) When i do a `git pull`, the error `unable to get local issuer certificate` is shown. [![enter image description here](https://i.stack.imgur.com/jVkdg.png)](https://i.stack.imgur.com/jVkdg.png) I do understand that git by default uses openssl and the certificate list via the file **ca-bundle.trust** for validating certificates. The strange thing is that git actually contains the root certificate, but it's not exactly the same. The certificate which is part of the ca-bundle.trust file has some additional content (Marked in green) [![enter image description here](https://i.stack.imgur.com/F1Z1Z.png)](https://i.stack.imgur.com/F1Z1Z.png) When i compare the properties of the two certificates, i don't see any difference, but i assume this is the reason why git does reject the certificate. Certificates in case someone wants to have a look at it: Official User Trust root certificate ==================================== ``` -----BEGIN CERTIFICATE----- MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B 3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/ Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2 VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT 79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6 c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3 ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs 8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/ qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG jjxDah2nGN59PRbxYvnKkKj9 -----END CERTIFICATE----- ``` Root certificate which is part of the ca-bundle.trust file from git =================================================================== ``` -----BEGIN TRUSTED CERTIFICATE----- MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B 3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/ Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2 VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT 79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6 c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3 ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs 8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/ qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG jjxDah2nGN59PRbxYvnKkKj9MD0wFAYIKwYBBQUHAwQGCCsGAQUFBwMBDCVVU0VS VHJ1c3QgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5 -----END TRUSTED CERTIFICATE----- ``` Question ======== * Why does git not have the exact same root certificate as the one from User Trust? * What is in the additional content in the certificate file? Answer ====== As mentioned in a comment by user "qwerty 1999", the command `git config --global http.sslbackend schannel` can be used to force git to use the windows certificate store which solves my problem since the "User Trust" root certificate is part of the certificate store by default. I still don't understand why git doesn't use the root certificate provided by "User Trust CA". This would avoid having to apply this workaround.
2022/11/09
[ "https://Stackoverflow.com/questions/74378006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1155873/" ]
Make a typed getter so it has proper type and you don't have to store it ``` abstract class AbstractView { get ctx(): typeof AbstractView { return this.constructor as typeof AbstractView; } static getStatus() : string { return 'hi'; } } class TestView extends AbstractView { static getStatus() : string { return 'hi2'; } } console.log(new TestView().ctx.getStatus()) // > "hi2" ``` <https://www.typescriptlang.org/play?#code/FAQwRgzgLgTiDGUAE8A2IISQQUrBUAagJYCmA7kgN7BJ1IDmpyiAHgBQCUAXElAJ4AHUgHsAZjjxxEJCtVr1FMZgFcYAOz4ALYhAB08EeugwViETCQY+Q0RNwmCs8gG4FdAL7uk0EFGLwjMwAylB+KhBcSLwmxOoM3jSKSqoaSADkOuluil5eaBhYACqk0M5IpKxQpOoAJlgO+DJklEn0vv6BTFCh4ZGc0T6wcQmKbclIylBqmpnEAEzZ3nnAwIbGIqikeqgiDOzqciVlLVwGUKx63b3T-ZxAA>
The error message is telling you the problem: > > "Property 'ctx' is missing in type **'typeof AbstractView'** but required in type **'AbstractView'**" > > > Make them match! The following compiles, though storing the constructor looks pretty weird. ``` abstract class AbstractView { ctx : typeof AbstractView; constructor() { this.ctx = this.constructor as typeof AbstractView; } } ```
8,927
I work in a small but growing team of UX designers developing a suite of web applications. It's become obvious that we would benefit from a common pattern library, but are unsure how to get started or what tool we should use. We want something that we can collaborate on and also share with visual designers and developers - so adding detail such as notes, graphics and snippets of code would be useful. Has anyone had experience of building a library like this, do you have any tips or recommendations?
2011/07/12
[ "https://ux.stackexchange.com/questions/8927", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4500/" ]
There are several [design pattern repositories listed on Konigi web](http://konigi.com/wiki/design-pattern-repositories). From these, [Patternry](http://patternry.com/) allows you to create public and private collections of patterns.
Not a tool that I have got round to using myself yet but [Quince](http://quince.infragistics.com/) seems interesting. Personally I have found that having my own patterns sketchbook has been very useful, but I think you are looking for something more advanced and collaborative?
8,927
I work in a small but growing team of UX designers developing a suite of web applications. It's become obvious that we would benefit from a common pattern library, but are unsure how to get started or what tool we should use. We want something that we can collaborate on and also share with visual designers and developers - so adding detail such as notes, graphics and snippets of code would be useful. Has anyone had experience of building a library like this, do you have any tips or recommendations?
2011/07/12
[ "https://ux.stackexchange.com/questions/8927", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4500/" ]
We have put together our own Wiki-based pattern library that contains screenshots, descriptions of use-cases, and notes on variations of the element/widget. The intention of the library was to enforce standardized designs across the different applications. In this regard, it has been of limited success. I attribute this to: * Too many items: we made an attempt at defining every element we used across the applications. * Not enough information about each item: this is likely a result of the first point. There were details like sizing, relationships of elements in compound widgets, etc. that would have been helpful. Ultimately, it seems like we would have gotten better results from making sure we had a repository of fully realized and reusable code for most simple elements (buttons, dropdowns, etc.), combined with a fully detailed pattern library for more complex widgets (lightboxes, lookups, tables, etc.) that needed more explanation of use cases and that would be liable to have multiple variations.
Not a tool that I have got round to using myself yet but [Quince](http://quince.infragistics.com/) seems interesting. Personally I have found that having my own patterns sketchbook has been very useful, but I think you are looking for something more advanced and collaborative?
8,927
I work in a small but growing team of UX designers developing a suite of web applications. It's become obvious that we would benefit from a common pattern library, but are unsure how to get started or what tool we should use. We want something that we can collaborate on and also share with visual designers and developers - so adding detail such as notes, graphics and snippets of code would be useful. Has anyone had experience of building a library like this, do you have any tips or recommendations?
2011/07/12
[ "https://ux.stackexchange.com/questions/8927", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4500/" ]
We currently use a wiki that we have customized. It allows us to create detailed specs (flow charts, images, code snippets, comments, a history etc) that anyone with an account can access. Within this we have pixel specs and a library of common UI elements that are linked to pages (if needed) that explain the interaction in greater depth.
There's a market for this type of product. We've done a lot of research on it and haven't found one that really fits the bill yet. In the past two org's I've worked on, we've built skunkworks pattern/component libraries by hand...typically a loose mix of PHP includes. We're toying with the idea of building some custom WordPress components for the task. 'Officially' it's usually a mess of products. SharePoint to maintain wireframes. Perforce to maintain code snippets. Random PDFs scattered about with visual design spec's. Email boxes full of discussions. It's a real mess.
8,927
I work in a small but growing team of UX designers developing a suite of web applications. It's become obvious that we would benefit from a common pattern library, but are unsure how to get started or what tool we should use. We want something that we can collaborate on and also share with visual designers and developers - so adding detail such as notes, graphics and snippets of code would be useful. Has anyone had experience of building a library like this, do you have any tips or recommendations?
2011/07/12
[ "https://ux.stackexchange.com/questions/8927", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4500/" ]
There are several [design pattern repositories listed on Konigi web](http://konigi.com/wiki/design-pattern-repositories). From these, [Patternry](http://patternry.com/) allows you to create public and private collections of patterns.
We currently use a wiki that we have customized. It allows us to create detailed specs (flow charts, images, code snippets, comments, a history etc) that anyone with an account can access. Within this we have pixel specs and a library of common UI elements that are linked to pages (if needed) that explain the interaction in greater depth.
8,927
I work in a small but growing team of UX designers developing a suite of web applications. It's become obvious that we would benefit from a common pattern library, but are unsure how to get started or what tool we should use. We want something that we can collaborate on and also share with visual designers and developers - so adding detail such as notes, graphics and snippets of code would be useful. Has anyone had experience of building a library like this, do you have any tips or recommendations?
2011/07/12
[ "https://ux.stackexchange.com/questions/8927", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4500/" ]
We currently use a wiki that we have customized. It allows us to create detailed specs (flow charts, images, code snippets, comments, a history etc) that anyone with an account can access. Within this we have pixel specs and a library of common UI elements that are linked to pages (if needed) that explain the interaction in greater depth.
I've worked with various approaches to such libraries from creating graffle stencils to full design repos complete with wikis and working code widgets. If you have the resource and time, the latter does have some real benefits as fully coded examples can be useful in clarifying the patterns more comprehensively e.g. you can see how elements are not only rendered by how they behave on interaction. A compartmentalised approach to your coded pattern library means you can also scoop out the examples and play around with variants on colour etc for your testing. Creating the patterns in actual working code and hosting them online, where your whole team can access them, also pays dividends. However, saying all this, I appreciate going to this level of detail has an overhead and is not always appropriate for all organisations and projects... sometimes some astute screen grabbing and consistent notation can suffice; the trick then is to get it into a format that is easy to navigate and access, otherwise you are less likely to use it ;)
8,927
I work in a small but growing team of UX designers developing a suite of web applications. It's become obvious that we would benefit from a common pattern library, but are unsure how to get started or what tool we should use. We want something that we can collaborate on and also share with visual designers and developers - so adding detail such as notes, graphics and snippets of code would be useful. Has anyone had experience of building a library like this, do you have any tips or recommendations?
2011/07/12
[ "https://ux.stackexchange.com/questions/8927", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4500/" ]
Not a tool that I have got round to using myself yet but [Quince](http://quince.infragistics.com/) seems interesting. Personally I have found that having my own patterns sketchbook has been very useful, but I think you are looking for something more advanced and collaborative?
I've worked with various approaches to such libraries from creating graffle stencils to full design repos complete with wikis and working code widgets. If you have the resource and time, the latter does have some real benefits as fully coded examples can be useful in clarifying the patterns more comprehensively e.g. you can see how elements are not only rendered by how they behave on interaction. A compartmentalised approach to your coded pattern library means you can also scoop out the examples and play around with variants on colour etc for your testing. Creating the patterns in actual working code and hosting them online, where your whole team can access them, also pays dividends. However, saying all this, I appreciate going to this level of detail has an overhead and is not always appropriate for all organisations and projects... sometimes some astute screen grabbing and consistent notation can suffice; the trick then is to get it into a format that is easy to navigate and access, otherwise you are less likely to use it ;)
8,927
I work in a small but growing team of UX designers developing a suite of web applications. It's become obvious that we would benefit from a common pattern library, but are unsure how to get started or what tool we should use. We want something that we can collaborate on and also share with visual designers and developers - so adding detail such as notes, graphics and snippets of code would be useful. Has anyone had experience of building a library like this, do you have any tips or recommendations?
2011/07/12
[ "https://ux.stackexchange.com/questions/8927", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4500/" ]
We have put together our own Wiki-based pattern library that contains screenshots, descriptions of use-cases, and notes on variations of the element/widget. The intention of the library was to enforce standardized designs across the different applications. In this regard, it has been of limited success. I attribute this to: * Too many items: we made an attempt at defining every element we used across the applications. * Not enough information about each item: this is likely a result of the first point. There were details like sizing, relationships of elements in compound widgets, etc. that would have been helpful. Ultimately, it seems like we would have gotten better results from making sure we had a repository of fully realized and reusable code for most simple elements (buttons, dropdowns, etc.), combined with a fully detailed pattern library for more complex widgets (lightboxes, lookups, tables, etc.) that needed more explanation of use cases and that would be liable to have multiple variations.
This depends on the tools you're using. Usually you can create a master file placed in a shared location. I've seen this done with Powerpoint (just a ppt with elements), Visio (custom stencils), Axure RP (widget libraries / shared project) and Illustrator (don't know how it was done exactly).
8,927
I work in a small but growing team of UX designers developing a suite of web applications. It's become obvious that we would benefit from a common pattern library, but are unsure how to get started or what tool we should use. We want something that we can collaborate on and also share with visual designers and developers - so adding detail such as notes, graphics and snippets of code would be useful. Has anyone had experience of building a library like this, do you have any tips or recommendations?
2011/07/12
[ "https://ux.stackexchange.com/questions/8927", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4500/" ]
We have put together our own Wiki-based pattern library that contains screenshots, descriptions of use-cases, and notes on variations of the element/widget. The intention of the library was to enforce standardized designs across the different applications. In this regard, it has been of limited success. I attribute this to: * Too many items: we made an attempt at defining every element we used across the applications. * Not enough information about each item: this is likely a result of the first point. There were details like sizing, relationships of elements in compound widgets, etc. that would have been helpful. Ultimately, it seems like we would have gotten better results from making sure we had a repository of fully realized and reusable code for most simple elements (buttons, dropdowns, etc.), combined with a fully detailed pattern library for more complex widgets (lightboxes, lookups, tables, etc.) that needed more explanation of use cases and that would be liable to have multiple variations.
There's a market for this type of product. We've done a lot of research on it and haven't found one that really fits the bill yet. In the past two org's I've worked on, we've built skunkworks pattern/component libraries by hand...typically a loose mix of PHP includes. We're toying with the idea of building some custom WordPress components for the task. 'Officially' it's usually a mess of products. SharePoint to maintain wireframes. Perforce to maintain code snippets. Random PDFs scattered about with visual design spec's. Email boxes full of discussions. It's a real mess.
8,927
I work in a small but growing team of UX designers developing a suite of web applications. It's become obvious that we would benefit from a common pattern library, but are unsure how to get started or what tool we should use. We want something that we can collaborate on and also share with visual designers and developers - so adding detail such as notes, graphics and snippets of code would be useful. Has anyone had experience of building a library like this, do you have any tips or recommendations?
2011/07/12
[ "https://ux.stackexchange.com/questions/8927", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4500/" ]
There are several [design pattern repositories listed on Konigi web](http://konigi.com/wiki/design-pattern-repositories). From these, [Patternry](http://patternry.com/) allows you to create public and private collections of patterns.
There's a market for this type of product. We've done a lot of research on it and haven't found one that really fits the bill yet. In the past two org's I've worked on, we've built skunkworks pattern/component libraries by hand...typically a loose mix of PHP includes. We're toying with the idea of building some custom WordPress components for the task. 'Officially' it's usually a mess of products. SharePoint to maintain wireframes. Perforce to maintain code snippets. Random PDFs scattered about with visual design spec's. Email boxes full of discussions. It's a real mess.
8,927
I work in a small but growing team of UX designers developing a suite of web applications. It's become obvious that we would benefit from a common pattern library, but are unsure how to get started or what tool we should use. We want something that we can collaborate on and also share with visual designers and developers - so adding detail such as notes, graphics and snippets of code would be useful. Has anyone had experience of building a library like this, do you have any tips or recommendations?
2011/07/12
[ "https://ux.stackexchange.com/questions/8927", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4500/" ]
Internally here we use [confluence](http://www.atlassian.com/software/confluence/). One of our guys is in charge of keeping it in order, and we just all post use it as a way to reference the correct UI to use in a certain situation. That being said, we also use it as a discussion point when we believe an element is wrong or out-of-date.
There's a market for this type of product. We've done a lot of research on it and haven't found one that really fits the bill yet. In the past two org's I've worked on, we've built skunkworks pattern/component libraries by hand...typically a loose mix of PHP includes. We're toying with the idea of building some custom WordPress components for the task. 'Officially' it's usually a mess of products. SharePoint to maintain wireframes. Perforce to maintain code snippets. Random PDFs scattered about with visual design spec's. Email boxes full of discussions. It's a real mess.
49,109
From death to brittleness? Two bodies, on a bed, in an embrace. Windows and doors closed, so little to no air and light, but not completely air/light tight. No scavenger animals/rodents, but bugs would obviously be present. Humid (tropical rain-forest) environment. The aim is to have my characters stumble across this old castle, and find the bones of two people on the bed. I don't care if the bones are touched they would fall to dust, or if they are moved slightly/disturbed by bugs, or even if some of the bones are dust already, as long as it can be made out that its two skeletons embraced together. (and if not clearly embraced, its at least clear that its two skeletons) (i know "dust" isn't the appropriate term here, but you get what I mean?) How many years could this take? Thankyou EDIT: Just wanted to re-iterate, I don't so much care about the decomposing bodily fluids and flesh. I know that will decompose and be eaten by bugs and will stain the sheets upon decomposition. I know that mummification is out, as of the humidity. I'm wanting to know what happens to the BONES well after the process of rotting flesh is done. I know the joints wont stay together, and I know that the bugs will move the bones around a bit if they are eating the flesh. But say that, after a month or so of the people being dead, their bones would still be on the bed, and it would be obvious that two people were on the bed together, even if not embracing? how long would it take before their bones became so fragile and brittle that they would turn to "dust." or upon discovery of the bones, and disturbing the bones, would they disintegrate to dust upon a rush or air or a touch of hand?
2016/07/31
[ "https://worldbuilding.stackexchange.com/questions/49109", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/21849/" ]
Not as long as you might think, especially if the room is not tightly sealed. Bugs will eat a corpse pretty efficiently, even without animals. If you are looking for this to be some romantic scene because there isn't viscera, well, it's going to smell if it's been sealed, no matter what. Even if they are bones. The bed will be stained with the fluids of their bodies as well. Mummification might actually be better, but won't work if it's humid/not sealed tightly. The problem with bones is this: once flesh falls away, bones fall apart. They hold together when buried, because they are held together by the earth itself, but in the conditions you are talking about, the jaw bone generally falls away from the skull. Here are the factors you will need to consider, because these data points are crucial, and you can't get an answer without them: **Humidity** The higher the humidity, the less likely the corpses will mummify. **Temperature** Are there seasons? Is this a tropical area? The season in which they die will be a crucial factor. In high humidity and temperature, they can be reduced to bone in a matter of weeks with insects around. If any rats/small critters can get in, the hands and feet will likely be gone. And if there is any airflow at all, rats/critters will be highly motivated. I think, if you are going for romance, which is what it sounds like and you want realism, so I'd say--seal it tight to make some mummies. Mummies rule! Skeletons just can't keep it together! ;)
The rule of thumb is “100 degree-days to get bones”. I don't know what *degree* is measured from, but that should be a start for Google… And that turns up [this link](https://weather.com/science/news/flesh-bone-what-role-weather-plays-body-decomposition-20131031) which is a start. [This one, *The Rate of Decay in a Corpse*](http://www.exploreforensics.co.uk/the-rate-of-decay-in-a-corpse.html) is more informative and provides the vocabulary you will need for further searching. Just skimming, the lack of rain or direct exposure and not being directly connected to the soil will reduce the decay rate. Depending on conditions you may bet a mummy and not a skelleton. So allow for **rats** or other wildlife to get in from a wooded area, as well as flys and beetles. That's the opposite of what you specified, so you can expect dessicated remains with nothing happening after flys. You might postulate specific carnivorous beetles, but really you wrote yourself into a corner. Where would the flesh hqve gone off to?
49,109
From death to brittleness? Two bodies, on a bed, in an embrace. Windows and doors closed, so little to no air and light, but not completely air/light tight. No scavenger animals/rodents, but bugs would obviously be present. Humid (tropical rain-forest) environment. The aim is to have my characters stumble across this old castle, and find the bones of two people on the bed. I don't care if the bones are touched they would fall to dust, or if they are moved slightly/disturbed by bugs, or even if some of the bones are dust already, as long as it can be made out that its two skeletons embraced together. (and if not clearly embraced, its at least clear that its two skeletons) (i know "dust" isn't the appropriate term here, but you get what I mean?) How many years could this take? Thankyou EDIT: Just wanted to re-iterate, I don't so much care about the decomposing bodily fluids and flesh. I know that will decompose and be eaten by bugs and will stain the sheets upon decomposition. I know that mummification is out, as of the humidity. I'm wanting to know what happens to the BONES well after the process of rotting flesh is done. I know the joints wont stay together, and I know that the bugs will move the bones around a bit if they are eating the flesh. But say that, after a month or so of the people being dead, their bones would still be on the bed, and it would be obvious that two people were on the bed together, even if not embracing? how long would it take before their bones became so fragile and brittle that they would turn to "dust." or upon discovery of the bones, and disturbing the bones, would they disintegrate to dust upon a rush or air or a touch of hand?
2016/07/31
[ "https://worldbuilding.stackexchange.com/questions/49109", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/21849/" ]
They discovered [Richard III's](https://en.wikipedia.org/wiki/Richard_III_of_England#Discovery_of_remains) bones a few years ago. Given that he died in 1485, bones do survive for around 5 centuries in soil. Flesh rots in air, bones desiccate. From what a quick Google search indicates, bones become powdery in air in around 50 years. That said, I would guess, given a lack of air movement, and no animals crushing them with their weight/gnawing on them, the bones should retain their shape indefinitely.
The rule of thumb is “100 degree-days to get bones”. I don't know what *degree* is measured from, but that should be a start for Google… And that turns up [this link](https://weather.com/science/news/flesh-bone-what-role-weather-plays-body-decomposition-20131031) which is a start. [This one, *The Rate of Decay in a Corpse*](http://www.exploreforensics.co.uk/the-rate-of-decay-in-a-corpse.html) is more informative and provides the vocabulary you will need for further searching. Just skimming, the lack of rain or direct exposure and not being directly connected to the soil will reduce the decay rate. Depending on conditions you may bet a mummy and not a skelleton. So allow for **rats** or other wildlife to get in from a wooded area, as well as flys and beetles. That's the opposite of what you specified, so you can expect dessicated remains with nothing happening after flys. You might postulate specific carnivorous beetles, but really you wrote yourself into a corner. Where would the flesh hqve gone off to?
49,109
From death to brittleness? Two bodies, on a bed, in an embrace. Windows and doors closed, so little to no air and light, but not completely air/light tight. No scavenger animals/rodents, but bugs would obviously be present. Humid (tropical rain-forest) environment. The aim is to have my characters stumble across this old castle, and find the bones of two people on the bed. I don't care if the bones are touched they would fall to dust, or if they are moved slightly/disturbed by bugs, or even if some of the bones are dust already, as long as it can be made out that its two skeletons embraced together. (and if not clearly embraced, its at least clear that its two skeletons) (i know "dust" isn't the appropriate term here, but you get what I mean?) How many years could this take? Thankyou EDIT: Just wanted to re-iterate, I don't so much care about the decomposing bodily fluids and flesh. I know that will decompose and be eaten by bugs and will stain the sheets upon decomposition. I know that mummification is out, as of the humidity. I'm wanting to know what happens to the BONES well after the process of rotting flesh is done. I know the joints wont stay together, and I know that the bugs will move the bones around a bit if they are eating the flesh. But say that, after a month or so of the people being dead, their bones would still be on the bed, and it would be obvious that two people were on the bed together, even if not embracing? how long would it take before their bones became so fragile and brittle that they would turn to "dust." or upon discovery of the bones, and disturbing the bones, would they disintegrate to dust upon a rush or air or a touch of hand?
2016/07/31
[ "https://worldbuilding.stackexchange.com/questions/49109", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/21849/" ]
Okay, there's not much data on timescales of human bones decaying away to nothing, because we bury/ cremate our dead. Also when folk come across a pile of bones, they tend to phone the police. So you might have to look at studies of animal bones and extrapolate from that. The search term you'll need is [taphonomy](https://en.wikipedia.org/wiki/Taphonomy). That's the science of death and decay (and fossilisation). The stages of bone decay are as follows. This scale was invented by Dr Clive Trueman and is based on British chocolates and biscuits, so apologies to those not familiar with them. 1. Fresh bone. The bone is just like one you get from the butcher's for your dog. 2. The [Crunchie](https://en.wikipedia.org/wiki/Crunchie#/media/File:Crunchie_bar.jpg). The bone has dried out but still has a smooth outer cortex. If you split it open it has a 'honeycomb' cellular structure, like in life. 3. The [Ripple](http://thecandybitch.com/galaxy-ripple/). The bone still looks normal from the outside, with the outer cortex still intact. However, inside it is starting to recrystallise. 4. The [Flake](https://en.wikipedia.org/wiki/Flake_(chocolate_bar)). The outer cortex has gone and the recrystallisation is complete. The bone has a crumbly texture and will fall to pieces if you pick it up or handle it roughly. 5. The soggy digestive biscuit. The bone is reduced to lumps of mush. 6. Only a chemical analysis of the soil it was lying on can now detect that the bone was there at all. Not the same environment as your bones, but animal bones in Amboseli National Park [decayed beyond recognition in 10 to 15 years](http://journals.cambridge.org/action/displayAbstract?fromPage=online&aid=9669155&fileId=S0094837300005820). These bones are out in the open air. I'd say that's the fast end of the scale for bone disappearance. Here's another paper where bones in Amboselli [are there for at least 26 to 40 years](https://www.researchgate.net/profile/Clive_Trueman/publication/222557629_Mineralogical_and_compositional_changes_in_bones_exposed_on_soil_surfaces_in_Amboseli_National_Park_Kenya_Diagenetic_mechanisms_and_the_role_of_sediment_pore_fluids/links/02bfe50ffbfee2930f000000.pdf). This [paper on bone decay in different environments](http://onlinelibrary.wiley.com/doi/10.1002/oa.2275/abstract) looks as if it has useful data, but you'll have to pay to get beyond the abstract. So, your case has humidity, which will speed bone decay as fungi and bacteria get at them, but is indoors, so it won't be as fast as the Amboseli examples. If it is tropical rainforest climate humidity things will decay a lot faster than cold, damp UK humidity. Given that there are caves full of ice age cave bear bones, your skeletons can survive for thousands of years if you want them to. Or crumble if that fits the story better.
The rule of thumb is “100 degree-days to get bones”. I don't know what *degree* is measured from, but that should be a start for Google… And that turns up [this link](https://weather.com/science/news/flesh-bone-what-role-weather-plays-body-decomposition-20131031) which is a start. [This one, *The Rate of Decay in a Corpse*](http://www.exploreforensics.co.uk/the-rate-of-decay-in-a-corpse.html) is more informative and provides the vocabulary you will need for further searching. Just skimming, the lack of rain or direct exposure and not being directly connected to the soil will reduce the decay rate. Depending on conditions you may bet a mummy and not a skelleton. So allow for **rats** or other wildlife to get in from a wooded area, as well as flys and beetles. That's the opposite of what you specified, so you can expect dessicated remains with nothing happening after flys. You might postulate specific carnivorous beetles, but really you wrote yourself into a corner. Where would the flesh hqve gone off to?
49,109
From death to brittleness? Two bodies, on a bed, in an embrace. Windows and doors closed, so little to no air and light, but not completely air/light tight. No scavenger animals/rodents, but bugs would obviously be present. Humid (tropical rain-forest) environment. The aim is to have my characters stumble across this old castle, and find the bones of two people on the bed. I don't care if the bones are touched they would fall to dust, or if they are moved slightly/disturbed by bugs, or even if some of the bones are dust already, as long as it can be made out that its two skeletons embraced together. (and if not clearly embraced, its at least clear that its two skeletons) (i know "dust" isn't the appropriate term here, but you get what I mean?) How many years could this take? Thankyou EDIT: Just wanted to re-iterate, I don't so much care about the decomposing bodily fluids and flesh. I know that will decompose and be eaten by bugs and will stain the sheets upon decomposition. I know that mummification is out, as of the humidity. I'm wanting to know what happens to the BONES well after the process of rotting flesh is done. I know the joints wont stay together, and I know that the bugs will move the bones around a bit if they are eating the flesh. But say that, after a month or so of the people being dead, their bones would still be on the bed, and it would be obvious that two people were on the bed together, even if not embracing? how long would it take before their bones became so fragile and brittle that they would turn to "dust." or upon discovery of the bones, and disturbing the bones, would they disintegrate to dust upon a rush or air or a touch of hand?
2016/07/31
[ "https://worldbuilding.stackexchange.com/questions/49109", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/21849/" ]
It really depends on four things 1. how well sealed the room is, keeping rodents out is essential, they will eat bone just for the calcium. 2. the humidity, fungi can eat bone so you want it dry, light is likewise the enemy. 3. the temprature, if it is exposed to freezing and thawing the bones will powderize quite quickly. so it needs to be consistently above freezing or consistently below, dryness will also help. 4. how much anatomy the people finding them know, the more anatomy they know the worse off the bones can be. As long as only bacteria or small insects can get to it bones, and it is dry they may survive intact (identifiable) for 300 years as long as they do not go through to many freeze/thaw cycles. basically the better the conditions are for natural mummification the better they are for your bones. Your biggest problem is the tropical rain forest, the bones are gone unless they get buried, heck even your *buildings* are not going to survive that well in that environment. Bones a month sure, a hundred years highly unlikely. The more cave like the place they are they better they will survive in that climate. There is one way to preserve the bones, but they will not be easy to find afterwards. Guano can seal and preserve material in a similar fashion to amber, but you need to keep it away from the sun and it needs to build up quickly. so you need a lot of bats, possibly coming in through a hole in the roof to keep the rodent population non-existent and keep out the most destructive insects (ants and termites), for this same reason your building needs to be big. The downside is that your bones will then be buried, so unless your people are looking for them they will not find them. bones turning to dust requires a very dry environment, you need to keep biological activity to a minimum. I have handled fossilized mammoth bones in Wyoming and you could crush them with your hands and they were constantly flaking off bone. They were buried in almost 3 feet of natron soil in an extremely dry environment.
The rule of thumb is “100 degree-days to get bones”. I don't know what *degree* is measured from, but that should be a start for Google… And that turns up [this link](https://weather.com/science/news/flesh-bone-what-role-weather-plays-body-decomposition-20131031) which is a start. [This one, *The Rate of Decay in a Corpse*](http://www.exploreforensics.co.uk/the-rate-of-decay-in-a-corpse.html) is more informative and provides the vocabulary you will need for further searching. Just skimming, the lack of rain or direct exposure and not being directly connected to the soil will reduce the decay rate. Depending on conditions you may bet a mummy and not a skelleton. So allow for **rats** or other wildlife to get in from a wooded area, as well as flys and beetles. That's the opposite of what you specified, so you can expect dessicated remains with nothing happening after flys. You might postulate specific carnivorous beetles, but really you wrote yourself into a corner. Where would the flesh hqve gone off to?
49,109
From death to brittleness? Two bodies, on a bed, in an embrace. Windows and doors closed, so little to no air and light, but not completely air/light tight. No scavenger animals/rodents, but bugs would obviously be present. Humid (tropical rain-forest) environment. The aim is to have my characters stumble across this old castle, and find the bones of two people on the bed. I don't care if the bones are touched they would fall to dust, or if they are moved slightly/disturbed by bugs, or even if some of the bones are dust already, as long as it can be made out that its two skeletons embraced together. (and if not clearly embraced, its at least clear that its two skeletons) (i know "dust" isn't the appropriate term here, but you get what I mean?) How many years could this take? Thankyou EDIT: Just wanted to re-iterate, I don't so much care about the decomposing bodily fluids and flesh. I know that will decompose and be eaten by bugs and will stain the sheets upon decomposition. I know that mummification is out, as of the humidity. I'm wanting to know what happens to the BONES well after the process of rotting flesh is done. I know the joints wont stay together, and I know that the bugs will move the bones around a bit if they are eating the flesh. But say that, after a month or so of the people being dead, their bones would still be on the bed, and it would be obvious that two people were on the bed together, even if not embracing? how long would it take before their bones became so fragile and brittle that they would turn to "dust." or upon discovery of the bones, and disturbing the bones, would they disintegrate to dust upon a rush or air or a touch of hand?
2016/07/31
[ "https://worldbuilding.stackexchange.com/questions/49109", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/21849/" ]
Not as long as you might think, especially if the room is not tightly sealed. Bugs will eat a corpse pretty efficiently, even without animals. If you are looking for this to be some romantic scene because there isn't viscera, well, it's going to smell if it's been sealed, no matter what. Even if they are bones. The bed will be stained with the fluids of their bodies as well. Mummification might actually be better, but won't work if it's humid/not sealed tightly. The problem with bones is this: once flesh falls away, bones fall apart. They hold together when buried, because they are held together by the earth itself, but in the conditions you are talking about, the jaw bone generally falls away from the skull. Here are the factors you will need to consider, because these data points are crucial, and you can't get an answer without them: **Humidity** The higher the humidity, the less likely the corpses will mummify. **Temperature** Are there seasons? Is this a tropical area? The season in which they die will be a crucial factor. In high humidity and temperature, they can be reduced to bone in a matter of weeks with insects around. If any rats/small critters can get in, the hands and feet will likely be gone. And if there is any airflow at all, rats/critters will be highly motivated. I think, if you are going for romance, which is what it sounds like and you want realism, so I'd say--seal it tight to make some mummies. Mummies rule! Skeletons just can't keep it together! ;)
They discovered [Richard III's](https://en.wikipedia.org/wiki/Richard_III_of_England#Discovery_of_remains) bones a few years ago. Given that he died in 1485, bones do survive for around 5 centuries in soil. Flesh rots in air, bones desiccate. From what a quick Google search indicates, bones become powdery in air in around 50 years. That said, I would guess, given a lack of air movement, and no animals crushing them with their weight/gnawing on them, the bones should retain their shape indefinitely.
49,109
From death to brittleness? Two bodies, on a bed, in an embrace. Windows and doors closed, so little to no air and light, but not completely air/light tight. No scavenger animals/rodents, but bugs would obviously be present. Humid (tropical rain-forest) environment. The aim is to have my characters stumble across this old castle, and find the bones of two people on the bed. I don't care if the bones are touched they would fall to dust, or if they are moved slightly/disturbed by bugs, or even if some of the bones are dust already, as long as it can be made out that its two skeletons embraced together. (and if not clearly embraced, its at least clear that its two skeletons) (i know "dust" isn't the appropriate term here, but you get what I mean?) How many years could this take? Thankyou EDIT: Just wanted to re-iterate, I don't so much care about the decomposing bodily fluids and flesh. I know that will decompose and be eaten by bugs and will stain the sheets upon decomposition. I know that mummification is out, as of the humidity. I'm wanting to know what happens to the BONES well after the process of rotting flesh is done. I know the joints wont stay together, and I know that the bugs will move the bones around a bit if they are eating the flesh. But say that, after a month or so of the people being dead, their bones would still be on the bed, and it would be obvious that two people were on the bed together, even if not embracing? how long would it take before their bones became so fragile and brittle that they would turn to "dust." or upon discovery of the bones, and disturbing the bones, would they disintegrate to dust upon a rush or air or a touch of hand?
2016/07/31
[ "https://worldbuilding.stackexchange.com/questions/49109", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/21849/" ]
Okay, there's not much data on timescales of human bones decaying away to nothing, because we bury/ cremate our dead. Also when folk come across a pile of bones, they tend to phone the police. So you might have to look at studies of animal bones and extrapolate from that. The search term you'll need is [taphonomy](https://en.wikipedia.org/wiki/Taphonomy). That's the science of death and decay (and fossilisation). The stages of bone decay are as follows. This scale was invented by Dr Clive Trueman and is based on British chocolates and biscuits, so apologies to those not familiar with them. 1. Fresh bone. The bone is just like one you get from the butcher's for your dog. 2. The [Crunchie](https://en.wikipedia.org/wiki/Crunchie#/media/File:Crunchie_bar.jpg). The bone has dried out but still has a smooth outer cortex. If you split it open it has a 'honeycomb' cellular structure, like in life. 3. The [Ripple](http://thecandybitch.com/galaxy-ripple/). The bone still looks normal from the outside, with the outer cortex still intact. However, inside it is starting to recrystallise. 4. The [Flake](https://en.wikipedia.org/wiki/Flake_(chocolate_bar)). The outer cortex has gone and the recrystallisation is complete. The bone has a crumbly texture and will fall to pieces if you pick it up or handle it roughly. 5. The soggy digestive biscuit. The bone is reduced to lumps of mush. 6. Only a chemical analysis of the soil it was lying on can now detect that the bone was there at all. Not the same environment as your bones, but animal bones in Amboseli National Park [decayed beyond recognition in 10 to 15 years](http://journals.cambridge.org/action/displayAbstract?fromPage=online&aid=9669155&fileId=S0094837300005820). These bones are out in the open air. I'd say that's the fast end of the scale for bone disappearance. Here's another paper where bones in Amboselli [are there for at least 26 to 40 years](https://www.researchgate.net/profile/Clive_Trueman/publication/222557629_Mineralogical_and_compositional_changes_in_bones_exposed_on_soil_surfaces_in_Amboseli_National_Park_Kenya_Diagenetic_mechanisms_and_the_role_of_sediment_pore_fluids/links/02bfe50ffbfee2930f000000.pdf). This [paper on bone decay in different environments](http://onlinelibrary.wiley.com/doi/10.1002/oa.2275/abstract) looks as if it has useful data, but you'll have to pay to get beyond the abstract. So, your case has humidity, which will speed bone decay as fungi and bacteria get at them, but is indoors, so it won't be as fast as the Amboseli examples. If it is tropical rainforest climate humidity things will decay a lot faster than cold, damp UK humidity. Given that there are caves full of ice age cave bear bones, your skeletons can survive for thousands of years if you want them to. Or crumble if that fits the story better.
Not as long as you might think, especially if the room is not tightly sealed. Bugs will eat a corpse pretty efficiently, even without animals. If you are looking for this to be some romantic scene because there isn't viscera, well, it's going to smell if it's been sealed, no matter what. Even if they are bones. The bed will be stained with the fluids of their bodies as well. Mummification might actually be better, but won't work if it's humid/not sealed tightly. The problem with bones is this: once flesh falls away, bones fall apart. They hold together when buried, because they are held together by the earth itself, but in the conditions you are talking about, the jaw bone generally falls away from the skull. Here are the factors you will need to consider, because these data points are crucial, and you can't get an answer without them: **Humidity** The higher the humidity, the less likely the corpses will mummify. **Temperature** Are there seasons? Is this a tropical area? The season in which they die will be a crucial factor. In high humidity and temperature, they can be reduced to bone in a matter of weeks with insects around. If any rats/small critters can get in, the hands and feet will likely be gone. And if there is any airflow at all, rats/critters will be highly motivated. I think, if you are going for romance, which is what it sounds like and you want realism, so I'd say--seal it tight to make some mummies. Mummies rule! Skeletons just can't keep it together! ;)
49,109
From death to brittleness? Two bodies, on a bed, in an embrace. Windows and doors closed, so little to no air and light, but not completely air/light tight. No scavenger animals/rodents, but bugs would obviously be present. Humid (tropical rain-forest) environment. The aim is to have my characters stumble across this old castle, and find the bones of two people on the bed. I don't care if the bones are touched they would fall to dust, or if they are moved slightly/disturbed by bugs, or even if some of the bones are dust already, as long as it can be made out that its two skeletons embraced together. (and if not clearly embraced, its at least clear that its two skeletons) (i know "dust" isn't the appropriate term here, but you get what I mean?) How many years could this take? Thankyou EDIT: Just wanted to re-iterate, I don't so much care about the decomposing bodily fluids and flesh. I know that will decompose and be eaten by bugs and will stain the sheets upon decomposition. I know that mummification is out, as of the humidity. I'm wanting to know what happens to the BONES well after the process of rotting flesh is done. I know the joints wont stay together, and I know that the bugs will move the bones around a bit if they are eating the flesh. But say that, after a month or so of the people being dead, their bones would still be on the bed, and it would be obvious that two people were on the bed together, even if not embracing? how long would it take before their bones became so fragile and brittle that they would turn to "dust." or upon discovery of the bones, and disturbing the bones, would they disintegrate to dust upon a rush or air or a touch of hand?
2016/07/31
[ "https://worldbuilding.stackexchange.com/questions/49109", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/21849/" ]
Not as long as you might think, especially if the room is not tightly sealed. Bugs will eat a corpse pretty efficiently, even without animals. If you are looking for this to be some romantic scene because there isn't viscera, well, it's going to smell if it's been sealed, no matter what. Even if they are bones. The bed will be stained with the fluids of their bodies as well. Mummification might actually be better, but won't work if it's humid/not sealed tightly. The problem with bones is this: once flesh falls away, bones fall apart. They hold together when buried, because they are held together by the earth itself, but in the conditions you are talking about, the jaw bone generally falls away from the skull. Here are the factors you will need to consider, because these data points are crucial, and you can't get an answer without them: **Humidity** The higher the humidity, the less likely the corpses will mummify. **Temperature** Are there seasons? Is this a tropical area? The season in which they die will be a crucial factor. In high humidity and temperature, they can be reduced to bone in a matter of weeks with insects around. If any rats/small critters can get in, the hands and feet will likely be gone. And if there is any airflow at all, rats/critters will be highly motivated. I think, if you are going for romance, which is what it sounds like and you want realism, so I'd say--seal it tight to make some mummies. Mummies rule! Skeletons just can't keep it together! ;)
It really depends on four things 1. how well sealed the room is, keeping rodents out is essential, they will eat bone just for the calcium. 2. the humidity, fungi can eat bone so you want it dry, light is likewise the enemy. 3. the temprature, if it is exposed to freezing and thawing the bones will powderize quite quickly. so it needs to be consistently above freezing or consistently below, dryness will also help. 4. how much anatomy the people finding them know, the more anatomy they know the worse off the bones can be. As long as only bacteria or small insects can get to it bones, and it is dry they may survive intact (identifiable) for 300 years as long as they do not go through to many freeze/thaw cycles. basically the better the conditions are for natural mummification the better they are for your bones. Your biggest problem is the tropical rain forest, the bones are gone unless they get buried, heck even your *buildings* are not going to survive that well in that environment. Bones a month sure, a hundred years highly unlikely. The more cave like the place they are they better they will survive in that climate. There is one way to preserve the bones, but they will not be easy to find afterwards. Guano can seal and preserve material in a similar fashion to amber, but you need to keep it away from the sun and it needs to build up quickly. so you need a lot of bats, possibly coming in through a hole in the roof to keep the rodent population non-existent and keep out the most destructive insects (ants and termites), for this same reason your building needs to be big. The downside is that your bones will then be buried, so unless your people are looking for them they will not find them. bones turning to dust requires a very dry environment, you need to keep biological activity to a minimum. I have handled fossilized mammoth bones in Wyoming and you could crush them with your hands and they were constantly flaking off bone. They were buried in almost 3 feet of natron soil in an extremely dry environment.
49,109
From death to brittleness? Two bodies, on a bed, in an embrace. Windows and doors closed, so little to no air and light, but not completely air/light tight. No scavenger animals/rodents, but bugs would obviously be present. Humid (tropical rain-forest) environment. The aim is to have my characters stumble across this old castle, and find the bones of two people on the bed. I don't care if the bones are touched they would fall to dust, or if they are moved slightly/disturbed by bugs, or even if some of the bones are dust already, as long as it can be made out that its two skeletons embraced together. (and if not clearly embraced, its at least clear that its two skeletons) (i know "dust" isn't the appropriate term here, but you get what I mean?) How many years could this take? Thankyou EDIT: Just wanted to re-iterate, I don't so much care about the decomposing bodily fluids and flesh. I know that will decompose and be eaten by bugs and will stain the sheets upon decomposition. I know that mummification is out, as of the humidity. I'm wanting to know what happens to the BONES well after the process of rotting flesh is done. I know the joints wont stay together, and I know that the bugs will move the bones around a bit if they are eating the flesh. But say that, after a month or so of the people being dead, their bones would still be on the bed, and it would be obvious that two people were on the bed together, even if not embracing? how long would it take before their bones became so fragile and brittle that they would turn to "dust." or upon discovery of the bones, and disturbing the bones, would they disintegrate to dust upon a rush or air or a touch of hand?
2016/07/31
[ "https://worldbuilding.stackexchange.com/questions/49109", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/21849/" ]
Okay, there's not much data on timescales of human bones decaying away to nothing, because we bury/ cremate our dead. Also when folk come across a pile of bones, they tend to phone the police. So you might have to look at studies of animal bones and extrapolate from that. The search term you'll need is [taphonomy](https://en.wikipedia.org/wiki/Taphonomy). That's the science of death and decay (and fossilisation). The stages of bone decay are as follows. This scale was invented by Dr Clive Trueman and is based on British chocolates and biscuits, so apologies to those not familiar with them. 1. Fresh bone. The bone is just like one you get from the butcher's for your dog. 2. The [Crunchie](https://en.wikipedia.org/wiki/Crunchie#/media/File:Crunchie_bar.jpg). The bone has dried out but still has a smooth outer cortex. If you split it open it has a 'honeycomb' cellular structure, like in life. 3. The [Ripple](http://thecandybitch.com/galaxy-ripple/). The bone still looks normal from the outside, with the outer cortex still intact. However, inside it is starting to recrystallise. 4. The [Flake](https://en.wikipedia.org/wiki/Flake_(chocolate_bar)). The outer cortex has gone and the recrystallisation is complete. The bone has a crumbly texture and will fall to pieces if you pick it up or handle it roughly. 5. The soggy digestive biscuit. The bone is reduced to lumps of mush. 6. Only a chemical analysis of the soil it was lying on can now detect that the bone was there at all. Not the same environment as your bones, but animal bones in Amboseli National Park [decayed beyond recognition in 10 to 15 years](http://journals.cambridge.org/action/displayAbstract?fromPage=online&aid=9669155&fileId=S0094837300005820). These bones are out in the open air. I'd say that's the fast end of the scale for bone disappearance. Here's another paper where bones in Amboselli [are there for at least 26 to 40 years](https://www.researchgate.net/profile/Clive_Trueman/publication/222557629_Mineralogical_and_compositional_changes_in_bones_exposed_on_soil_surfaces_in_Amboseli_National_Park_Kenya_Diagenetic_mechanisms_and_the_role_of_sediment_pore_fluids/links/02bfe50ffbfee2930f000000.pdf). This [paper on bone decay in different environments](http://onlinelibrary.wiley.com/doi/10.1002/oa.2275/abstract) looks as if it has useful data, but you'll have to pay to get beyond the abstract. So, your case has humidity, which will speed bone decay as fungi and bacteria get at them, but is indoors, so it won't be as fast as the Amboseli examples. If it is tropical rainforest climate humidity things will decay a lot faster than cold, damp UK humidity. Given that there are caves full of ice age cave bear bones, your skeletons can survive for thousands of years if you want them to. Or crumble if that fits the story better.
They discovered [Richard III's](https://en.wikipedia.org/wiki/Richard_III_of_England#Discovery_of_remains) bones a few years ago. Given that he died in 1485, bones do survive for around 5 centuries in soil. Flesh rots in air, bones desiccate. From what a quick Google search indicates, bones become powdery in air in around 50 years. That said, I would guess, given a lack of air movement, and no animals crushing them with their weight/gnawing on them, the bones should retain their shape indefinitely.
49,109
From death to brittleness? Two bodies, on a bed, in an embrace. Windows and doors closed, so little to no air and light, but not completely air/light tight. No scavenger animals/rodents, but bugs would obviously be present. Humid (tropical rain-forest) environment. The aim is to have my characters stumble across this old castle, and find the bones of two people on the bed. I don't care if the bones are touched they would fall to dust, or if they are moved slightly/disturbed by bugs, or even if some of the bones are dust already, as long as it can be made out that its two skeletons embraced together. (and if not clearly embraced, its at least clear that its two skeletons) (i know "dust" isn't the appropriate term here, but you get what I mean?) How many years could this take? Thankyou EDIT: Just wanted to re-iterate, I don't so much care about the decomposing bodily fluids and flesh. I know that will decompose and be eaten by bugs and will stain the sheets upon decomposition. I know that mummification is out, as of the humidity. I'm wanting to know what happens to the BONES well after the process of rotting flesh is done. I know the joints wont stay together, and I know that the bugs will move the bones around a bit if they are eating the flesh. But say that, after a month or so of the people being dead, their bones would still be on the bed, and it would be obvious that two people were on the bed together, even if not embracing? how long would it take before their bones became so fragile and brittle that they would turn to "dust." or upon discovery of the bones, and disturbing the bones, would they disintegrate to dust upon a rush or air or a touch of hand?
2016/07/31
[ "https://worldbuilding.stackexchange.com/questions/49109", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/21849/" ]
Okay, there's not much data on timescales of human bones decaying away to nothing, because we bury/ cremate our dead. Also when folk come across a pile of bones, they tend to phone the police. So you might have to look at studies of animal bones and extrapolate from that. The search term you'll need is [taphonomy](https://en.wikipedia.org/wiki/Taphonomy). That's the science of death and decay (and fossilisation). The stages of bone decay are as follows. This scale was invented by Dr Clive Trueman and is based on British chocolates and biscuits, so apologies to those not familiar with them. 1. Fresh bone. The bone is just like one you get from the butcher's for your dog. 2. The [Crunchie](https://en.wikipedia.org/wiki/Crunchie#/media/File:Crunchie_bar.jpg). The bone has dried out but still has a smooth outer cortex. If you split it open it has a 'honeycomb' cellular structure, like in life. 3. The [Ripple](http://thecandybitch.com/galaxy-ripple/). The bone still looks normal from the outside, with the outer cortex still intact. However, inside it is starting to recrystallise. 4. The [Flake](https://en.wikipedia.org/wiki/Flake_(chocolate_bar)). The outer cortex has gone and the recrystallisation is complete. The bone has a crumbly texture and will fall to pieces if you pick it up or handle it roughly. 5. The soggy digestive biscuit. The bone is reduced to lumps of mush. 6. Only a chemical analysis of the soil it was lying on can now detect that the bone was there at all. Not the same environment as your bones, but animal bones in Amboseli National Park [decayed beyond recognition in 10 to 15 years](http://journals.cambridge.org/action/displayAbstract?fromPage=online&aid=9669155&fileId=S0094837300005820). These bones are out in the open air. I'd say that's the fast end of the scale for bone disappearance. Here's another paper where bones in Amboselli [are there for at least 26 to 40 years](https://www.researchgate.net/profile/Clive_Trueman/publication/222557629_Mineralogical_and_compositional_changes_in_bones_exposed_on_soil_surfaces_in_Amboseli_National_Park_Kenya_Diagenetic_mechanisms_and_the_role_of_sediment_pore_fluids/links/02bfe50ffbfee2930f000000.pdf). This [paper on bone decay in different environments](http://onlinelibrary.wiley.com/doi/10.1002/oa.2275/abstract) looks as if it has useful data, but you'll have to pay to get beyond the abstract. So, your case has humidity, which will speed bone decay as fungi and bacteria get at them, but is indoors, so it won't be as fast as the Amboseli examples. If it is tropical rainforest climate humidity things will decay a lot faster than cold, damp UK humidity. Given that there are caves full of ice age cave bear bones, your skeletons can survive for thousands of years if you want them to. Or crumble if that fits the story better.
It really depends on four things 1. how well sealed the room is, keeping rodents out is essential, they will eat bone just for the calcium. 2. the humidity, fungi can eat bone so you want it dry, light is likewise the enemy. 3. the temprature, if it is exposed to freezing and thawing the bones will powderize quite quickly. so it needs to be consistently above freezing or consistently below, dryness will also help. 4. how much anatomy the people finding them know, the more anatomy they know the worse off the bones can be. As long as only bacteria or small insects can get to it bones, and it is dry they may survive intact (identifiable) for 300 years as long as they do not go through to many freeze/thaw cycles. basically the better the conditions are for natural mummification the better they are for your bones. Your biggest problem is the tropical rain forest, the bones are gone unless they get buried, heck even your *buildings* are not going to survive that well in that environment. Bones a month sure, a hundred years highly unlikely. The more cave like the place they are they better they will survive in that climate. There is one way to preserve the bones, but they will not be easy to find afterwards. Guano can seal and preserve material in a similar fashion to amber, but you need to keep it away from the sun and it needs to build up quickly. so you need a lot of bats, possibly coming in through a hole in the roof to keep the rodent population non-existent and keep out the most destructive insects (ants and termites), for this same reason your building needs to be big. The downside is that your bones will then be buried, so unless your people are looking for them they will not find them. bones turning to dust requires a very dry environment, you need to keep biological activity to a minimum. I have handled fossilized mammoth bones in Wyoming and you could crush them with your hands and they were constantly flaking off bone. They were buried in almost 3 feet of natron soil in an extremely dry environment.
102,279
I am trying to solve the recurrence below but I find myself stuck. $T(n) = \frac{n}{2}T(\frac{n}{2}) + \log n$ I have tried coming up with a guess by drawing a recurrence tree. What I have found is number of nodes at a level: $\frac{n}{2^{i}}$ running time at each node: $\log \frac{n}{2^{i}}$ total running time at each level: $\frac{n}{2^{i}} \log \frac{n}{2^{i}}$ I try to sum this over through n > $\log n$ which is the height of the tree $$\begin{align} \sum\limits\_{i=0}^n \frac{n}{2^{i}} \log \frac{n}{2^{i}}&= n \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log \frac{n}{2^{i}}\\ &=n \sum\limits\_{i=0}^n \frac{1}{2^{i}} (\log n - \log 2^{i})\\ &=n \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log n - \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log 2^{i}\\ &=n \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log n - \sum\limits\_{i=0}^n \frac{ \log 2^{i}}{2^{i}}\\ &=n \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log n - d \sum\limits\_{i=0}^n \frac{i}{2^{i}}\\ &=2 n \log n - d \sum\limits\_{i=0}^n \frac{i}{2^{i}} \end{align}$$ I am still trying to figure out the sum of the second summation above but I somehow feel that it will be bigger than $2n \log n$ which makes my whole approach wrong. Is there another way to tackle this problem?
2012/01/25
[ "https://math.stackexchange.com/questions/102279", "https://math.stackexchange.com", "https://math.stackexchange.com/users/14078/" ]
Consider the equality $$ 1+x+x^2+...+x^n=\frac{x^{n + 1} -1}{x-1} $$ Differentiate it by $x$, then multiply by $x$: $$ x+2x^2+3x^3+...+n x^n=\frac{nx^{n+2} - (n + 1)x^{n+1} + x}{(x-1)^2} $$ Now we can substitute $x=\frac{1}{2}$ and obtain $$ \sum\limits\_{i=0}^n\frac{i}{2^i}=n\left(\frac{1}{2}\right)^{n} - (n + 1)\left(\frac{1}{2}\right)^{n-1} + 2 $$
**Summary:** Like in several questions of the same ilk asked previously on the site, the recursion can only determine each $T(n)$ as a function of $T(2i+1)$ and $k\geqslant0$, where $n=(2i+1)2^k$. Furthermoree, the series considered by the OP are simply not relevant to the asymptotics of $T(n)$. The growth of $T(n)$ of the order of $n\log n$, which the OP seems to infer, is not compatible with the recursion at hand since, speaking very roughly, $T(n)$ grows like $n^{\frac12\log n}$. **Gory details:** Consider for example $t\_k=T(2^k)$. Then, for every $k\geqslant1$, $$ t\_k=2^{k-1}t\_{k-1}+k\log2, $$ hence the change of variables $ s\_k=2^{-k(k-1)/2}t\_k $ yields the recursion $s\_0=t\_0=T(1)$ and $ s\_k=s\_{k-1}+2^{-k(k-1)/2}k\log2$. This is solved by $$ s\_k=s\_0+\log2\sum\limits\_{i=1}^ki2^{-i(i-1)/2}, $$ whose translation in terms of $t\_k$ is $$ t\_k=2^{k(k-1)/2}\left(T(1)+\log2\sum\limits\_{i=1}^k\frac{i}{2^{i(i-1)/2}}\right). $$ Finally, $$ T(2^k)=2^{k(k-1)/2}\tau\_0-(\log2)\,(k/2^{k})+o(k/2^k),$$ with $$ \tau\_0=T(1)+(\log2)\,\sum\limits\_{i=1}^{\infty}\frac{i}{2^{i(i-1)/2}}= T(1)+1.69306\ldots $$ **Conclusion:** One sees that, along the subsequence indexed by the powers of $2$, $T(n)$ grows roughly like $n^{\frac12\log n}$ rather than like $n\log n$. The same argument applies to each subsequence indexed by the powers of $2$ times any given odd integer.
102,279
I am trying to solve the recurrence below but I find myself stuck. $T(n) = \frac{n}{2}T(\frac{n}{2}) + \log n$ I have tried coming up with a guess by drawing a recurrence tree. What I have found is number of nodes at a level: $\frac{n}{2^{i}}$ running time at each node: $\log \frac{n}{2^{i}}$ total running time at each level: $\frac{n}{2^{i}} \log \frac{n}{2^{i}}$ I try to sum this over through n > $\log n$ which is the height of the tree $$\begin{align} \sum\limits\_{i=0}^n \frac{n}{2^{i}} \log \frac{n}{2^{i}}&= n \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log \frac{n}{2^{i}}\\ &=n \sum\limits\_{i=0}^n \frac{1}{2^{i}} (\log n - \log 2^{i})\\ &=n \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log n - \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log 2^{i}\\ &=n \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log n - \sum\limits\_{i=0}^n \frac{ \log 2^{i}}{2^{i}}\\ &=n \sum\limits\_{i=0}^n \frac{1}{2^{i}} \log n - d \sum\limits\_{i=0}^n \frac{i}{2^{i}}\\ &=2 n \log n - d \sum\limits\_{i=0}^n \frac{i}{2^{i}} \end{align}$$ I am still trying to figure out the sum of the second summation above but I somehow feel that it will be bigger than $2n \log n$ which makes my whole approach wrong. Is there another way to tackle this problem?
2012/01/25
[ "https://math.stackexchange.com/questions/102279", "https://math.stackexchange.com", "https://math.stackexchange.com/users/14078/" ]
Consider the equality $$ 1+x+x^2+...+x^n=\frac{x^{n + 1} -1}{x-1} $$ Differentiate it by $x$, then multiply by $x$: $$ x+2x^2+3x^3+...+n x^n=\frac{nx^{n+2} - (n + 1)x^{n+1} + x}{(x-1)^2} $$ Now we can substitute $x=\frac{1}{2}$ and obtain $$ \sum\limits\_{i=0}^n\frac{i}{2^i}=n\left(\frac{1}{2}\right)^{n} - (n + 1)\left(\frac{1}{2}\right)^{n-1} + 2 $$
The summation $$ \sum\limits\_{i=0}^n \frac{i}{2^{i}} $$ is equal to $$ \sum\limits\_{i=0}^n i(\frac{1}{2})^i $$ which is of the form $$ \sum\limits\_{i=0}^n ix^i, x = \frac{1}{2} $$ Consider the summation $$ \sum\limits\_{i=0}^n x^i = \frac{x^{n+1} - 1}{x - 1} $$ By differentiating with respect to $x$ we have $$ \frac{d}{dx}\left( \sum\limits\_{i=0}^n x^i \right) = \frac{d}{dx} \left( \frac{x^{n+1} - 1}{x - 1} \right)$$ $$ \Rightarrow \sum\limits\_{i=0}^n ix^{i-1} = \frac{(x - 1)(n + 1)x^n - (x^{n+1} -1)(1)}{(x - 1)^2} $$ $$ \Rightarrow \sum\limits\_{i=0}^n ix^{i-1} = \frac{(x^{n+1} - x^n)(n + 1) - x^{n+1} + 1}{(x - 1)^2} $$ $$ \Rightarrow \sum\limits\_{i=0}^n ix^{i-1} = \frac{(nx^{n+1} - nx^n) + (x^{n+1} - x^n) - x^{n+1} + 1}{(x - 1)^2} $$ $$ \Rightarrow \sum\limits\_{i=0}^n ix^{i-1} = \frac{nx^{n+1} - nx^n + x^{n+1} - x^n - x^{n+1} + 1}{(x - 1)^2} $$ $$ \Rightarrow \sum\limits\_{i=0}^n ix^{i-1} = \frac{nx^{n+1} - nx^n - x^n + 1}{(x - 1)^2} $$ By multiplying $x$ to both sides, $$ x\sum\limits\_{i=0}^n ix^{i-1} = x\left( \frac{nx^{n+1} - nx^n - x^n + 1}{(x - 1)^2} \right)$$ $$ \Rightarrow \sum\limits\_{i=0}^n ix^{i} = \frac{nx^{n+2} - nx^{n+1} - x^{n+1} + x}{(x - 1)^2} $$ By substitution $ \left( x = \frac{1}{2} \right) $, $$ \sum\limits\_{i=0}^n i\left(\frac{1}{2}\right)^{i} = \frac{n\left(\frac{1}{2}\right)^{n+2} - n\left(\frac{1}{2}\right)^{n+1} - \left(\frac{1}{2}\right)^{n+1} + \left(\frac{1}{2}\right)}{(\left(\frac{1}{2}\right) - 1)^2} $$ $$ \Rightarrow \sum\limits\_{i=0}^n i\left(\frac{1}{2}\right)^{i} = \frac{n\left(\frac{1}{2^{n+2}}\right) - n\left(\frac{1}{2^{n+1}}\right) - \left(\frac{1}{2^{n+1}}\right) + \left(\frac{1}{2}\right)}{\left(-\frac{1}{2}\right)^2} $$ $$ \Rightarrow \sum\limits\_{i=0}^n i\left(\frac{1}{2}\right)^{i} = \frac{\frac{n}{2^{n+2}} - \frac{n + 1}{2^{n+1}} + \frac{1}{2}}{\left(\frac{1}{4}\right)} $$ $$ \Rightarrow \sum\limits\_{i=0}^n i\left(\frac{1}{2}\right)^{i} = 4 \left( \frac{n}{2^{n+2}} - \frac{n + 1}{2^{n+1}} + \frac{1}{2} \right) $$ $$ \Rightarrow \sum\limits\_{i=0}^n i\left(\frac{1}{2}\right)^{i} = 4 \left( \frac{n}{2^{n+2}} - \frac{2(n + 1)}{2^{n+2}} + \frac{2^{n+1}}{2^{n+2}} \right) $$ $$ \Rightarrow \sum\limits\_{i=0}^n i\left(\frac{1}{2}\right)^{i} = \frac{n - 2(n + 1) + 2^{(n+1)}}{2^{n}} $$ $$ \Rightarrow \sum\limits\_{i=0}^n \frac{i}{2^{i}} = \frac{n - 2(n + 1) + 2^{(n+1)}}{2^{n}} $$
13,383
I need a web based project management software. It should basically have: * Issue tracker * Wiki (not mandatory) * Git integration * Progress It should be open source and I should be able to install it onto my server. Currently, I have found the following options : * [ProjeQtOr](http://www.projeqtor.org/) * [MyCollab](http://community.mycollab.com/) Is there anyone who tested one of those software? I'm also open to any other suggestion.
2014/10/22
[ "https://softwarerecs.stackexchange.com/questions/13383", "https://softwarerecs.stackexchange.com", "https://softwarerecs.stackexchange.com/users/8417/" ]
I'd recommend using **[Trac](http://trac.edgewall.org/)** (for details and screenshots, see my answers [here](https://softwarerecs.stackexchange.com/a/7501/185) and [here](https://softwarerecs.stackexchange.com/a/1560/185). Trac fulfills all your requirements listed: * **Issue tracker:** Yes. * **Wiki:** Yes. * **GIT integration:** Yes, also other VCSs as e.g. SVN or Mercurial are supported. For Git, there's even integration with Github. * **Progress:** Yes, via multiple plugins you can even chose what fits you best. * **Self-hosted:** Definitely, that's what I use. Requirements are at least Python and a web server supporting Python; setup is not that difficult using Apache. A setup [guide for use with SVN can be found on my server](http://www.izzysoft.de/software/ifaqmaker.php?id=1). You can skip the SVN part and take a look at [Installing Trac](http://www.izzysoft.de/software/ifaqmaker.php?id=1;toc=1;topic=trac_install) and [Useful Trac resources](http://www.izzysoft.de/software/ifaqmaker.php?id=1;toc=1;topic=trac_resources). I'm sure there are guides for setting up Trac with Git as well, and probably even more up-to-date ones at that (mine is already a little outdated).
There are various options out there: Gitlab, Redmine, Launchpad, and [others](https://en.wikipedia.org/wiki/Comparison_of_project_management_software). Out of all of these, I have the best experience with **GitLab**, which is used by the likes of the **GNOME project and F-Droid**. (According to Wikipedia, other users include IBM, Sony, Jülich Research Center, NASA, Alibaba, Invincea, O’Reilly Media, Leibniz-Rechenzentrum (LRZ), CERN, European XFEL, and SpaceX) As for your needs: * Issue tracker: yes * Wiki (not mandatory): yes * Git integration: yes * Progress: I think so--see if [milestones](https://docs.gitlab.com/ee/user/project/milestones/) meet your needs * Open-source: yes * Can self-host: yes
53,573,017
I am using lit html to create custom web components in my project. And my problem is when I try to use the CSS target selector in a web component it wont get triggered, but when I am doing it without custom component the code works perfectly. Could someone shed some light to why this is happening and to what would be the workaround for this problem? Here is my code: **target-test-element.js:** ``` import { LitElement, html} from '@polymer/lit-element'; class TargetTest extends LitElement { render(){ return html` <link rel="stylesheet" href="target-test-element.css"> <div class="target-test" id="target-test"> <p>Hello from test</p> </div> `; } } customElements.define('target-test-element', TargetTest); ``` with the following style: **target-test-element.css:** ``` .target-test{ background: yellow; } .target-test:target { background: blue; } ``` and I created a link in the index.html: **index.html(with custom component):** ``` <!DOCTYPE html> <head> ... </head> <body> <target-test-element></target-test-element> <a href="#target-test">Link</a> </body> </html> ``` And here is the working one: **index.html(without custom component)** ``` <!DOCTYPE html> <head> ... </head> <body> <a href="#target-test">Link</a> <div class="target-test" id="target-test"> Hello </div> </body> </html> ```
2018/12/01
[ "https://Stackoverflow.com/questions/53573017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10558165/" ]
LitElement uses a Shadow DOM to render its content. Shadow DOM isolates the CSS style defined inside and prevent selecting inner content from the outide with CSS selectors. For that reason, the `:target` pseudo-class won't work. Instead, you could use a standard (vanilla) custom element instead of the LitElement. With no Shadow DOM: ```js class TargetTest extends HTMLElement { connectedCallback() { this.innerHTML = ` <div> <span class="test" id="target-test">Hello from test</span> </div>` } } customElements.define('target-test-element', TargetTest) ``` ```css .test { background: yellow } .test:target { background: blue } ``` ```html <target-test-element></target-test-element> <a href="#target-test">Link</a> ``` Alternately, if you still want to use a Shadow DOM, you should then set the `id` property to the custom element itself. That supposes there's only one target in the custom element. ```js class TargetTest extends HTMLElement { connectedCallback() { this.attachShadow( { mode: 'open' } ).innerHTML = ` <style> :host( :target ) .test { background-color: lightgreen } </style> <div> <span class="test">Hello from test</span> </div>` } } customElements.define('target-test-element', TargetTest) ``` ```html <target-test-element id="target-test"></target-test-element> <a href="#target-test">Link</a> ```
Bit in late, i've experienced the same problem! So i'm following one of two paths: 1. Use a lit element but without the shadowDOM, to do that in your Lit element call the method **createRenderRoot()** ```js createRenderRoot () { return this } ``` 2. Instead handle the CSS logic with :target i'm handling the attribute on the element (easy to do with Lit) eg. active and use it in CSS: ```css element[active] { /* CSS rules */ } ``` These are my solutions for the moment! Hope it's help...
46,308,541
I have a linechart, and by default I need to show just a subset of elements, then show a different subset on dropdown event. Here is initial code: ``` varlines = svg.append("g") .attr('id', 'lines') .selectAll('g') .data(datum.filter(function(d) { return d.group == 'default' }), function(d) { return d.name } ).enter() .append("g") .attr("class", 'varline') .append("path") .attr("class", "line") .attr("id", function(d) { return 'line_' + d.name }) .attr("d", function(d) { return line(d.datum); }); ``` And it works fine. Now, here is the code that meant to update my selection: ``` $('.dropdown-menu a').click(function(d) { var g = this.text; dd.select("button").text(g) // switch header var newdata = datum.filter(function(d) { return d.group == g }); # datalines for selected group varlines.data(newdata, function(d) { return d.name }) .enter() .merge(varlines) .append("g") .attr("class", 'varline') .attr("id", function(d) { return 'line_' + d.name }) .append("path") .attr("class", "line") .attr("d", function(d) { return line(d.datum); }); varlines.exit().remove() ``` And it works weird. While it adds stuff and does not duplicate dom elements, it doesn't remove old ones. Also, when I `console.log(varlines);` at any step, it shows only two initial elements in the `_groups` Array, and no `_enter` and `_exit` properties, even having 3 lines in the svg. I am using d3v4, jquery3.1.1.slim
2017/09/19
[ "https://Stackoverflow.com/questions/46308541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2286597/" ]
If you look at your `varlines`, you'll see that it is just an **enter** selection: ``` varlines = svg.append("g") .attr('id', 'lines') .selectAll('g') .data(datum.filter(function(d) { return d.group == 'default' }), function(d) { return d.name } ).enter() .append("g") //etc... ``` And, of course, you cannot call `exit()` on an enter selection. Therefore, this: ``` varlines.exit().remove() ``` ... is useless. **Solution**: make `varlines` an "update" selection by breaking it (I'm using `var` here, so we avoid it being a global): ``` var varlines = svg.append("g") .attr('id', 'lines') .selectAll('g') .data(datum.filter(function(d) { return d.group == 'default' }), function(d) { return d.name } ); varlines.enter() .append("g") //etc... ``` Pay attention to this fact: since you're using D3 v4, you have to use `merge()`, otherwise **nothing** will show up the first time the code runs. Alternativelly, you can just duplicate your code: ``` varlines = svg.append("g") .attr('id', 'lines') .selectAll('g') .data(datum.filter(function(d) { return d.group == 'default' }), function(d) { return d.name } ) varlines.enter() .append("g") //all the attributes here varlines.//all the attributes here again ``` EDIT: the problem in your plunker is clear: when you do... ``` .attr("class", "line") ``` ... you are overwriting the previous class. Therefore, it should be: ``` .attr("class", "varline line") ``` Here is the updated plunker: <https://plnkr.co/edit/43suZoDC37TOEfCBJOdT?p=preview>
Here is my new code following Gerardo's recommendations as well as this Mike's tutorial: <https://bl.ocks.org/EmbraceLife/efb531e68ce46c51cb1df2ca360348bb> ``` function update(data) { var varlines = svg.selectAll(".varlines") .data(data, function(d) {return d.name}); // ENTER // Create new elements as needed. // // ENTER + UPDATE varlines.enter().append("g") .attr("class", 'varline') .attr("id", function(d) { return 'line_' + d.name }) .append("path") .attr("class", "line") .attr("d", function(d) { return line(d.datum); }) .style('stroke', function(d) { return z(d.name) }); // .merge(varlines); does not help if uncomment and move after .enter() // EXIT // Remove old elements as needed. varlines.exit().remove(); } ``` and then in the initial code (queue.await(...)): ``` svg.append("g") .attr('id', 'lines'); var data = datum.filter(function(d){return (d.group == settings['groups_settings']['default_group']) && (d.tp == tp)}); update(data) ``` and the same on dropdown change event: ``` var newdata = datum.filter(function(d){return (d.group == g) && (d.tp == tp)}); update(newdata); ``` Behaviour remains the same - correctly displays first batch, but does not remove lines on any changes (just keeps adding lines) on print .selectAll returns this: ``` Selection {_groups: Array(1), _parents: Array(1), _enter: Array(1), _exit: Array(1)} _enter:[Array(6)]_exit :[Array(0)]_groups :[Array(6)] _parents:[svg] __proto__:Object] ``` here is the full code: <https://gist.github.com/Casyfill/78069927d2b95bf4856aa8048a4fa4be>
21,889,087
I'm using this line of code: ``` $("#middle_child").contents().filter(function(){return this.nodeType == Node.TEXT_NODE;}).text(); ``` For now, I'm just placing this in a console.log(). I'm using Chrome for testing & value returns as an empty string, but the value should return "Middle Child". This is the HTML: ``` <div id='parent'> Parent <div id='oldest_child'> Oldest Child <div id='middle_child'> Middle Child <div id='youngest_child'> Youngest Child </div> </div> </div> </div> <div id='lone'>Lonely Div</div> ``` **EDIT**: I tried making a jsfiddle & that did provide me with some potential insight. In the fiddle I selected jQuery 1.6.4 & it worked just fine. The version of jQuery I'm running on my site is 1.6.2. Does anyone know if that could be part (if not all) of my issue?
2014/02/19
[ "https://Stackoverflow.com/questions/21889087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3277004/" ]
You were on the right track. Just needed to make minor changes. The following query will give you the desired results. In inner query got the first 4 columns and to get rank cross joined that to `(SELECT @curRank := 0) r` which is MySQL trick for getting rank. in the end just needed to order by Cnt to make it work. ``` SELECT username ,userid ,category ,Cnt ,@curRank := @curRank + 1 AS rank FROM ( SELECT b.Username ,B.userid ,A.category ,count(*) Cnt FROM tblb B JOIN tbla A ON B.UserID = A.User WHERE a.Category = 1 GROUP BY b.username )a ,(SELECT @curRank := 0) r Order by cnt desc ``` In order to put it into View you can use hack described by [@Gordon-Linoff](https://stackoverflow.com/users/1144035/gordon-linoff) [in this question](https://stackoverflow.com/questions/16280080/assiging-rank-in-mysql-and-view-creation) End code will look something like this. ``` CREATE VIEW TestView1 AS SELECT b.Username ,B.userid ,A.category ,COUNT(*) Cnt FROM tblb B JOIN tbla A ON B.UserID = A.User WHERE a.Category = 1 GROUP BY b.username ORDER BY cnt DESC; CREATE VIEW TestView2 AS SELECT t1.* ,( SELECT 1 + COUNT(*) FROM TestView1 AS t2 WHERE t2.Cnt > t1.Cnt OR ( t2.Cnt = t1.Cnt AND t2.userid < t1.userid ) ) AS Rank FROM TestView1 AS t1 ``` `TestView1` is used to get first 4 columns that you defined. `TestView2` you just select everything from first view and than add column that checks to see if value that you selecting is ether bigger or smaller than value in first instance of that view.
I'm sure SaUce's answer's fine - but there still seems to be too much query there! ``` SELECT username , user , category , COUNT(*) num , @i:=@i+1 rank FROM tbla a JOIN tblB b ON b.userid = a.user , (SELECT @i:=0)var WHERE category = 1 GROUP BY user ORDER BY num DESC; ```
5,391,816
i have a javascript file about 6000+ lines of codes created by myself. Now it has functions for different sections of my site.. Now what i want to ask is that should i use that large file or divide it in parts for respective sections and call it in respective section.
2011/03/22
[ "https://Stackoverflow.com/questions/5391816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229849/" ]
I would suggest using 1 large one, as that requires only 1 http request. And with the right server setup it is only loaded once as it becomes cached.
It depends on how much the HTTP request cost is Vs. how likely a visitor is to access one of the sections with specific JS Vs. how much bandwidth is saved for the other pages.
5,391,816
i have a javascript file about 6000+ lines of codes created by myself. Now it has functions for different sections of my site.. Now what i want to ask is that should i use that large file or divide it in parts for respective sections and call it in respective section.
2011/03/22
[ "https://Stackoverflow.com/questions/5391816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229849/" ]
I would suggest using 1 large one, as that requires only 1 http request. And with the right server setup it is only loaded once as it becomes cached.
If it's just a question of serving the file, then one large one is almost definitely better, particularly if your server has gzip compression turned on (which it should). However, you might also want to break the file up into smaller parts to improve the readability and maintainability aspects of the code. In such a case you might still want to serve out the entire script in a single request, which you can do with a custom servlet (or other comparable bit of server-side logic) that concatenates all the parts together and sends the result to the client.
5,391,816
i have a javascript file about 6000+ lines of codes created by myself. Now it has functions for different sections of my site.. Now what i want to ask is that should i use that large file or divide it in parts for respective sections and call it in respective section.
2011/03/22
[ "https://Stackoverflow.com/questions/5391816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229849/" ]
I would suggest using 1 large one, as that requires only 1 http request. And with the right server setup it is only loaded once as it becomes cached.
Lately, it appears as if the best approach is to split it up into smaller files and load only the needed ones, in parallell, using some kind of JS loader (like [Head JS](http://headjs.com) for example; click the link and scroll down to the headline "Combining scripts" to read more about the performance difference). Another possible loader to use would be [RequireJS](http://requirejs.org/).
5,391,816
i have a javascript file about 6000+ lines of codes created by myself. Now it has functions for different sections of my site.. Now what i want to ask is that should i use that large file or divide it in parts for respective sections and call it in respective section.
2011/03/22
[ "https://Stackoverflow.com/questions/5391816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229849/" ]
It depends on how much the HTTP request cost is Vs. how likely a visitor is to access one of the sections with specific JS Vs. how much bandwidth is saved for the other pages.
If it's just a question of serving the file, then one large one is almost definitely better, particularly if your server has gzip compression turned on (which it should). However, you might also want to break the file up into smaller parts to improve the readability and maintainability aspects of the code. In such a case you might still want to serve out the entire script in a single request, which you can do with a custom servlet (or other comparable bit of server-side logic) that concatenates all the parts together and sends the result to the client.
5,391,816
i have a javascript file about 6000+ lines of codes created by myself. Now it has functions for different sections of my site.. Now what i want to ask is that should i use that large file or divide it in parts for respective sections and call it in respective section.
2011/03/22
[ "https://Stackoverflow.com/questions/5391816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229849/" ]
It depends on how much the HTTP request cost is Vs. how likely a visitor is to access one of the sections with specific JS Vs. how much bandwidth is saved for the other pages.
Lately, it appears as if the best approach is to split it up into smaller files and load only the needed ones, in parallell, using some kind of JS loader (like [Head JS](http://headjs.com) for example; click the link and scroll down to the headline "Combining scripts" to read more about the performance difference). Another possible loader to use would be [RequireJS](http://requirejs.org/).
32,892,143
I have been using nodejs a lot lately but I keep coming up against a similar error. There are a huge amount of projects out there and a lot of them have npm packages, but whenever I attempt `npm install --save some-package` I can't seem to figure out how to use them. I don't mean things like express, or mongoose, which I seem to be able to use just fine. I mean things like Bootstrap, or right now, `masonry-layout`. For instance I followed the steps on the masonry layout page, and executed the following steps: `npm install --save masonry-layout` Then according to the [npm page for masonry-layout](https://www.npmjs.com/package/masonry-layout) I added to following to my general purpose `scripts.js` files (I am keeping small snippets I need in here until I separate code more logically): ``` $('.grid').masonry({ // options... itemSelector: '.grid-item', columnWidth: 200 }); ``` However I get the following error in my console on page load: ``` TypeError: $(...).masonry is not a function $('.grid').masonry({ ``` I get similar problems when I try and use other frontend node modules or projects. Am I missing something? I always just end up using the cdn or installing the files manually and I am getting tired of working that way.
2015/10/01
[ "https://Stackoverflow.com/questions/32892143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091965/" ]
You still need to include those scripts in your page. Use a good old `<script src="…">` or some module loader. (e.g. [require.js](http://requirejs.org/))
what I did was instead of using masonry package download jQuery masonry script and add it as a "script tag" /js file and you can form layout easily in css
32,892,143
I have been using nodejs a lot lately but I keep coming up against a similar error. There are a huge amount of projects out there and a lot of them have npm packages, but whenever I attempt `npm install --save some-package` I can't seem to figure out how to use them. I don't mean things like express, or mongoose, which I seem to be able to use just fine. I mean things like Bootstrap, or right now, `masonry-layout`. For instance I followed the steps on the masonry layout page, and executed the following steps: `npm install --save masonry-layout` Then according to the [npm page for masonry-layout](https://www.npmjs.com/package/masonry-layout) I added to following to my general purpose `scripts.js` files (I am keeping small snippets I need in here until I separate code more logically): ``` $('.grid').masonry({ // options... itemSelector: '.grid-item', columnWidth: 200 }); ``` However I get the following error in my console on page load: ``` TypeError: $(...).masonry is not a function $('.grid').masonry({ ``` I get similar problems when I try and use other frontend node modules or projects. Am I missing something? I always just end up using the cdn or installing the files manually and I am getting tired of working that way.
2015/10/01
[ "https://Stackoverflow.com/questions/32892143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091965/" ]
You still need to include those scripts in your page. Use a good old `<script src="…">` or some module loader. (e.g. [require.js](http://requirejs.org/))
The `masonry-layout` npm package will install the .js you need into `node_modules/masonry-layout/dist/masonry.pkgd.min.js`. You need to include that file in a `<script>` tag on your page.
28,824,570
So Im keep coming up with typeError: Cannot read property 'style' undefined. It situated on the last line of javascript. Anyone any suggestions. The finished piece is to be a marquee with vertically scrolling text. ```js window.onload = defineMarquee; var timeID; var marqueeTxt = new Array(); var marqueeOff = true; /* defineMarquee() Initializes the contents of the marquee, determines the top style positions of each marquee item, and sets the onclick event handlers for the document */ function defineMarquee() { var topValue var allElems = document.getElementsByTagName("*"); for (var i = 0; i < allElems.length; i++) { if (allElems[i].className == "marqueeTxt") marqueeTxt.push(allElems[i]); } //Extract the "top" CSS class from marqueeTxt for (var i = 0; i < marqueeTxt.length; i++) { if (marqueeTxt[i].getComputedStyle) { topValue = marqueeTxt[i].getPropertyValue("top") } else if (marqueeTxt[i].currentStyle) { topValue = marqueeTxt[i].currentStyle("top"); } marqueeTxt[i].style.top = topValue; } document.getElementById("startMarquee").onclick = startMarquee; document.getElementById("stopMarquee").onclick = stopMarquee; } /* startMarquee() Starts the marquee in motion */ function startMarquee() { if (marqueeOff == true) { timeID = setInterval("moveText()", 50); marqueeOff = false; } } /* stopMarquee() Stops the Marquee */ function stopMarquee() { clearInterval(timeID); marqueeOff = true; } /* moveText () move the text within the marquee in a vertical direction */ function moveText() { for (var i = 0; i < marqueeTxt.length; i++) { topPos = parseInt(marqueeTxt[i].style.top); } if (topPos < -110) { topPos = 700; } else { topPos -= 1; } marqueeTxt[i].style.top = topPos + "px"; } ``` ```css * { margin: 0px; padding: 0px } body { font-size: 15px; font-family: Arial, Helvetica, sans-serif } #pageContent { position: absolute; top: 0px; left: 30px; width: 800px } #links { display: block; width: 100%; margin-bottom: 20px; border-bottom: 1px solid rgb(0, 153, 102); float: left } #links { list-style-type: none } #links li { display: block; float: left; text-align: center; width: 19% } #links li a { display: block; width: 100%; text-decoration: none; color: black; background-color: white } #links li a:hover { color: white; background-color: rgb(0, 153, 102) } #leftCol { clear: left; float: left } h1 { font-size: 24px; letter-spacing: 5px; color: rgb(0, 153, 102) } #main { float: left; width: 450px; margin-left: 10px; padding-left: 10px; border-left: 1px solid rgb(0, 153, 102); padding-bottom: 15px } #main img { float: right; margin: 0px 0px 10px 10px } #main p { margin-bottom: 10px } address { width: 100%; clear: left; font-style: normal; font-size: 12px; border-top: 1px solid black; text-align: center; padding-bottom: 15px } .marquee { position: absolute; top: 0px; left: 0px; width: 280px; height: 300px; background-color: rgb(0, 153, 102); color: white; border: 5px inset white; padding: 0px; overflow: hidden; position: relative } #marqueeTxt1 { font-size: 1.4em; letter-spacing: 0.15em; border-bottom: 1px solid white } input { width: 120px; margin: 5px; font-size: 0.9em } #marqueeButtons { width: 280px; text-align: center } #marqueeTxt1 { position: absolute; top: 40px; left: 20px } #marqueeTxt2 { position: absolute; top: 90px; left: 20px } #marqueeTxt3 { position: absolute; top: 170px; left: 20px } #marqueeTxt4 { position: absolute; top: 250px; left: 20px } #marqueeTxt5 { position: absolute; top: 330px; left: 20px } #marqueeTxt6 { position: absolute; top: 410px; left: 20px } #marqueeTxt7 { position: absolute; top: 490px; left: 20px } #marqueeTxt8 { position: absolute; top: 570px; left: 20px } #marqueeTxt9 { position: absolute; top: 640px; left: 20px } ``` ```html <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!-- New Perspectives on JavaScript, 2nd Edition Tutorial 4 Case Problem 3 BYSO Web Page Author: Gavin Macken Date: 28 Feb `15 Filename: byso.htm Supporting files: bstyles.css, byso.jpg, bysologo.jpg, marquee.js --> <title>Boise Youth Symphony Orchestra</title> <link href="bstyles.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="marquee.js"></script> </head> <body> <form id="marqueeForm" action=""> <div id="pageContent"> <div id="head"> <img src="bysologo.jpg" alt="Boise Youth Symphony Orchestra" /> </div> <ul id="links"> <li><a href="#">Home Page</a> </li> <li><a href="#">About BYSO</a> </li> <li><a href="#">Our Director</a> </li> <li><a href="#">Join BYSO</a> </li> <li><a href="#">Contact Us</a> </li> </ul> <div id="leftCol"> <div class="marquee"> <div id="marqueeTxt1" class="marqueeTxt"> Schedule of Events </div> <div id="marqueeTxt2" class="marqueeTxt"> Holiday Concert <br />December 14, 7:30 PM <br />Boise Civic Center </div> <div id="marqueeTxt3" class="marqueeTxt"> Christmas Concert <br />Dec. 16, 7 PM <br />Our Savior Episcopal Church </div> <div id="marqueeTxt4" class="marqueeTxt"> Spring Concert <br />Feb. 27, 7 PM <br />Boise Civic Center </div> <div id="marqueeTxt5" class="marqueeTxt"> Easter Fanfare <br />March 14, 9 PM <br />Our Savior Episcopal Church </div> <div id="marqueeTxt6" class="marqueeTxt"> High School MusicFest <br />May 2, 3 PM <br />Boise Central High School </div> <div id="marqueeTxt7" class="marqueeTxt"> Summer Concert <br />June 15, 7:30 PM <br />Frontier Concert Hall </div> <div id="marqueeTxt8" class="marqueeTxt"> Fourth Fest <br />July 4, 4 PM <br />Canyon View Park </div> <div id="marqueeTxt9" class="marqueeTxt"> Frontier Days <br />August 9, 1 PM <br />Boise Concert Hall </div> </div> <div id="marqueeButtons"> <input type="button" id="startMarquee" value="Start Marquee" /> <input type="button" id="stopMarquee" value="Pause Marquee" /> </div> </div> <div id="main"> <h1>Boise Youth Symphony Orchestra</h1> <img src="byso.jpg" alt="" /> <p>The Boise Youth Symphony Orchestra has delighted audiences worldwide with beautiful music while offering the highest quality musical training to over 1,000 teens throughout Idaho for the past 30 years. BYSO has established an outstanding reputation for its high quality sound, its series of commissioned works, and collaborations with prominent musical groups such as the Idaho and Boise Symphony Orchestras, the Montana Chamber Orchestra, the Boise Adult Choir and the Western Symphony Orchestra. Last year the group was invited to serve as the U.S. representative to the 7th Annual World Festival of youth orchestras in Poznan, Poland.</p> <p>Leading this success for the past decade has been Boise Symphony artistic director Denise Young. In a concert review by John Aehl, music critic for the <i>Boise Times</i>, Roger Adler writes, "It is a pleasure to report that the orchestra is playing better than ever."</p> </div> <address> BYSO &#183; 300 Mountain Lane &#183; Boise, Idaho 83702 &#183; (208) 555 - 9114 </address> </div> </form> </body> </html> ```
2015/03/03
[ "https://Stackoverflow.com/questions/28824570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4318762/" ]
1. Hmm no, because with your piece of code you make ALL methods on the collection class available for a static call. That's not the purpose of the (abstract) factory pattern. 2. (Magic) methods like `__callStatic` or `call_user_func_array` are very tricky because a developer can use it to call every method. 3. What would you really like to do? Implement the factory pattern OR use static one-liner methods for your MongoDB implementation?! If the implementation of the book and author collection has different methods(lets say getName() etc..) I recommend something like this: ``` class BookCollection extends Collection { protected $collection = 'book'; public function getName() { return 'Book!'; } } class AuthorCollection extends Collection { protected $collection = 'author'; public function getName() { return 'Author!'; } } class Collection { private $adapter = null; public function __construct() { $this->getAdapter()->selectCollection($this->collection); } public function findOne($query = array(), $projection = array()) { $doc = $this->getAdapter()->findOne($query, $projection); return isset($doc) ? new Document($doc) : false; } public function getAdapter() { // some get/set dep.injection for mongo if(isset($this->adapter)) { return $this->adapter; } return new Mongo(); } } class CollectionFactory { public static function build($collection) { switch($collection) { case 'book': return new BookCollection(); break; case 'author': return new AuthorCollection(); break; } // or use reflection magic } } $bookCollection = CollectionFactory::build('book'); $bookCollection->findOne(array('name' => 'Google')); print $bookCollection->getName(); // Book! ``` **Edit: An example with static one-liner methods** ``` class BookCollection extends Collection { protected static $name = 'book'; } class AuthorCollection extends Collection { protected static $name = 'author'; } class Collection { private static $adapter; public static function setAdapter($adapter) { self::$adapter = $adapter; } public static function getCollectionName() { $self = new static(); return $self::$name; } public function findOne($query = array(), $projection = array()) { self::$adapter->selectCollection(self::getCollectionName()); $doc = self::$adapter->findOne($query, $projection); return $doc; } } Collection::setAdapter(new Mongo()); //initiate mongo adapter (once) BookCollection::findOne(array('name' => 'Google')); AuthorCollection::findOne(array('name' => 'John')); ```
Does it make sense for `Collection` to extend `Document`? It seems to me like a `Collection` could *have* `Document`(s), but not *be* a `Document`... So I would say this code looks a bit tangled. Also, with the factory method, you really want to use that to instantiate a different concrete subclass of either `Document` or `Collection`. Let's suppose you've only ever got one type of `Collection` for ease of conversation; then your factory class needs only focus on the different `Document` subclasses. So you might have a `Document` class that expects a raw `array` representing a single document. ``` class Document { private $_aRawDoc; public function __construct(array $aRawDoc) { $this->_aRawDoc = $aRawDoc; } // Common Document methods here.. } ``` Then specialized subclasses for given Document types ``` class Book extends Document { // Specialized Book functions ... } ``` For the factory class you'll need something that will then wrap your raw results as they are read off the cursor. PDO let's you do this out of the box (see the `$className` parameter of [`PDOStatement::fetchObject`](http://php.net/manual/en/pdostatement.fetchobject.php) for example), but we'll need to use a decorator since PHP doesn't let us get as fancy with the Mongo extension. ``` class MongoCursorDecorator implements MongoCursorInterface, Iterator { private $_sDocClass; // Document class to be used private $_oCursor; // Underlying MongoCursor instance private $_aDataObjects = []; // Concrete Document instances // Decorate the MongoCursor, so we can wrap the results public function __construct(MongoCursor $oCursor, $sDocClass) { $this->_oCursor = $oCursor; $this->_sDocClass = $sDocClass; } // Delegate to most of the stock MongoCursor methods public function __call($sMethod, array $aParams) { return call_user_func_array([$this->_oCursor, $sMethod], $aParams); } // Wrap the raw results by our Document classes public function current() { $key = $this->key(); if(!isset($this->_aDataObjects[$key])) $this->_aDataObjects[$key] = new $this->sDocClass(parent::current()); return $this->_aDataObjects[$key]; } } ``` Now a sample of how you would query mongo for books by a given author ``` $m = new MongoClient(); $db = $m->selectDB('test'); $collection = new MongoCollection($db, 'book'); // search for author $bookQuery = array('Author' => 'JR Tolken'); $cursor = $collection->find($bookQuery); // Wrap the native cursor by our Decorator $cursor = new MongoCursorDecorator($cursor, 'Book'); foreach ($cursor as $doc) { var_dump($doc); // This will now be an instance of Book } ``` You could tighten it up a bit with a `MongoCollection` subclass and you may as well have it anyway, since you'll want the `findOne` method decorating those raw results too. ``` class MongoDocCollection extends MongoCollection { public function find(array $query=[], array $fields=[]) { // The Document class name is based on the collection name $sDocClass = ucfirst($this->getName()); $cursor = parent::find($query, $fields); $cursor = new MongoCursorDecorator($cursor, $sDocClass); return $cursor; } public function findOne( array $query=[], array $fields=[], array $options=[] ) { $sDocClass = ucfirst($this->getName()); return new $sDocClass(parent::findOne($query, $fields, $options)); } } ``` Then our sample usage becomes ``` $m = new MongoClient(); $db = $m->selectDB('test'); $collection = new MongoDocCollection($db, 'book'); // search for author $bookQuery = array('Author' => 'JR Tolken'); $cursor = $collection->find($bookQuery); foreach($cursor as $doc) { var_dump($doc); // This will now be an instance of Book } ```
252,729
I know you get 2 set pieces in the new season for reaching level 70, what else do you have to do to get the other 4 pieces? Can you get a free set again if you complete the parameters with a new character?
2016/01/21
[ "https://gaming.stackexchange.com/questions/252729", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/73403/" ]
You get two more set pieces for completing the Chapter 4 objective "Mercy" (Defeat Zoltan Kulle on Torment II) and two pieces for completing the Chapter 4 objective "Great Expectations" (Complete a Level 20 Greater Rift solo).
As yuuki didn't answer this: **NO**, you can't get the items on other characters.
31,655,986
I have an asp.net gridview which displays two rows for each record, using the following code below (example). However using a dropdownlist which is on the top of the page, based on its selection (1 or 2) I want the gridview to update itself on the following way: option 1 = display two rows per record. option 2 = display only one row per record (second table row shown on code below I don't want it to be shown when Option 2 is selected. UPDATE: Selecting the dropdownlist option and making it work is fine, I don't have a problem there, but I need to know how to manipulate the gridview to display one or two rows per record. So basically how can I (with code) change the format of the gridview from 1 to 2 rows. Obviously there is the option of using two gridviews and show the one needed based on your selection, but I prefer to use one gridview only (if that's possible). ``` <HeaderTemplate> <asp:LinkButton ID="lbPN" runat="server" Text="Project Name" style "color:white;" CommandName="Sort" CommandArgument="PN" tabindex="1000" ></asp:LinkButton><br /> <asp:TextBox runat="server" ID="S_PN" CssClass="FilterField" ></asp:TextBox> </HeaderTemplate> <ItemTemplate> <table > <tr> <td class="STD_normal" style="width:150px; font-weight:bold"><%#Eval("PN")%> </td> </tr> <tr> <td class="STD_Normal_Grey" style="width:150px"><%#Eval("DD", "{0:dd-MMM-yyyy}")%> </td> </tr> </table> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"/> </asp:TemplateField> ```
2015/07/27
[ "https://Stackoverflow.com/questions/31655986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1135218/" ]
**Client Side** One way would be to use JavaScript or jQuery to show/hide the second row. For this, I recommend replacing the table with `<div>`'s and adding the class to the `div` tag instead of the `td` tag, or splitting out the tables, as shown in the Server Side example. Here's a jQuery example: ``` $("#ddl").change(function() { if($('#ddl option:selected').val() == 1) { $('STD_Normal_Grey').show(); } else { $('STD_Normal_Grey').hide(); } } ``` **Server Side** Here's another example showing a server side option, as well as how you might be able to split out the tables to make controlling the display a bit easier: ``` <table> <tr> <td class="STD_normal" style="width:150px; font-weight:bold"> <%#Eval("PN")%> </td> </tr> </table> <table style="display:<%# DdlVal == "1" ? "inline-block" : "none" %>;"> <tr> <td class="STD_Normal_Grey" style="width:150px"> <%#Eval("DD", "{0:dd-MMM-yyyy}")%> </td> </tr> </table> ``` Then, in your code behind: ``` protected string DdlVal { get { return ddl.SelectedValue; } } ``` This would require the DropDownList to post back, whereas the Client Side solution would not, making the Client Side solution much faster.
with a dropdownlist you could use the OnSelectedIndexChanged function. like this: ```html <asp:DropDownList runat="server" ID="ddlDemo" on SelectedIndexChanged="ddlDemo_SelectedIndexChanged"> <asp:ListItem Value="1">one</asp:ListItem><asp:ListItem Value="2">tow</asp:ListItem> </asp:DropDownList> ``` and in the code you could play with it: ```html Protected Sub ddlDemo_SelectedIndexChanged(sender As Object, e As EventArgs) Dim selectedValue As Integer = ddlDemo.SelectedValue If ddlDemo.SelectedValue = 1 Then ' do something End If End Sub ```
31,655,986
I have an asp.net gridview which displays two rows for each record, using the following code below (example). However using a dropdownlist which is on the top of the page, based on its selection (1 or 2) I want the gridview to update itself on the following way: option 1 = display two rows per record. option 2 = display only one row per record (second table row shown on code below I don't want it to be shown when Option 2 is selected. UPDATE: Selecting the dropdownlist option and making it work is fine, I don't have a problem there, but I need to know how to manipulate the gridview to display one or two rows per record. So basically how can I (with code) change the format of the gridview from 1 to 2 rows. Obviously there is the option of using two gridviews and show the one needed based on your selection, but I prefer to use one gridview only (if that's possible). ``` <HeaderTemplate> <asp:LinkButton ID="lbPN" runat="server" Text="Project Name" style "color:white;" CommandName="Sort" CommandArgument="PN" tabindex="1000" ></asp:LinkButton><br /> <asp:TextBox runat="server" ID="S_PN" CssClass="FilterField" ></asp:TextBox> </HeaderTemplate> <ItemTemplate> <table > <tr> <td class="STD_normal" style="width:150px; font-weight:bold"><%#Eval("PN")%> </td> </tr> <tr> <td class="STD_Normal_Grey" style="width:150px"><%#Eval("DD", "{0:dd-MMM-yyyy}")%> </td> </tr> </table> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"/> </asp:TemplateField> ```
2015/07/27
[ "https://Stackoverflow.com/questions/31655986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1135218/" ]
There is code based on one of my database, just change parameters (this is *server side* example, someone else provide here client side example) : aspx : ``` <asp:DropDownList runat="server" ID="ddlChoice" AutoPostBack="true"> <asp:ListItem Text="One row"></asp:ListItem> <asp:ListItem Text="Two rows"></asp:ListItem> </asp:DropDownList> <br /><br /> <asp:GridView runat="server" ID="grdInfo" DataSourceID="sqlInfo"> <Columns> <asp:TemplateField> <HeaderTemplate> <asp:LinkButton ID="lbPN" runat="server" Text="Project Name" style="color:white;" CommandName="Sort" CommandArgument="PN" tabindex="1000" ></asp:LinkButton><br /> <asp:TextBox runat="server" ID="S_PN" CssClass="FilterField" ></asp:TextBox> </HeaderTemplate> <ItemTemplate> <table> <tr><td runat="server" id="tdFirst" class="STD_normal" style="width:150px; display:block; font-weight:bold"><%# Eval("PNaziv")%></td></tr> <tr><td runat="server" id="tdSecond" class="STD_Normal_Grey" style="width:150px; display:none;"><%#Eval("PMesto")%></td></tr> </table> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:SqlDataSource ID="sqlInfo" runat="server" ConnectionString="<%$ ConnectionStrings:MDFConnection %>" SelectCommand="SELECT PNaziv,PMesto FROM Partneri ORDER BY PNaziv;" ></asp:SqlDataSource> ``` code behind (vb.net) ``` Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load End Sub Private Sub ddlChoice_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlChoice.SelectedIndexChanged grdInfo.DataBind() End Sub Private Sub grdInfo_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdInfo.RowCreated If e.Row.RowType = DataControlRowType.DataRow Then Dim td As HtmlTableCell = e.Row.Cells(0).FindControl("tdSecond") If ddlChoice.SelectedIndex = 0 Then td.Style("display") = "none" Else td.Style("display") = "block" End If End Sub ``` Like I wrote in comment, I set to each `td` `id` and `runat="server"`. Dropdownlist must have `AutoPostBack="true"`. Now, on every `SelectedIndexChanged` must bind Your grid and on every created row find `HtmlTableCell`, now, control (it's `td`) and based on selected index show or hide second `td`. But, under `style` of every `td` I put `display:block/none;` depend of row. When You start webapp only one row will be visible, and after that, depend of dropdownlist choice. In this example that table is in first column (`Dim td As HtmlTableCell = e.Row.Cells(0).FindControl("tdSecond")`)... You have to change that `.e.Row.Cells(x)...`; where *x* is Your column index. **Update :** You not define prog.language so bellow code is in `c#` (converted from vb.net using online conversion tool, sorry I programming in vb.net) ``` private void ddlChoice_SelectedIndexChanged(object sender, System.EventArgs e) { grdInfo.DataBind(); } private void grdInfo_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { HtmlTableCell td = e.Row.Cells[0].FindControl("tdSecond"); if (ddlChoice.SelectedIndex == 0) td.Style("display") = "none"; else td.Style("display") = "block"; } } ```
with a dropdownlist you could use the OnSelectedIndexChanged function. like this: ```html <asp:DropDownList runat="server" ID="ddlDemo" on SelectedIndexChanged="ddlDemo_SelectedIndexChanged"> <asp:ListItem Value="1">one</asp:ListItem><asp:ListItem Value="2">tow</asp:ListItem> </asp:DropDownList> ``` and in the code you could play with it: ```html Protected Sub ddlDemo_SelectedIndexChanged(sender As Object, e As EventArgs) Dim selectedValue As Integer = ddlDemo.SelectedValue If ddlDemo.SelectedValue = 1 Then ' do something End If End Sub ```
31,655,986
I have an asp.net gridview which displays two rows for each record, using the following code below (example). However using a dropdownlist which is on the top of the page, based on its selection (1 or 2) I want the gridview to update itself on the following way: option 1 = display two rows per record. option 2 = display only one row per record (second table row shown on code below I don't want it to be shown when Option 2 is selected. UPDATE: Selecting the dropdownlist option and making it work is fine, I don't have a problem there, but I need to know how to manipulate the gridview to display one or two rows per record. So basically how can I (with code) change the format of the gridview from 1 to 2 rows. Obviously there is the option of using two gridviews and show the one needed based on your selection, but I prefer to use one gridview only (if that's possible). ``` <HeaderTemplate> <asp:LinkButton ID="lbPN" runat="server" Text="Project Name" style "color:white;" CommandName="Sort" CommandArgument="PN" tabindex="1000" ></asp:LinkButton><br /> <asp:TextBox runat="server" ID="S_PN" CssClass="FilterField" ></asp:TextBox> </HeaderTemplate> <ItemTemplate> <table > <tr> <td class="STD_normal" style="width:150px; font-weight:bold"><%#Eval("PN")%> </td> </tr> <tr> <td class="STD_Normal_Grey" style="width:150px"><%#Eval("DD", "{0:dd-MMM-yyyy}")%> </td> </tr> </table> </ItemTemplate> <HeaderStyle HorizontalAlign="Left"/> </asp:TemplateField> ```
2015/07/27
[ "https://Stackoverflow.com/questions/31655986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1135218/" ]
There is code based on one of my database, just change parameters (this is *server side* example, someone else provide here client side example) : aspx : ``` <asp:DropDownList runat="server" ID="ddlChoice" AutoPostBack="true"> <asp:ListItem Text="One row"></asp:ListItem> <asp:ListItem Text="Two rows"></asp:ListItem> </asp:DropDownList> <br /><br /> <asp:GridView runat="server" ID="grdInfo" DataSourceID="sqlInfo"> <Columns> <asp:TemplateField> <HeaderTemplate> <asp:LinkButton ID="lbPN" runat="server" Text="Project Name" style="color:white;" CommandName="Sort" CommandArgument="PN" tabindex="1000" ></asp:LinkButton><br /> <asp:TextBox runat="server" ID="S_PN" CssClass="FilterField" ></asp:TextBox> </HeaderTemplate> <ItemTemplate> <table> <tr><td runat="server" id="tdFirst" class="STD_normal" style="width:150px; display:block; font-weight:bold"><%# Eval("PNaziv")%></td></tr> <tr><td runat="server" id="tdSecond" class="STD_Normal_Grey" style="width:150px; display:none;"><%#Eval("PMesto")%></td></tr> </table> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:SqlDataSource ID="sqlInfo" runat="server" ConnectionString="<%$ ConnectionStrings:MDFConnection %>" SelectCommand="SELECT PNaziv,PMesto FROM Partneri ORDER BY PNaziv;" ></asp:SqlDataSource> ``` code behind (vb.net) ``` Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load End Sub Private Sub ddlChoice_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlChoice.SelectedIndexChanged grdInfo.DataBind() End Sub Private Sub grdInfo_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdInfo.RowCreated If e.Row.RowType = DataControlRowType.DataRow Then Dim td As HtmlTableCell = e.Row.Cells(0).FindControl("tdSecond") If ddlChoice.SelectedIndex = 0 Then td.Style("display") = "none" Else td.Style("display") = "block" End If End Sub ``` Like I wrote in comment, I set to each `td` `id` and `runat="server"`. Dropdownlist must have `AutoPostBack="true"`. Now, on every `SelectedIndexChanged` must bind Your grid and on every created row find `HtmlTableCell`, now, control (it's `td`) and based on selected index show or hide second `td`. But, under `style` of every `td` I put `display:block/none;` depend of row. When You start webapp only one row will be visible, and after that, depend of dropdownlist choice. In this example that table is in first column (`Dim td As HtmlTableCell = e.Row.Cells(0).FindControl("tdSecond")`)... You have to change that `.e.Row.Cells(x)...`; where *x* is Your column index. **Update :** You not define prog.language so bellow code is in `c#` (converted from vb.net using online conversion tool, sorry I programming in vb.net) ``` private void ddlChoice_SelectedIndexChanged(object sender, System.EventArgs e) { grdInfo.DataBind(); } private void grdInfo_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { HtmlTableCell td = e.Row.Cells[0].FindControl("tdSecond"); if (ddlChoice.SelectedIndex == 0) td.Style("display") = "none"; else td.Style("display") = "block"; } } ```
**Client Side** One way would be to use JavaScript or jQuery to show/hide the second row. For this, I recommend replacing the table with `<div>`'s and adding the class to the `div` tag instead of the `td` tag, or splitting out the tables, as shown in the Server Side example. Here's a jQuery example: ``` $("#ddl").change(function() { if($('#ddl option:selected').val() == 1) { $('STD_Normal_Grey').show(); } else { $('STD_Normal_Grey').hide(); } } ``` **Server Side** Here's another example showing a server side option, as well as how you might be able to split out the tables to make controlling the display a bit easier: ``` <table> <tr> <td class="STD_normal" style="width:150px; font-weight:bold"> <%#Eval("PN")%> </td> </tr> </table> <table style="display:<%# DdlVal == "1" ? "inline-block" : "none" %>;"> <tr> <td class="STD_Normal_Grey" style="width:150px"> <%#Eval("DD", "{0:dd-MMM-yyyy}")%> </td> </tr> </table> ``` Then, in your code behind: ``` protected string DdlVal { get { return ddl.SelectedValue; } } ``` This would require the DropDownList to post back, whereas the Client Side solution would not, making the Client Side solution much faster.
72,341,977
I have been trying to find solutions for this for a few days now and can't seem to get anything to work. The script below shows/hides columns in the tabs and works perfectly in the named sheet. I just need it to run through all of the tabs, **except for the first few**,and be applied in them too. I just don't understand how it all works so am getting stuck. All help hugely appreciated!!!!!! ``` function hidecolumns() { var ss = SpreadsheetApp.getActive(); var sh = ss.getSheetByName('Jun 2025 2HR'); var first_row = sh.getRange(2,1,1,sh.getMaxColumns()).getValues().flat(); first_row.forEach((fr,i)=>{ if(fr==0){ sh.hideColumns(i+1); } else { sh.showColumns(i+1); } }) } ```
2022/05/22
[ "https://Stackoverflow.com/questions/72341977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19176386/" ]
SQLAlchemy itself only calls the cursor's `execute` method, which does not support executing multiple statements. However it's possible to access the DB API connection directly, and call its `executescript` method: ```py import sqlalchemy as sa engine = sa.create_engine('sqlite:///so72341960.db') # Create a table for our example. tbl = sa.Table( 'mytable', sa.MetaData(), sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.String), ) # Ensure we start with a clean table. tbl.drop(engine, checkfirst=True) tbl.create(engine) SQL = """ INSERT INTO mytable (name) VALUES ('Alice'); INSERT INTO mytable (name) VALUES ('Bob'); """ with engine.begin() as conn: dbapi_conn = conn.connection dbapi_conn.executescript(SQL) ```
This is because sqlite3 only supports executing one statement at a time. If you want to execute multiple statements, they need to be separate commands. For example, ```py statements = [] // put your statements in this array for statement in statements: session.execute(text(statement)) ``` This will iterate over the array of statements and execute each one in turn.
8,188,172
I am pretty new to rails so this may be an easy question, but I was looking to create a Rails app that would use youtube in it. I have found that youtube\_it seems to be the gem of choice for a task like this but I am having trouble using it. Basically, I want to use the gem so that I can get videos from specific users, i.e. Stanford University and create a list of those videos with links to another page that has the video information and player. To test this out I tried the follow code: application\_controller.rb ``` class ApplicationController < ActionController::Base protect_from_forgery helper_method :yt_client private def yt_client @yt_client ||= YouTubeIt::Client.new(:dev_key => dev_key) end end ``` home\_controller.rb ``` class HomeController < ApplicationController def index @playlists = yt_client.playlists('stanforduniversity') end end ``` index.html.erb ``` <h3>Home</h3> <% @playlists.each do |playlist| %> <p>Playlist: <%= playlist %></p> <% end %> ``` The problem with this is all I get for output on my home page is a list of something like this: # My questions then are: is there a way to change this output into an actual title? Am I doing something wrong/forgetting a step? Or should I just use python code to use the Google API and put all the videos into my database(I already have some code for this) and just access it using my rails app? Hope this is clear enough.
2011/11/18
[ "https://Stackoverflow.com/questions/8188172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1054494/" ]
it looks like what you want to print out is the name of the playlist - but that is an attribute of the playlist object, so you'll need something like: ``` <% @playlists.each do |playlist| %> <p>Playlist: <%= playlist.title %></p> <% end %> ``` otherwise ruby is trying to "print" the playlist object - which just doesn't work the way you expect. Note: I've not used this gem either, I'm gathering this info from the gem docs here: <https://github.com/kylejginavan/youtube_it>
<https://github.com/kylejginavan/youtube_it> or youtube\_it is the new version of youtube\_g. This was forked and enhanced. If you need any enhancements please reach out to me.
8,188,172
I am pretty new to rails so this may be an easy question, but I was looking to create a Rails app that would use youtube in it. I have found that youtube\_it seems to be the gem of choice for a task like this but I am having trouble using it. Basically, I want to use the gem so that I can get videos from specific users, i.e. Stanford University and create a list of those videos with links to another page that has the video information and player. To test this out I tried the follow code: application\_controller.rb ``` class ApplicationController < ActionController::Base protect_from_forgery helper_method :yt_client private def yt_client @yt_client ||= YouTubeIt::Client.new(:dev_key => dev_key) end end ``` home\_controller.rb ``` class HomeController < ApplicationController def index @playlists = yt_client.playlists('stanforduniversity') end end ``` index.html.erb ``` <h3>Home</h3> <% @playlists.each do |playlist| %> <p>Playlist: <%= playlist %></p> <% end %> ``` The problem with this is all I get for output on my home page is a list of something like this: # My questions then are: is there a way to change this output into an actual title? Am I doing something wrong/forgetting a step? Or should I just use python code to use the Google API and put all the videos into my database(I already have some code for this) and just access it using my rails app? Hope this is clear enough.
2011/11/18
[ "https://Stackoverflow.com/questions/8188172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1054494/" ]
it looks like what you want to print out is the name of the playlist - but that is an attribute of the playlist object, so you'll need something like: ``` <% @playlists.each do |playlist| %> <p>Playlist: <%= playlist.title %></p> <% end %> ``` otherwise ruby is trying to "print" the playlist object - which just doesn't work the way you expect. Note: I've not used this gem either, I'm gathering this info from the gem docs here: <https://github.com/kylejginavan/youtube_it>
you have a complete demo that I made here <http://youtube-it.heroku.com/> included source!
54,264,668
Hello everyone i have the following row as a sample in my table ``` id shop_id start_time end_time 1 21 10:00 11:00 ``` and i want to check whether start\_time and end\_time exist in table or not I am using following query but not working correctly, Where i am wrong ? ``` select * from usr_booking where shop_id='21' and start_time between '10:10:00' and '11:01:00' or end_time between '10:10:00' and '11:01:00' ```
2019/01/19
[ "https://Stackoverflow.com/questions/54264668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10784895/" ]
You need to clearly separate the checks on the `shop_id` and the time ranges: ``` SELECT * FROM usr_booking WHERE shop_id = 21 AND (start_time BETWEEN '10:10:00' AND '11:01:00' OR end_time BETWEEN '10:10:00' AND '11:01:00'); ``` The `AND` operator in MySQL has higher precedence than the `OR` operator. So, your current query is actually evaluating as this: ``` SELECT * FROM usr_booking WHERE (shop_id = 21 AND start_time BETWEEN '10:10:00' AND '11:01:00') OR end_time BETWEEN '10:10:00' AND '11:01:00'; ``` Clearly, this is not the same logic as you what you probably intended.
Try to make groups in such type of queries ``` select * from usr_booking where shop_id='21' AND ((start_time between '10:10:00' and '11:01:00') OR (end_time between '10:10:00' and '11:01:00')) ``` Add the extra brackets make groups.
54,264,668
Hello everyone i have the following row as a sample in my table ``` id shop_id start_time end_time 1 21 10:00 11:00 ``` and i want to check whether start\_time and end\_time exist in table or not I am using following query but not working correctly, Where i am wrong ? ``` select * from usr_booking where shop_id='21' and start_time between '10:10:00' and '11:01:00' or end_time between '10:10:00' and '11:01:00' ```
2019/01/19
[ "https://Stackoverflow.com/questions/54264668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10784895/" ]
You need to clearly separate the checks on the `shop_id` and the time ranges: ``` SELECT * FROM usr_booking WHERE shop_id = 21 AND (start_time BETWEEN '10:10:00' AND '11:01:00' OR end_time BETWEEN '10:10:00' AND '11:01:00'); ``` The `AND` operator in MySQL has higher precedence than the `OR` operator. So, your current query is actually evaluating as this: ``` SELECT * FROM usr_booking WHERE (shop_id = 21 AND start_time BETWEEN '10:10:00' AND '11:01:00') OR end_time BETWEEN '10:10:00' AND '11:01:00'; ``` Clearly, this is not the same logic as you what you probably intended.
Try this Query: ``` SELECT * FROM usr_booking Where shop_id='21' AND start_time BETWEEN '10:10:00' AND '11:01:00' AND end_time BETWEEN '10:10:00' AND '11:01:00' ```
54,264,668
Hello everyone i have the following row as a sample in my table ``` id shop_id start_time end_time 1 21 10:00 11:00 ``` and i want to check whether start\_time and end\_time exist in table or not I am using following query but not working correctly, Where i am wrong ? ``` select * from usr_booking where shop_id='21' and start_time between '10:10:00' and '11:01:00' or end_time between '10:10:00' and '11:01:00' ```
2019/01/19
[ "https://Stackoverflow.com/questions/54264668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10784895/" ]
You need to clearly separate the checks on the `shop_id` and the time ranges: ``` SELECT * FROM usr_booking WHERE shop_id = 21 AND (start_time BETWEEN '10:10:00' AND '11:01:00' OR end_time BETWEEN '10:10:00' AND '11:01:00'); ``` The `AND` operator in MySQL has higher precedence than the `OR` operator. So, your current query is actually evaluating as this: ``` SELECT * FROM usr_booking WHERE (shop_id = 21 AND start_time BETWEEN '10:10:00' AND '11:01:00') OR end_time BETWEEN '10:10:00' AND '11:01:00'; ``` Clearly, this is not the same logic as you what you probably intended.
Try this ``` SELECT * FROM usr_booking WHERE shop_id=21 AND (start_time BETWEEN '10:10:00' AND '11:01:00') OR (end_time BETWEEN '10:10:00' AND '11:01:00') ```
54,264,668
Hello everyone i have the following row as a sample in my table ``` id shop_id start_time end_time 1 21 10:00 11:00 ``` and i want to check whether start\_time and end\_time exist in table or not I am using following query but not working correctly, Where i am wrong ? ``` select * from usr_booking where shop_id='21' and start_time between '10:10:00' and '11:01:00' or end_time between '10:10:00' and '11:01:00' ```
2019/01/19
[ "https://Stackoverflow.com/questions/54264668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10784895/" ]
You need to clearly separate the checks on the `shop_id` and the time ranges: ``` SELECT * FROM usr_booking WHERE shop_id = 21 AND (start_time BETWEEN '10:10:00' AND '11:01:00' OR end_time BETWEEN '10:10:00' AND '11:01:00'); ``` The `AND` operator in MySQL has higher precedence than the `OR` operator. So, your current query is actually evaluating as this: ``` SELECT * FROM usr_booking WHERE (shop_id = 21 AND start_time BETWEEN '10:10:00' AND '11:01:00') OR end_time BETWEEN '10:10:00' AND '11:01:00'; ``` Clearly, this is not the same logic as you what you probably intended.
If you are given the times '10:10:00' and '11:01:00' and you want to know if anything overlaps with that period, then the logic is: ``` select b.* from usr_booking where shop_id = 21 and -- do not use single quotes for numeric constants (assuming `shop_id` is a number end_time > '10:10:00' and start_time < '11:01:00'; ``` For overlapping intervals, `between` is not appropriate.
12,996,365
I have coding below: ``` try{ address = "http://isbndb.com//api/books.xml? access_key=CKEHIG4D&index1=isbn&value1=" +barcode; URL url = new URL(address); URLConnection conn = url.openConnection(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(conn.getInputStream()); NodeList nodes = doc.getElementsByTagName("BookData"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); NodeList title = element.getElementsByTagName("LongTitle"); Element line = (Element) title.item(0); titleList.add(line.getTextContent()); } } catch (Exception e) { e.printStackTrace(); } ``` and theXML format is <http://isbndb.com//api/books.xml?access_key=CKEHIG4D&index1=isbn&value1=1593270615> the error is the line --> NodeList title = element.getElementsByTagName("LongTitle"); Actually what's wrong with that?
2012/10/21
[ "https://Stackoverflow.com/questions/12996365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1740540/" ]
Make sure you are importing the right Element class ([org.w3c.dom.Element](http://developer.android.com/reference/org/w3c/dom/Element.html)).
Change "LongTitle" --> "TitleLong" in ``` NodeList title = element.getElementsByTagName("LongTitle"); ```
56,630,969
I have one json file with 100 columns and I want to read all columns along with predefined datatype of two columns. I know that I could do this with schema option: ``` struct1 = StructType([StructField("npi", StringType(), True), StructField("NCPDP", StringType(), True) spark.read.json(path=abc.json, schema=struct1) ``` However, this code reads only two columns: ``` >>> df.printSchema() root |-- npi: string (nullable = true) |-- NCPDP: string (nullable = true) ``` To use above code I have to give data type of all 100 columns. How can I solve this?
2019/06/17
[ "https://Stackoverflow.com/questions/56630969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5219480/" ]
According to [official documentation](https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrameReader.json), schema can be either a `StructType` or a `String`. I can advice you 2 solutions : ### 1 - You use the schema of a dummy file If you have one light file with the same schema (ie one line same structure), you can read it as Dataframe and then use the schema for your other json files : ```py df = spark.read.json("/path/to/dummy/file.json") schm = df.schema df = spark.read.json(path="abc.json", schema=schm) ``` ### 2 - You generate the schema This step needs you to provide column name (and maybe types too). Let's assume `col` is a dict with (key, value) as (column name, column type). ```py col_list = ['{col_name} {col_type}'.format( col_name=col_name, col_type=col_type, ) for col_name, col_type in col.items()] schema_string = ', '.join(col_list) df = spark.read.json(path="abc.json", schema=schema_string) ```
You can read all the data first and then convert the two columns in question: ``` df = spark.read.json(path=abc.json) df.withColumn("npi", df["npi"].cast("string"))\ .withColumn("NCPDP", df["NCPDP"].cast("string")) ```
3,945,342
I started building an app under an individual developer account. In preparing to beta and release this I'm switching over to a new company account. I'm trying to prepare a checklist of the things I will need to update in order to move the project over to the new account. * Install new development certificate and profile * Change bundle identifier in the -info.plist to match the new app ID * In project build settings change code signing identify Appreciate any words of wisdom from others who may have gone through a similar process or pointers to other questions that address this.
2010/10/15
[ "https://Stackoverflow.com/questions/3945342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/296003/" ]
Here is my checklist in addition to your list: * Change Version of your app to 1.0 in case if this is your first time you submit the app. If it's an update make sure it has higher version number than the one on app store * Add Code Signing Entitlement file to the project * Remove debug code like NSLog * Build the App store distribution. Actually there is a guide for this <https://developer.apple.com/ios/manage/distribution/index.action> * Remember to keep the dSYM file that generated along with the .app file so that you can symbolicate the crash log later. * I don't know if that happen to everyone. But before you zip your binary file (.app file) make sure that the file name of the binary file don't have any special character, best to leave it as alphabet only, since it does not affect anything. * Zip your binary file * Submit to appstore using app uploader utility. That what I remember. Correct me If I'm wrong. Hope this help:).
Make sure to clear your Mac user account's Keychain of all old certificates (or use a different Mac User account), clear the Xcode Organizer of all old provisions and then quit and restart Xcode, and delete all old provisions off of your device (Edit: you can keep the old provisions if they are named differently and are for different app IDs). Also make sure to register the new app ID in the provisioning portal and create and download new mobileprovisions.
25,179,650
Is it good practice to declare object inside [`block scope`](http://msdn.microsoft.com/en-us/library/1t0wsc67.aspx) Condition ``` If item.DocType = 1 Then Dim objass As Assignment = DBFactory.GetAssignmentDB.AssignmentGetByID(vis.AssignmentID) End If ``` OR should i declare object outside the if condition and then do assignment inside ``` Dim objass As Assignment If item.DocType = 1 Then objass = DBFactory.GetAssignmentDB.AssignmentGetByID(vis.AssignmentID) End If ```
2014/08/07
[ "https://Stackoverflow.com/questions/25179650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1263981/" ]
That entirely depends on the scenario. If you want to use the variable within the condition only, then declare it inside the condition. If you want the variable to be used outside of the If statement, then it's scope must extend to outside the condition. There is no 'good practice' for all scenarios. Sometimes it'll be inside, sometimes not - depends on it's usage. <http://msdn.microsoft.com/en-gb/library/1t0wsc67.aspx>
Normally it is good coding style to declare variables in the smalles scope they are used. I.e. in your example it depends if you want to access ´ass´ outside the if condition. - If you declare ´ass` inside it, you cannot access it outside.
246,823
*Prenote: I have asked this question first on [math stackexhange](https://math.stackexchange.com/questions/1882475/gauss-theorem-for-null-boundaries), but a user suggested that mathoverflow might be a better place for this question. Upon thinking about it I have agreed with him and copy-pasted the question here.* *Note: I have solved this problem on my own, mostly while actually typing it in here, as I was stuck with this problem previously. This is however quite important for my research, so I nontheless would like to verify the correctness of my solution, hence I went forth with posting this "question". If this goes against site principles then please vote close on the question.* **Introductions**: Let $(M,g)$ be a Riemannian manifold with boundary (or a Lorentzian/pseudo-Riemannian manifold whose boundary is timelike or spacelike everywhere). Gauss' theorem then states that $$ \int\_M\text{div}(X)\mu\_g=\int\_{\partial M}\langle X,n\rangle\mu\_h, $$ where $\mu\_g$ is the volume form associated with $g$, $\mu\_h$ is the volume form associated with the induced metric $h$, and $n$ is the unit normal vector field along the boundary. This theorem is also available in an intermediate step between Stokes' theorem and the form I have given above. Since $\mathcal{L}\_X\mu\_g=\text{div}(X)\mu\_g$, but $\mathcal{L}\_X\mu\_g=\mathrm{d}i\_X\mu\_g+i\_X\mathrm{d}\mu\_g=\mathrm{d}i\_X\mu\_g$, we have $$ \int\_M\text{div}(X)\mu\_g=\int\_M\mathrm{d}i\_X\mu\_g=\int\_{\partial M}\phi^\*(i\_X\mu\_g), $$ where $\phi$ is the inclusion $\phi:\partial M\rightarrow M$. **The problem**: I wish to use Gauss' theorem on a Lorentzian manifold, whose boundary is a null surface. Then the normal vector is also tangent, the induced metric is degenerate, and the induced volume is zero. Durr. The "intermediate" form of the Gauss' theorem still applies though, so I seek to use it to define a version of Gauss' theorem which, instead of using the normal vector $n$, it will use an arbitrary **transverse** vector field $N$, which is surely not tangent to $\partial M$. **Proposed solution**: If $e\_1,...,e\_{n-1}$ is a positively oriented frame on $\partial M$, then $X$ is locally decomposible as $X=\langle X,N\rangle N+Y$, where $Y=Y^ie\_i$, furthermore, I assume if $N$ is globally defined then this decomposition also applies globally in the general form $X=\langle X,N\rangle N+Y$, where $Y$ is tangent to $\partial M$. (*Is this assumption correct?*). Then plugging $X$ into $\mu\_g$ gives $$ i\_X\mu\_g(e\_1,...,e\_{n-1})=\mu\_g(\langle X,N\rangle N+Y,e\_1,...,e\_{n-1})=\langle X,N\rangle\mu\_g(N,e\_1,...,e\_{n-1})= \\=\langle X,N\rangle i\_N\mu\_g(e\_1,...,e\_{n-1}) $$ where the term involving $Y$ is annihilated, because if $Y$ is tangent to $\partial M$, then the arguments of $\mu\_g$ are linearly dependent. So from this we have $$ \int\_M\text{div}(X)\mu\_g=\int\_{\partial M}\langle X,N\rangle \phi^\*(i\_N\mu\_g), $$ so apparantly $i\_N\mu\_g$ is such a volume form for $\partial M$, that Gauss' theorem with $N$ instead of $n$ applies. I also want to obtain a local coordinate formula for this, so if $(U,x^\mu)$ is a local chart for $M$, and $(V,y^i)$ is a local chart for $\partial M$, then in the relevant chart domains we have $$ i\_N\mu\_g=i\_N(\sqrt{-g}\mathrm{d}x^1\wedge...\wedge\mathrm{d}x^n)=i\_N(n!^{-1}\sqrt{-g}\epsilon\_{\mu\_1...\mu\_n}\mathrm{d}x^{\mu\_1}\wedge...\wedge\mathrm{d}x^{\mu\_n})=\\=i\_N(\sqrt{-g}\epsilon\_{\mu\_1...\mu\_n}\mathrm{d}x^{\mu\_1}\otimes...\otimes\mathrm{d}x^{\mu\_n})=\sqrt{-g}N^{\mu\_1}\epsilon\_{\mu\_1...\mu\_n}\mathrm{d}x^{\mu\_2}\otimes...\otimes\mathrm{d}x^{\mu\_n}=\\=\frac{1}{(n-1)!}\sqrt{-g}N^\mu\epsilon\_{\mu\mu\_2...\mu\_n}\mathrm{d}x^{\mu\_2}\wedge...\wedge\mathrm{d}x^{\mu\_n}. $$ Now pulling back gives $$ \phi^\*(i\_N\mu\_g)=\frac{1}{(n-1)!}\sqrt{-g}\epsilon\_{\mu\mu\_2...\mu\_n}N^\mu\frac{\partial x^{\mu\_2}}{\partial y^{i\_1}}...\frac{\partial x^{\mu\_n}}{\partial y^{i\_{n-1}}}\mathrm{d}y^{i\_1}\wedge...\wedge\mathrm{d}y^{i\_{n-1}} .$$ Now, the matrix $e^\mu\_{(i)}=\partial x^\mu/\partial y^i$ maybe identified (with a bit of abuse of notation regarding tangent maps) as the $\mu$th component of the $i$-th coordinate basis vector field on the boundary $\partial M$, with the components being taken with respect to the coordinate system $\{x^\mu\}$. Then, by the definition of determinants we have $\epsilon\_{\mu\mu\_2...\mu\_n}N^\mu e^{\mu\_2}\_{i\_1}...e^{\mu\_n}\_{i\_{n-1}}=\det(N,e\_{(i\_1)},...,e\_{(i\_{n-1})})$, so $$\phi^\*(i\_N\mu\_g)=\frac{1}{(N-1)!}\sqrt{-g}\det(N,e\_{(i\_1)},...,e\_{(i\_{n-1})})\mathrm{d}y^{i\_1}\wedge...\wedge\mathrm{d}y^{i\_{n-1}}=\\=\sqrt{-g}\det(N,e\_1,...,e\_{n-1})d^{n-1}y, $$ so the modified Gauss' theorem in coordinates is (assuming $M$ can be covered by a single chart) $$ \int\_M \text{div}(X)\sqrt{-g}d^nx=\int\_{\partial M}X^\mu N\_\mu\sqrt{-g}\det(N,e\_1,...,e\_{n-1})d^{n-1}y $$. **Questions**: * Is this derivation correct? * I can work with the form I have gotten, but I don't like the determinant factor in it. Is there any way I can express that in a more pleasant form? * In case the derivation is incorrect, how can I get a formula I can work with in coordinate notation that does what I want?
2016/08/04
[ "https://mathoverflow.net/questions/246823", "https://mathoverflow.net", "https://mathoverflow.net/users/85500/" ]
Gauss' Theorem has nothing to do with the (pseudo-)metric. Is just a consequence of Stokes' theorem. Stokes's theorem says that, for any $n-1$ form $\omega$, $$ \int\_M d\omega = \int\_{\partial M} \omega. $$ Now fix any smooth measure $\mu$ (i.e. given by a smooth non-vanishing top dimensional form, or a density if $M$ is not orientable). It might be the Riemannian measure of a Riemannian structure, but it's not relevant. Let $X$ be a vector field. If you apply the above formula to the $n-1$ form $\omega:=\iota\_X \mu$, you get, using one of the many definitions of divergence (associated with the measure $\mu$) $$\int\_M \mathrm{div}(X) \mu = \int\_{\partial M} \iota\_X \mu, \qquad (\star),$$ where $\iota\_X$ is the contraction. This holds whatever is $X$, on any smooth manifold with boundary. Now it all boils down to how you want to define a "reference" measure on $\partial M$. As you propose, you can pick a transverse vector $N$ to $\partial M$, and define a reference measure on $\partial M$ as $\eta:=\iota\_T \mu$. Then $$ \int\_M \mathrm{div}(X) \mu = \int\_{\partial M} f\, \iota\_T \mu, $$ where $$f := \frac{\mu(X,Y\_1,\ldots,Y\_{n-1})}{\mu(T,Y\_1,\ldots,Y\_{n-1})}. $$ for any arbitrary local frame $Y\_1,\ldots,Y\_{n-1}$ tangent to $\partial M$ (oriented, otherwise take densities and absolute values). In particular, you can easily compute $f$ by looking at the "$T$" component of "$X$": $$X = f\, T \mod \mathrm{span}\{Y\_1,\ldots,Y\_{n-1}\}.$$ There is no need to use orthonormality, or a (pseudo)-metric. However, if you are on a Riemannian manifold, $\mu = \mu\_g$ is the Riemannian measure, and $N$ is the normal vector to $\partial M$, then $f= g(N,X)$, and $\iota\_N \mu$ is Riemannian measure of the induced Riemannian metric on $\partial M$, recovering the classical statement.
Okay, as Futurologist pointed out, the decomposition $X=\langle X,N\rangle N+Y$ is incorrect. In fact, this was quite a rookie mistake. Instead, let $\{e\_1,...,e\_{n-1}\}=\{\partial/\partial y^1,...,\partial/\partial y^{n-1}\}$ be a positively oriented holonomic frame on $\partial M$, and let $N$ be a transversal along $\partial M$. Let $N$ be extended in such way, that $\phi^N\_\lambda(p)=\exp\_p(\lambda N)$, where $\phi^N\_\lambda(p)$ is the flow of $N$. Then the coordinate system $\{\lambda,y^1,...,y^{n-1}\}$ is some sort of "oblique gaussian normal coordinate system" near $\partial M$. The vector field $X$ then may be decomposed as $$ X=\mathrm{d}\lambda(X)N+Y. $$ It is clear that the vector $N^\*=\sharp\mathrm{d}\lambda$ is a null vector, because this is normal to all vectors tangential to $\partial M$. We have then $i\_X\mu\_g=\langle X,N^\*\rangle i\_N\mu\_g$, so Gauss' theorem is $$ \int\_M\text{div}(X)\mu\_g=\int\_{\partial M}\langle X,N^\*\rangle\phi^\*(i\_N\mu\_g), $$ or, in local coordinates $$ \int\_M\nabla\_\mu X^\mu\sqrt{-g}d^nx=\int\_{\partial M}X^\mu N^\*\_\mu\sqrt{-g}\det(N,e\_1,...,e\_{n-1})d^{n-1}y, $$ where clearly $N^\*\_\mu=(\mathrm{d}\lambda)\_\mu=\partial\_\mu\lambda$. The coordinate $\lambda$ is I guess might be difficult to calculate, so alternatively the normal form $\mathrm{d}\lambda$ can be given as $$ \mathrm{d}\lambda=\frac{\mu\_g(.,e\_1,...,e\_{n-1})}{\mu\_g(N,e\_1,...,e\_{n-1})}=\frac{\det(.,e\_1,...,e\_{n-1})}{\det(N,e\_1,...,e\_{n-1})}, $$ which I guess is hardly surprising, since plugging this back into the equation gives just $i\_X\mu\_g$ on the right-hand side... (I love it when I seem to discover something deep, only for it to end up being a triviality or a tautology...) On the other hand, this modified version of Gauss' theorem does not require the metric $g$ actually, any preferred volume form will do instead of $\mu\_g$, which is, I guess, is pretty interesting. Meh, I am not sure this is of much use to me in this form, but I answered my own question because it seems *this is* the answer to my question, however, if anyone has any comment/observation, or any way to express this in a different form, they are welcome to do so.
15,024,035
I'm experiencing a very slow startup of gvim with tex files and the latex-suite plugin. For example, opening [this tex file](https://bitbucket.org/andrenarchy/funcall/raw/25d83535b4839ae1598a620b4cb7315a467ccc4b/funcall.tex) takes 7 seconds. A minimal .vimrc file only contains the following line: ``` filetype plugin on ``` My .vim folder only contains the [latex-suite plugin](http://vim-latex.sourceforge.net/index.php?subject=download&title=Download) (snapshot 2013-01-16). I suspect the folding functionality in latex-suite but I'm not sure how to track this down properly and fix it. I'm running gvim 7.3 on Ubuntu 12.10. Does anybody know how to fix this slow startup?
2013/02/22
[ "https://Stackoverflow.com/questions/15024035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219479/" ]
The reason for that error lies in the fact that you try to map a Set of plain Objects. Object is not a JPA-entity and therefore it cannot be mapped to a relational type. You'll need to create an entity named Occurence and map it the way you did it with the Set of Objects.
I think the problem is here mappedBy = "pk.chemicalStructure" Check that you have a ManyToOne relation in this class like: ``` @ManyToOne @JoinColumn(name = "chemicalstructure_id", nullable = false) @ForeignKey(name = "fk_chemicalstructure_id") private Occurence occurence; ``` then mappedBy = "occurence" The error says that this bi directional relation is missing.
9,648
I have various devices to connect to my iMac using good-old RS-232. Of course, I only have USB connectors on my machine. I have a couple of Prolific PL2303-based cables, and they seem to work OK, but the kext provided seems a little flaky and I'm not sure about long-term support. What is the most-stable, best-supported USB-Serial chip-set or cable?
2011/03/05
[ "https://apple.stackexchange.com/questions/9648", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/1794/" ]
I have two Prolific USB-to-serial adapters but they are made by different Vendors (one is Prolific, the other ATEN). I've used their supplied drivers just fine. Note that there are open source drivers for these devices too available here: <https://github.com/failberg/osx-pl2303> FYI my use case is actually patching them through to a VirtualBox Windows VM and using them in Windows, so I have two layers of drivers and have not had any problems yet. However, I think the best supported USB-to-serial devices are those made by Belkin. This is subjective, but I've used them for years without problem, and they are a large company with a reputation. They will likely be around in the future.
Just to be clear, **I have not used this device myself.** Stewart Cheshire, creator of ZeroConf (the basis of Bonjour), gave a Google Tech Talk on the subject of ZeroConf, and presented a couple of embedded devices (Cameras, and an RS-232 unit). I've always wanted to try this out, but have never had a good enough use to cough up the money to do so. Stewart presented an RS-232 over Ethernet module from [SitePlayer](http://netmedia.com/siteplayer/telnet/index.html). They have a built in web interface used to set up the ethernet and serial parameters, and if I understand correctly, you simply telnet to the device's IP address in order to be presented with the serial interface. (See their [pdf](http://netmedia.com/siteplayer/telnet/documents/SitePlayer%20Telnet.pdf) on the subject.)
9,648
I have various devices to connect to my iMac using good-old RS-232. Of course, I only have USB connectors on my machine. I have a couple of Prolific PL2303-based cables, and they seem to work OK, but the kext provided seems a little flaky and I'm not sure about long-term support. What is the most-stable, best-supported USB-Serial chip-set or cable?
2011/03/05
[ "https://apple.stackexchange.com/questions/9648", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/1794/" ]
I have two Prolific USB-to-serial adapters but they are made by different Vendors (one is Prolific, the other ATEN). I've used their supplied drivers just fine. Note that there are open source drivers for these devices too available here: <https://github.com/failberg/osx-pl2303> FYI my use case is actually patching them through to a VirtualBox Windows VM and using them in Windows, so I have two layers of drivers and have not had any problems yet. However, I think the best supported USB-to-serial devices are those made by Belkin. This is subjective, but I've used them for years without problem, and they are a large company with a reputation. They will likely be around in the future.
I'm professionaly using a [Roline USB to Serial 0.3 m long adapter](http://shop.roline.com/roline_converter_cable_usb_to_serial_0_3_m/12.02.1089-20.html?t_Action=searchKatalog&t_SearchValue=&t_Sort=&manufacturer=&device=&t_Hier=&t_SubHier=&t_lager=&t_CatID=3078&t_ParentID=3077). I'm using the [PL2303 OSX driver](http://sourceforge.net/projects/osx-pl2303/). When I plug my cable, this driver dynamically create `/dev/tty.PL2303-0000nnnn`. I use it from a `Terminal` or `xterm` window with: `screen /dev/tty.PL2303-0000nnnn`. 0 problem with hundreds of connections on network equipments and servers (Brocade, Cisco, Extreme, Oracle (ex. Sun)…).
9,648
I have various devices to connect to my iMac using good-old RS-232. Of course, I only have USB connectors on my machine. I have a couple of Prolific PL2303-based cables, and they seem to work OK, but the kext provided seems a little flaky and I'm not sure about long-term support. What is the most-stable, best-supported USB-Serial chip-set or cable?
2011/03/05
[ "https://apple.stackexchange.com/questions/9648", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/1794/" ]
I have two Prolific USB-to-serial adapters but they are made by different Vendors (one is Prolific, the other ATEN). I've used their supplied drivers just fine. Note that there are open source drivers for these devices too available here: <https://github.com/failberg/osx-pl2303> FYI my use case is actually patching them through to a VirtualBox Windows VM and using them in Windows, so I have two layers of drivers and have not had any problems yet. However, I think the best supported USB-to-serial devices are those made by Belkin. This is subjective, but I've used them for years without problem, and they are a large company with a reputation. They will likely be around in the future.
Both Prolific PL2303 and FTDI devices work fine. I'm using a TrendNET TU-S9 v2 currently (PL-2303). Other than the vendor provided driver or driver from Prolific's Taiwan website, options include <https://www.mac-usb-serial.com> (fairly inexpensive driver), and the nice Mac app <https://www.decisivetactics.com/products/serial/> (not free but works well) which has built-in drivers and doesn't require a separate driver installation. I have also seen claims that FTDI drivers are built into MacOS now but haven't personally tested since I don't have a FTDI device. One thing to be aware of - to connect to PC's and certain PC-like devices with serial ports (some routers/firewalls etc) you need a null modem adaptor or null modem cable between your USB-serial device and the PC/device you're connecting to, usually with female-female connectors.
9,648
I have various devices to connect to my iMac using good-old RS-232. Of course, I only have USB connectors on my machine. I have a couple of Prolific PL2303-based cables, and they seem to work OK, but the kext provided seems a little flaky and I'm not sure about long-term support. What is the most-stable, best-supported USB-Serial chip-set or cable?
2011/03/05
[ "https://apple.stackexchange.com/questions/9648", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/1794/" ]
Just to be clear, **I have not used this device myself.** Stewart Cheshire, creator of ZeroConf (the basis of Bonjour), gave a Google Tech Talk on the subject of ZeroConf, and presented a couple of embedded devices (Cameras, and an RS-232 unit). I've always wanted to try this out, but have never had a good enough use to cough up the money to do so. Stewart presented an RS-232 over Ethernet module from [SitePlayer](http://netmedia.com/siteplayer/telnet/index.html). They have a built in web interface used to set up the ethernet and serial parameters, and if I understand correctly, you simply telnet to the device's IP address in order to be presented with the serial interface. (See their [pdf](http://netmedia.com/siteplayer/telnet/documents/SitePlayer%20Telnet.pdf) on the subject.)
I'm professionaly using a [Roline USB to Serial 0.3 m long adapter](http://shop.roline.com/roline_converter_cable_usb_to_serial_0_3_m/12.02.1089-20.html?t_Action=searchKatalog&t_SearchValue=&t_Sort=&manufacturer=&device=&t_Hier=&t_SubHier=&t_lager=&t_CatID=3078&t_ParentID=3077). I'm using the [PL2303 OSX driver](http://sourceforge.net/projects/osx-pl2303/). When I plug my cable, this driver dynamically create `/dev/tty.PL2303-0000nnnn`. I use it from a `Terminal` or `xterm` window with: `screen /dev/tty.PL2303-0000nnnn`. 0 problem with hundreds of connections on network equipments and servers (Brocade, Cisco, Extreme, Oracle (ex. Sun)…).
9,648
I have various devices to connect to my iMac using good-old RS-232. Of course, I only have USB connectors on my machine. I have a couple of Prolific PL2303-based cables, and they seem to work OK, but the kext provided seems a little flaky and I'm not sure about long-term support. What is the most-stable, best-supported USB-Serial chip-set or cable?
2011/03/05
[ "https://apple.stackexchange.com/questions/9648", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/1794/" ]
Just to be clear, **I have not used this device myself.** Stewart Cheshire, creator of ZeroConf (the basis of Bonjour), gave a Google Tech Talk on the subject of ZeroConf, and presented a couple of embedded devices (Cameras, and an RS-232 unit). I've always wanted to try this out, but have never had a good enough use to cough up the money to do so. Stewart presented an RS-232 over Ethernet module from [SitePlayer](http://netmedia.com/siteplayer/telnet/index.html). They have a built in web interface used to set up the ethernet and serial parameters, and if I understand correctly, you simply telnet to the device's IP address in order to be presented with the serial interface. (See their [pdf](http://netmedia.com/siteplayer/telnet/documents/SitePlayer%20Telnet.pdf) on the subject.)
Both Prolific PL2303 and FTDI devices work fine. I'm using a TrendNET TU-S9 v2 currently (PL-2303). Other than the vendor provided driver or driver from Prolific's Taiwan website, options include <https://www.mac-usb-serial.com> (fairly inexpensive driver), and the nice Mac app <https://www.decisivetactics.com/products/serial/> (not free but works well) which has built-in drivers and doesn't require a separate driver installation. I have also seen claims that FTDI drivers are built into MacOS now but haven't personally tested since I don't have a FTDI device. One thing to be aware of - to connect to PC's and certain PC-like devices with serial ports (some routers/firewalls etc) you need a null modem adaptor or null modem cable between your USB-serial device and the PC/device you're connecting to, usually with female-female connectors.
9,648
I have various devices to connect to my iMac using good-old RS-232. Of course, I only have USB connectors on my machine. I have a couple of Prolific PL2303-based cables, and they seem to work OK, but the kext provided seems a little flaky and I'm not sure about long-term support. What is the most-stable, best-supported USB-Serial chip-set or cable?
2011/03/05
[ "https://apple.stackexchange.com/questions/9648", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/1794/" ]
I'm professionaly using a [Roline USB to Serial 0.3 m long adapter](http://shop.roline.com/roline_converter_cable_usb_to_serial_0_3_m/12.02.1089-20.html?t_Action=searchKatalog&t_SearchValue=&t_Sort=&manufacturer=&device=&t_Hier=&t_SubHier=&t_lager=&t_CatID=3078&t_ParentID=3077). I'm using the [PL2303 OSX driver](http://sourceforge.net/projects/osx-pl2303/). When I plug my cable, this driver dynamically create `/dev/tty.PL2303-0000nnnn`. I use it from a `Terminal` or `xterm` window with: `screen /dev/tty.PL2303-0000nnnn`. 0 problem with hundreds of connections on network equipments and servers (Brocade, Cisco, Extreme, Oracle (ex. Sun)…).
Both Prolific PL2303 and FTDI devices work fine. I'm using a TrendNET TU-S9 v2 currently (PL-2303). Other than the vendor provided driver or driver from Prolific's Taiwan website, options include <https://www.mac-usb-serial.com> (fairly inexpensive driver), and the nice Mac app <https://www.decisivetactics.com/products/serial/> (not free but works well) which has built-in drivers and doesn't require a separate driver installation. I have also seen claims that FTDI drivers are built into MacOS now but haven't personally tested since I don't have a FTDI device. One thing to be aware of - to connect to PC's and certain PC-like devices with serial ports (some routers/firewalls etc) you need a null modem adaptor or null modem cable between your USB-serial device and the PC/device you're connecting to, usually with female-female connectors.
14,082,113
I didnt quite understand whats is the `effect.World` and `effect.View` etc. and why we put the matricies in them? ``` foreach (ModelMesh mesh in model1.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = Matrix.CreateWorld(Vector3.Zero, Vector3.Forward, Vector3.Up); effect.View = Matrix.CreateLookAt(Vector3.Zero, Vector3.Zero, Vector3.Up); } } ```
2012/12/29
[ "https://Stackoverflow.com/questions/14082113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1673384/" ]
effect.World is not a matrix representing the world. It is a matrix representing a 3d object's (mesh, model) position and orientation relative to the 3d game world. Each object will have a different effect.World matrix if they are positioned differently &/or pointed differently. effect.View is a matrix that represents (in an inverted form) the position & orientation of the camera relative to that same 3d game world. Most of the time, there is only one camera, but there can be more (say, a rear view mirror will have it's own view matrix as opposed to the main screen showing the view out the windshield of a car racing game). 1. a model's vertices are hard valued to model local space. 2. Then the effect.World transforms them to game world space. 3. then the effect.View transforms them to camera space. 4. Then the effect.Projection transforms them to 2d screen space and 'volia', your pixel shader knows where to draw what.
From MSDN; [`BasicEffect.World`](http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.basiceffect.world.aspx) > > Gets or sets the world matrix. **Use this matrix to change the position > of the model, using world coordinates**. > > > [`BasicEffect.View`](http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.basiceffect.view.aspx) > > Gets or sets the view matrix. **Use this matrix to change the position > and direction of the camera**. > > > I think bold lines explain what is exactly their difference. Also I found some helpful articles; * [How to: Use BasicEffect](http://msdn.microsoft.com/en-us/library/bb203926%28v=xnagamestudio.10%29.aspx) * [Does every Entity in an XNA game need it's own BasicEffect instance?](https://gamedev.stackexchange.com/questions/36026/does-every-entity-in-an-xna-game-need-its-own-basiceffect-instance) * [Understanding Half-Pixel and Half-Texel Offsets](http://drilian.com/2008/11/25/understanding-half-pixel-and-half-texel-offsets/) * <http://blogs.msdn.com/b/shawnhar/archive/2010/04/05/spritebatch-and-custom-shaders-in-xna-game-studio-4-0.aspx> * <http://msdn.microsoft.com/en-us/library/bb219690(VS.85).aspx>
10,701,393
Should an HTML email message begin like any valid HTML-document and should it even have a DOCTYPE declaration?
2012/05/22
[ "https://Stackoverflow.com/questions/10701393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/92063/" ]
HTML emails should include a doctype, html and body declaration if you intend to do anything fancy at all. There are a multitude of guides on this subject which can help you learn how to properly code HTML Email, but most of them disregard the specifics of a doctype, which is how I stumbled on your question. I suggest you read the following 2 posts which are from reputable teams familiar with the various problems: [campaign monitor's take](http://www.campaignmonitor.com/blog/post/3317/correct-doctype-to-use-in-html-email/) [email on acid's take](http://www.emailonacid.com/blog/details/C13/doctype_-_the_black_sheep_of_html_email_design)
No, since most email clients strip out the `<html>` and `<body>` tags and replace them with their own (see hotmail). As for the doctype, see: <http://www.campaignmonitor.com/blog/post/3317/correct-doctype-to-use-in-html-email/> Assuming you're using a table for your layout (you should be) you'd have one all encompassing table that effectively acts as your `<body>` element, and then nested within you'd have the rest of your content positioned within other tables.
10,701,393
Should an HTML email message begin like any valid HTML-document and should it even have a DOCTYPE declaration?
2012/05/22
[ "https://Stackoverflow.com/questions/10701393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/92063/" ]
HTML emails should include a doctype, html and body declaration if you intend to do anything fancy at all. There are a multitude of guides on this subject which can help you learn how to properly code HTML Email, but most of them disregard the specifics of a doctype, which is how I stumbled on your question. I suggest you read the following 2 posts which are from reputable teams familiar with the various problems: [campaign monitor's take](http://www.campaignmonitor.com/blog/post/3317/correct-doctype-to-use-in-html-email/) [email on acid's take](http://www.emailonacid.com/blog/details/C13/doctype_-_the_black_sheep_of_html_email_design)
Mail clients **are not** web-browsers. They support a small subset of HTML and almost every client behaves differently parsing those HTML elements. Therefore elements like `html`, `head`, `body` or `DOCTYPE` are irrelevant and usually discarded by the mail client. From Wikipedia: > > HTML mail allows the sender to properly express quotations (as in inline replying), headings, bulleted lists, emphasized text, subscripts and superscripts, and other visual and typographic cues to improve the readability and aesthetics of the message, ... Long URLs can be linked to without being broken into multiple pieces, and text is wrapped to fit the width of the user agent's viewport, ... It allows in-line inclusion of tables, as well as diagrams or mathematical formulae as images... > > >
33,302,235
I have a problem with reading from .xlsx (Excel) file. I tried to use: ``` var fileName = @"C:\automated_testing\ProductsUploadTemplate-2015-10-22.xlsx"; var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName); var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString); var ds = new DataSet(); adapter.Fill(ds, "XLSData"); DataTable data = ds.Tables["XLSData"]; // ... Loop over all rows. StringBuilder sb = new StringBuilder(); foreach (DataRow row in data.Rows) { sb.AppendLine(string.Join(",", row.ItemArray)); } ``` but if failed due to `connectionString`. So I updated the line to support .xlsx: ``` var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;", fileName); ``` but I get: > > The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine. > > > (Problem here is that, I am not able to install new software on my remote-testing machine, so I am not able to fix it and need to find other solution.) I do also need to be sure that imported data will be stored in some simple way (I am beginner programmer) to let me iterate through it i.e. to create objects with row's data. **Other approaches I checked:** * <https://bytescout.com/products/developer/spreadsheetsdk/read-write-excel.html> comment: seems to probably work for me, but doesn't support Excel files of unknown dimensions (random number of rows and columns). * <https://exceldatareader.codeplex.com/> comment: doesn't support settings column names from different row than first one (in some of my Excel files, there are comments in 4-6 first rows and then is headers row and data below). * <http://blog.fryhard.com/archive/2010/10/28/reading-xlsx-files-using-c-and-epplus.aspx> comment: same problem as above. * <https://freenetexcel.codeplex.com/> comment: downloaded package weight was over 60MB and it requires me to install it on system, which is not possible in my situation. Anyway, people comment that it is limited to 150 rows. Meanwhile I will try to check <https://code.google.com/p/linqtoexcel/>, but all other ideas are more than welcome! EDIT: Just checked that LinqToExcel, same issue as above: > > The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine. > > > **EDIT2: Ultimately, it seems that this solution solved my issue:** <https://stackoverflow.com/a/19065266/3146582>
2015/10/23
[ "https://Stackoverflow.com/questions/33302235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146582/" ]
If you are reading data from `Excel` file, you can use `EPPlus` NuGet package, and use following code: ``` //using OfficeOpenXml; using (ExcelPackage xlPackage = new ExcelPackage(new FileInfo(@"C:\YourDirectory\sample.xlsx"))) { var myWorksheet = xlPackage.Workbook.Worksheets.First(); //select sheet here var totalRows = myWorksheet.Dimension.End.Row; var totalColumns = myWorksheet.Dimension.End.Column; var sb = new StringBuilder(); //this is your data for (int rowNum = 1; rowNum <= totalRows; rowNum++) //select starting row here { var row = myWorksheet.Cells[rowNum, 1, rowNum, totalColumns].Select(c => c.Value == null ? string.Empty : c.Value.ToString()); sb.AppendLine(string.Join(",", row)); } } ```
Reading Excel files with OLE provider is possible only if MS Jet engine (MS Access) is installed. I noticed that you decided to use .NET interop to API but this is not a good idea: it requires installed MS Excel and doesn't recommended to use for automation on servers. If you don't need to support old (binary) Excel formats (xls) and reading XLSX is enough I recommend to use [EPPlus](http://epplus.codeplex.com/) library. It provides simple and powerful API for both reading and writing XLSX files (and has a lot of examples): ``` var existingFile = new FileInfo(filePath); // Open and read the XlSX file. using (var package = new ExcelPackage(existingFile)) { // access worksheets, cells etc } ```
55,691,091
[![error](https://i.stack.imgur.com/Uw9j2.jpg)](https://i.stack.imgur.com/Uw9j2.jpg) I am trying to transfer some text files on SFTP Server using Putty command line option. I have a batch file with the following commands: ``` ( echo cd /inbox echo mput c:\temp\*.txt echo bye echo cd c:\temp\ echo del c:\temp\*.txt ) |echo open <username@ip> <port no> -pw password ``` However, when I execute the batch file I get stuck at "Keyboard interactive prompt from Server" Appreciate any suggestions on how to get over this point to avoid manual intervention while executing this batch file?
2019/04/15
[ "https://Stackoverflow.com/questions/55691091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6089571/" ]
You don't need to make 2 connections to the db for getting the same data. You could create a collection of objects and use them in place like such... ``` <?php $arr = []; $sql = "SELECT category.name as cat, article.name as art from category JOIN article ON category.id = article.id"; $query = mysqli_query($conn, $sql); while($row = mysqli_fetch_array($query)){ $obj = (object) [ "cat" => $row["cat"], "art" => $row["art"] ]; array_push($arr, $obj); } mysqli_close($conn); ?> <select name="category"> <option value="category">category name</option> foreach($arr as $obj) { ?> <option value='"<?php echo $obj->cat; ?>"'><?php echo $obj->cat; ?></option> <?php } ``` ``` <select name="article"> <option value="articlename">article name</option> foreach($arr as $obj) { ?> <option value='"<?php echo $obj->art; ?>"'><?php echo $obj->art; ?></option> <?php } ```
You can prepare the strings that will hold the `<option>` in 1 loop, then simply echo them. In example : ``` <?php $sql = "SELECT category.name as cat, article.name as art FROM category JOIN article ON category.id = article.id"; $query = mysqli_query($conn, $sql); $articles = ""; $categories = ""; while($row = mysqli_fetch_array($query)) { $categories .= "<option value='" . $row["cat"] . "'>" . $row["cat"] . "</option>"; $articles .= "<option value='" . $row["art"] . "'>" . $row["art"] . "</option>"; } mysqli_close($conn); ?> <select name="category"> <option value="category">category name</option> <?php echo $categories; ?> </select> <select name="article"> <option value="articlename">article name</option> <?php echo $articles; ?> </select> ```
9,942,275
I'm working with two-dimensional array-values that should be inserted into a ArrayList. But this is done in a for-loop and the value of the two-dimensional array-value gets changed as the loop runs since it is just used as an temp-variable (which makes all of the variables stored in the ArrayList gets changed as this variable changes). So if I try to print out the content of the ArrayList when the loop is done all the values are the same. ``` for(int i = 0; i <= Counter; i++) { if(Xhavetomove >= i) arrayvalue[0][0] = this.Xspeed; else arrayvalue[0][0] = 0; if(Yhavetomove >= i) arrayvalue[0][1] = this.Xspeed; else arrayvalue[0][1] = 1; System.out.println(arrayvalue[0][1]); Object.movement.add(arrayvalue); } ``` Are there anyway I can make it store the value itself? For example: The first time the loop runs the value is "5,5" but if I print out the ArrayList when the loop is done all the values has turned into "5,1".
2012/03/30
[ "https://Stackoverflow.com/questions/9942275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1255810/" ]
The problem is the way Array is added to the Object here. You are not adding the Array to the Object. What is happening is you are adding the address to the location in memory where the Array resides. So every time you add the Array to the Object, you are adding the same address every time. So every Array in the Object is actually the same Array over and over since they all point to a single location in memory. So when you change the Array, it will appear to change all of them inside the Object. The best thing to do is either create a new Array every time through the loop, essentially creating a new location in memory for the Array to reside, or `clone()` the Array which will create a new reference. Example: ``` String[] houseOfStark = {"Eddard", "Catelyn", "Robb", "Sansa", "Arya", "Bran", "Rickon"}; // Sorry Jon String[] copyOfStark = houseOfStark; String[] cloneOfStark = houseOfStark.clone(); houseOfStark[1] = "Lady Catelyn"; System.out.println(houseOfStark[1]); System.out.println(copyOfStark[1]); System.out.println(cloneOfStark[1]); ``` Will produce: ``` Lady Catelyn Lady Catelyn Catelyn ``` [Good blog post explaining the difference](http://geekswithblogs.net/dforhan/archive/2005/12/01/61852.aspx)
You need to use array's `clone()` method to make its copy: ``` //for example int[][] copy = (int[][])arraySource.clone(); ```
9,942,275
I'm working with two-dimensional array-values that should be inserted into a ArrayList. But this is done in a for-loop and the value of the two-dimensional array-value gets changed as the loop runs since it is just used as an temp-variable (which makes all of the variables stored in the ArrayList gets changed as this variable changes). So if I try to print out the content of the ArrayList when the loop is done all the values are the same. ``` for(int i = 0; i <= Counter; i++) { if(Xhavetomove >= i) arrayvalue[0][0] = this.Xspeed; else arrayvalue[0][0] = 0; if(Yhavetomove >= i) arrayvalue[0][1] = this.Xspeed; else arrayvalue[0][1] = 1; System.out.println(arrayvalue[0][1]); Object.movement.add(arrayvalue); } ``` Are there anyway I can make it store the value itself? For example: The first time the loop runs the value is "5,5" but if I print out the ArrayList when the loop is done all the values has turned into "5,1".
2012/03/30
[ "https://Stackoverflow.com/questions/9942275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1255810/" ]
At the end each add needs to create an own object. To use **clone** is one way. Or to add always the values in pairs, in an other. A totally different way is to use serialization. This make sense when you do not want to calculate this values but to log it. In this case you need an outputStream What is best is defined by what you want to do with Object.movement
You need to use array's `clone()` method to make its copy: ``` //for example int[][] copy = (int[][])arraySource.clone(); ```
9,942,275
I'm working with two-dimensional array-values that should be inserted into a ArrayList. But this is done in a for-loop and the value of the two-dimensional array-value gets changed as the loop runs since it is just used as an temp-variable (which makes all of the variables stored in the ArrayList gets changed as this variable changes). So if I try to print out the content of the ArrayList when the loop is done all the values are the same. ``` for(int i = 0; i <= Counter; i++) { if(Xhavetomove >= i) arrayvalue[0][0] = this.Xspeed; else arrayvalue[0][0] = 0; if(Yhavetomove >= i) arrayvalue[0][1] = this.Xspeed; else arrayvalue[0][1] = 1; System.out.println(arrayvalue[0][1]); Object.movement.add(arrayvalue); } ``` Are there anyway I can make it store the value itself? For example: The first time the loop runs the value is "5,5" but if I print out the ArrayList when the loop is done all the values has turned into "5,1".
2012/03/30
[ "https://Stackoverflow.com/questions/9942275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1255810/" ]
The problem is the way Array is added to the Object here. You are not adding the Array to the Object. What is happening is you are adding the address to the location in memory where the Array resides. So every time you add the Array to the Object, you are adding the same address every time. So every Array in the Object is actually the same Array over and over since they all point to a single location in memory. So when you change the Array, it will appear to change all of them inside the Object. The best thing to do is either create a new Array every time through the loop, essentially creating a new location in memory for the Array to reside, or `clone()` the Array which will create a new reference. Example: ``` String[] houseOfStark = {"Eddard", "Catelyn", "Robb", "Sansa", "Arya", "Bran", "Rickon"}; // Sorry Jon String[] copyOfStark = houseOfStark; String[] cloneOfStark = houseOfStark.clone(); houseOfStark[1] = "Lady Catelyn"; System.out.println(houseOfStark[1]); System.out.println(copyOfStark[1]); System.out.println(cloneOfStark[1]); ``` Will produce: ``` Lady Catelyn Lady Catelyn Catelyn ``` [Good blog post explaining the difference](http://geekswithblogs.net/dforhan/archive/2005/12/01/61852.aspx)
At the end each add needs to create an own object. To use **clone** is one way. Or to add always the values in pairs, in an other. A totally different way is to use serialization. This make sense when you do not want to calculate this values but to log it. In this case you need an outputStream What is best is defined by what you want to do with Object.movement
25,668,796
I'm trying to make a function that changes a char array from the main function, that's what I'm trying to do: ``` #include <stdlib.h> #include <stdio.h> #include <conio.h> void change(char *a); int main() { char a[] = "hello"; printf("\na = %s", a); change(a); printf("%\na = %s", a); getch(); } void change(char *a) { a = "goodbye"; } ```
2014/09/04
[ "https://Stackoverflow.com/questions/25668796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3174594/" ]
The main problem is that you are sending a copy of the char pointer a by doing this: ``` void change(char *a) { a = "goodbye"; } ``` if you want to change a value in another function you should do this: ``` #include <stdlib.h> #include <stdio.h> #include <conio.h> void change(char **a); int main() { char *a = "hello"; printf("\na = %s", a); change(&a); printf("%\na = %s", a); getch(); } void change(char **a) { *a = "goodbye"; } ```
I changed the function, now it works, this way: ``` void change(char *a) { strcpy(a, "goodbye"); } ```
25,668,796
I'm trying to make a function that changes a char array from the main function, that's what I'm trying to do: ``` #include <stdlib.h> #include <stdio.h> #include <conio.h> void change(char *a); int main() { char a[] = "hello"; printf("\na = %s", a); change(a); printf("%\na = %s", a); getch(); } void change(char *a) { a = "goodbye"; } ```
2014/09/04
[ "https://Stackoverflow.com/questions/25668796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3174594/" ]
Several problems with this code, but first we need to take a step back and talk about how arrays are handled in C. Except when it is the operand of the `sizeof` or unary `&` operators, or is a string literal used to initialize another array in a declaration, an expression of type "N-element array of `T`" will be converted ("decay") to an expression of type "pointer to `T`", and the value of the expression will be the address of the first element of the array. In the declaration ``` char a[] = "hello"; ``` `"hello"` is a string literal, which has type "6-element array of `char`" (5 characters plus the 0 terminator). Since it is being used to initialize the array `a` in a declaration, the rule above doesn't apply; instead, the size of `a` is set to be the same as the size of the literal (6), and the contents of the string literal are copied to the array. When you call `change` from `main` as ``` change(a); ``` the *expression* `a` has type "6-element array of `char`". Since it is neither a string literal nor the operand of the `sizeof` or unary `&` operators, that expression will be converted to type "pointer to `char`", and the value of the expression will be the address of the first element of the aray. Hence why the `change` function is declared as ``` void change(char *a); ``` In this context, `a` is simply a pointer. When you write ``` a = "goodbye"; ``` the string literal `"goodbye"` is not being used in an initializer, and it's not the operand of the `sizeof` or unary `&` operators, so the expression is converted to type "pointer to `char`", and the value of the expression is the address of the first character. So what happens here is that you're copying the *address* of the string literal `"goodbye"` to `a`. This overwrites the value in `a`, but this `a` is not the same object in memory as the *array* `a` in `main`, so any changes to it are not reflected in `main`. If you want to update the *contents* of an array, you will need to use the library functions `strcpy/strncpy` (for 0-terminated strings) or `memcpy` (for everything else), or update each element explicitly (`a[0]='g'; a[1]='o'; a[2]='o';`, etc). To update the contents of `a`, you'd use ``` strcpy( a, "goodbye" ); ``` **Except**... `a` is only large enough to hold 5 characters plus a 0 terminator; `"goodbye"` is 7 characters plus the 0 terminator; it's two characters larger than what `a` is capable of storing. C will happliy let you perform the operation and trash the bytes immediately following `a`, which may lead to any number of problems (buffer overruns such as this are a classic malware exploit). You have a couple of choices at this juncture: First, you could declare `a` to be large enough to handle either string: ``` #define MAX_LEN 10 ... char a[MAX_LEN] = "hello"; ``` Second, you could limit the size of the string copied to `a`: ``` void change( char *a, size_t size ) { strncpy( a, "goodbye", size - 1 ); a[size - 1] = 0; } ``` Note that you will need to pass the number of elements `a` can store as a separate parameter when you call `change`; there's no way to tell from a pointer how big the array it points to is: ``` change( a, sizeof a / sizeof *a ); // although in this case, sizeof a would be // sufficient. ```
The main problem is that you are sending a copy of the char pointer a by doing this: ``` void change(char *a) { a = "goodbye"; } ``` if you want to change a value in another function you should do this: ``` #include <stdlib.h> #include <stdio.h> #include <conio.h> void change(char **a); int main() { char *a = "hello"; printf("\na = %s", a); change(&a); printf("%\na = %s", a); getch(); } void change(char **a) { *a = "goodbye"; } ```
25,668,796
I'm trying to make a function that changes a char array from the main function, that's what I'm trying to do: ``` #include <stdlib.h> #include <stdio.h> #include <conio.h> void change(char *a); int main() { char a[] = "hello"; printf("\na = %s", a); change(a); printf("%\na = %s", a); getch(); } void change(char *a) { a = "goodbye"; } ```
2014/09/04
[ "https://Stackoverflow.com/questions/25668796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3174594/" ]
Several problems with this code, but first we need to take a step back and talk about how arrays are handled in C. Except when it is the operand of the `sizeof` or unary `&` operators, or is a string literal used to initialize another array in a declaration, an expression of type "N-element array of `T`" will be converted ("decay") to an expression of type "pointer to `T`", and the value of the expression will be the address of the first element of the array. In the declaration ``` char a[] = "hello"; ``` `"hello"` is a string literal, which has type "6-element array of `char`" (5 characters plus the 0 terminator). Since it is being used to initialize the array `a` in a declaration, the rule above doesn't apply; instead, the size of `a` is set to be the same as the size of the literal (6), and the contents of the string literal are copied to the array. When you call `change` from `main` as ``` change(a); ``` the *expression* `a` has type "6-element array of `char`". Since it is neither a string literal nor the operand of the `sizeof` or unary `&` operators, that expression will be converted to type "pointer to `char`", and the value of the expression will be the address of the first element of the aray. Hence why the `change` function is declared as ``` void change(char *a); ``` In this context, `a` is simply a pointer. When you write ``` a = "goodbye"; ``` the string literal `"goodbye"` is not being used in an initializer, and it's not the operand of the `sizeof` or unary `&` operators, so the expression is converted to type "pointer to `char`", and the value of the expression is the address of the first character. So what happens here is that you're copying the *address* of the string literal `"goodbye"` to `a`. This overwrites the value in `a`, but this `a` is not the same object in memory as the *array* `a` in `main`, so any changes to it are not reflected in `main`. If you want to update the *contents* of an array, you will need to use the library functions `strcpy/strncpy` (for 0-terminated strings) or `memcpy` (for everything else), or update each element explicitly (`a[0]='g'; a[1]='o'; a[2]='o';`, etc). To update the contents of `a`, you'd use ``` strcpy( a, "goodbye" ); ``` **Except**... `a` is only large enough to hold 5 characters plus a 0 terminator; `"goodbye"` is 7 characters plus the 0 terminator; it's two characters larger than what `a` is capable of storing. C will happliy let you perform the operation and trash the bytes immediately following `a`, which may lead to any number of problems (buffer overruns such as this are a classic malware exploit). You have a couple of choices at this juncture: First, you could declare `a` to be large enough to handle either string: ``` #define MAX_LEN 10 ... char a[MAX_LEN] = "hello"; ``` Second, you could limit the size of the string copied to `a`: ``` void change( char *a, size_t size ) { strncpy( a, "goodbye", size - 1 ); a[size - 1] = 0; } ``` Note that you will need to pass the number of elements `a` can store as a separate parameter when you call `change`; there's no way to tell from a pointer how big the array it points to is: ``` change( a, sizeof a / sizeof *a ); // although in this case, sizeof a would be // sufficient. ```
I changed the function, now it works, this way: ``` void change(char *a) { strcpy(a, "goodbye"); } ```
67,481,013
I am using react-select with styled component and it is working but I want to use tailwind classes using twin macro. ``` import tw from 'twin.macro'; import styled from 'styled-components'; import Select from 'react-select'; export const StyledReactSelect = styled(Select)(() => [ ` .Select__control { height: 40px; width: 100%; border: 1px solid #a1a1a1; border-radius: 0; cursor: pointer; } .Select__control:hover { border-color: #a1a1a1; } .Select__control--is-focused { box-shadow: 0 0 0 1px black; outline: none; } .Select__indicator-separator { display: none; } .Select__menu { color: #3c3d3e; } `, ]); ``` **Now I want to use tw(twin-macro) with classes of react-select. can anyone help?**
2021/05/11
[ "https://Stackoverflow.com/questions/67481013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2585973/" ]
When you define a Coroutine, eg; ```cs using System.Collections; public class C { private void before() { } private void after() { } public IEnumerator MyCoroutine() { before(); yield return null; after(); } } ``` The compiler defines a new type to track the state of the method, including any local variables. You can see that in action by using a [decompiler](https://sharplab.io/#v2:D4AQDABCCMB0DCB7ANsgpgYwC4EtEDsBnAbgFgAoEAZigCYJ4IBvCiNiABwCccA3AQyxooAFggAjNADNEXNAAoAlMwgBfVu259BwkGP5ShXJSvXl2UGgEkAovgCuAWzRdBsiAFkAnki6J7uPgKihpsLOYW7JIyckpkEZFQ0NBQAOwQDqjxiWwGRnGhahSqQA). While it's more work, and more complicated, you could implement your own `IEnumerable` types instead. ```cs public class MyCoroutine : IEnumerator { private int state = 0; public object Current { get; private set; } private void before() { } private void after() { } public bool MoveNext() { switch (state) { case 0: before(); state++; Current = null; return true; case 1: after(); state++; break; } return false; } public void Reset() => throw new System.NotImplementedException(); } ``` Then it's up to you how you wish to save / load and resume your coroutines.
Unity doesn't have anything built in to support this. So, let's go over what saving a coroutine entails. A started & incomplete coroutine has local variables, a yield instruction that they are currently at. And the yield that they are currently at may instantiate an anonymous `YieldInstruction`. So, if you would want to save a coroutine, you would need to save these things. So, you would need to save a bunch of locals as well as answer the question of how to resume the couroutine at the correct yield instruction. This is a complicated task, and the outcome would probably be very messy without substantial effort and refactoring. So, I recommend that you accept the fact you will need to do some refactoring. Rather than keeping the coroutines intact, the more straightforward path here is to "unroll" your coroutines into the various update methods: * `Update`, when using `yield return null`, `WaitForSeconds`, `WaitUntil`, `WaitForSecondsRealtime` * `FixedUpdate`, if using the uncommonly used `WaitForFixedUpdate` * `LateUpdate`, when using `WaitForEndOfFrame` and move the locals of the coroutine into fields, as well as any additional necessary fields needed to track time passage in place of `WaitForSeconds` and such. And to make these fields so that they serialize properly. Since there is no specific example given in the question, I will provide a before/after example that may help: ### Using Coroutine (state not serializable): ``` void Update() { DoStuff(); } void StartMoveTowards(Transform target, Vector3 destination, float duration) { StartCoroutine(DoMoveTowards(target, destination, duration)); } IEnumerator DoMoveTowards(Transform target, Vector3 destination, float duration) { float v = Vector3.Distance(target.position, destination) / duration; while( target.position != destination) { yield return null; target.position = Vector3.MoveTowards(target.position, destination, v * Time.deltaTime); } DoFirstThing(); yield return new WaitForSeconds(3f); DoSecondThing(); } ``` ### Not using coroutine (serializable state): ``` enum MoveTowardsState { NotRunning, Starting, MovingTowards, DoingFirstThing, Waiting } // serializable coroutine locals, timers, and instruction state [SerializeField] MoveTowardsState currentMoveTowardsState; [SerializeReference] [SerializeField] Transform moveTowardsTarget; [SerializeField] Vector3 moveTowardsDestination; [SerializeField] float moveTowardsDuration; [SerializeField] float waitT; [SerializeField] float v; void Update() { DoStuff(); HandleDoMoveTowards(); } void StartMoveTowards(Transform target, Vector3 destination, float duration) { moveTowardsTarget = target; moveTowardsDestination = destination; moveTowardsDuration = duration; currentMoveTowardsState = MoveTowardsState.Starting; } void HandleDoMoveTowards() { bool continuing = true; while(continuing) { continuing = false; switch (currentMoveTowardsState) { case MoveTowardsState.NotRunning: break; case MoveTowardsState.Starting: v = Vector3.Distance(target.position, destination) / duration; if (target.position != destination) { currentMoveTowardsState = MoveTowardsState.MovingTowards; } else { currentMoveTowardsState = MoveTowardsState.DoingFirstThing; continuing = true; } break; case MoveTowardsState.MovingTowards: target.position = Vector3.MoveTowards(moveTowardsTarget.position, moveTowardsDestination, v * Time.deltaTime); if (target.position == destination) { currentMoveTowardsState = MoveTowardsState.DoingFirstThing; continuing = true; } break; case MoveTowardsState.DoingFirstThing: DoFirstThing(); waitT = 3f; currentMoveTowardsState = MoveTowardsState.Waiting; break; case MoveTowardsState.Waiting: waitT -= Time.deltaTime; if (waitT <= 0f) { DoSecondThing(); currentMoveTowardsState = MoveTowardsState.NotRunning; } break; } } } ``` And if multiple parallel instances are needed, You can create a new monobehavior for the coroutine, and create an instance for each running instance. Note: I can't check syntax at the moment, so please mind any syntax errors. Hopefully the idea gets across. Please let me know in the comments if any parts dont make sense.
40,142,675
The method I am using takes two sorted lists and returns a single list containing all of the elements in the two original lists, in sorted order. For example, if the original lists are (1, 4, 5) and (2, 3, 6) then the result list would be (1, 2, 3, 4, 5, 6). Is there something I am missing? ``` public static<E extends Comparable<E>> List<E> mergeSortedLists(List<E> a, List<E> b) { List<E> result = new ArrayList<E>(); PushbackIterator<E> aIter = new PushbackIterator<E>(a.iterator()); PushbackIterator<E> bIter = new PushbackIterator<E>(b.iterator()); while (aIter.hasNext() && bIter.hasNext()) { if (aIter.next().compareTo(bIter.next()) < 0) { result.add(aIter.next()); } if (bIter.next().compareTo(bIter.next()) > 0){ result.add(bIter.next()); } } while (aIter.hasNext()) { result.add(aIter.next()); } while (bIter.hasNext()) { result.add(bIter.next()); } return result; } ```
2016/10/19
[ "https://Stackoverflow.com/questions/40142675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5900887/" ]
In order to perform a merge, you need to peek at the next value, so see which next value to use. Eventually, one of the lists will run out of values before the other, so you need to check for that. One trick is to use `null` as an End-Of-Data marker, assuming that lists cannot contain `null` values, which is a fair assumption since they have to be sorted. In that case, code will be like this: ``` public static <E extends Comparable<E>> List<E> mergeSortedLists(List<E> list1, List<E> list2) { List<E> merged = new ArrayList<>(list1.size() + list2.size()); // Get list iterators and fetch first value from each, if available Iterator<E> iter1 = list1.iterator(); Iterator<E> iter2 = list2.iterator(); E value1 = (iter1.hasNext() ? iter1.next() : null); E value2 = (iter2.hasNext() ? iter2.next() : null); // Loop while values remain in either list while (value1 != null || value2 != null) { // Choose list to pull value from if (value2 == null || (value1 != null && value1.compareTo(value2) <= 0)) { // Add list1 value to result and fetch next value, if available merged.add(value1); value1 = (iter1.hasNext() ? iter1.next() : null); } else { // Add list2 value to result and fetch next value, if available merged.add(value2); value2 = (iter2.hasNext() ? iter2.next() : null); } } // Return merged result return merged; } ``` *Test* ``` System.out.println(mergeSortedLists(Arrays.asList(1, 4, 5), Arrays.asList(2, 3, 6))); ``` *Output* ``` [1, 2, 3, 4, 5, 6] ```
I'm going to assume you intended something like this with your use of `PushbackIterator`: ``` while (aIter.hasNext() && bIter.hasNext()) { E aElem = aIter.next(); E bElem = bIter.next(); if (aElem.compareTo(bElem) <= 0) { result.add(aElem); bIter.pushback(bElem); } else { result.add(bElem); aIter.pushback(aElem); } } ```
40,142,675
The method I am using takes two sorted lists and returns a single list containing all of the elements in the two original lists, in sorted order. For example, if the original lists are (1, 4, 5) and (2, 3, 6) then the result list would be (1, 2, 3, 4, 5, 6). Is there something I am missing? ``` public static<E extends Comparable<E>> List<E> mergeSortedLists(List<E> a, List<E> b) { List<E> result = new ArrayList<E>(); PushbackIterator<E> aIter = new PushbackIterator<E>(a.iterator()); PushbackIterator<E> bIter = new PushbackIterator<E>(b.iterator()); while (aIter.hasNext() && bIter.hasNext()) { if (aIter.next().compareTo(bIter.next()) < 0) { result.add(aIter.next()); } if (bIter.next().compareTo(bIter.next()) > 0){ result.add(bIter.next()); } } while (aIter.hasNext()) { result.add(aIter.next()); } while (bIter.hasNext()) { result.add(bIter.next()); } return result; } ```
2016/10/19
[ "https://Stackoverflow.com/questions/40142675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5900887/" ]
In order to perform a merge, you need to peek at the next value, so see which next value to use. Eventually, one of the lists will run out of values before the other, so you need to check for that. One trick is to use `null` as an End-Of-Data marker, assuming that lists cannot contain `null` values, which is a fair assumption since they have to be sorted. In that case, code will be like this: ``` public static <E extends Comparable<E>> List<E> mergeSortedLists(List<E> list1, List<E> list2) { List<E> merged = new ArrayList<>(list1.size() + list2.size()); // Get list iterators and fetch first value from each, if available Iterator<E> iter1 = list1.iterator(); Iterator<E> iter2 = list2.iterator(); E value1 = (iter1.hasNext() ? iter1.next() : null); E value2 = (iter2.hasNext() ? iter2.next() : null); // Loop while values remain in either list while (value1 != null || value2 != null) { // Choose list to pull value from if (value2 == null || (value1 != null && value1.compareTo(value2) <= 0)) { // Add list1 value to result and fetch next value, if available merged.add(value1); value1 = (iter1.hasNext() ? iter1.next() : null); } else { // Add list2 value to result and fetch next value, if available merged.add(value2); value2 = (iter2.hasNext() ? iter2.next() : null); } } // Return merged result return merged; } ``` *Test* ``` System.out.println(mergeSortedLists(Arrays.asList(1, 4, 5), Arrays.asList(2, 3, 6))); ``` *Output* ``` [1, 2, 3, 4, 5, 6] ```
Same approach of merging 2 arrays can also be used with iterators tweaking a little bit. you can use adding elements instead of printing if needed. ``` static void printItr(Iterator<String> it1, Iterator<String> it2) { String firstString=null,secondString = null; boolean moveAheadIt1 = true, moveAheadIt2 = true; while(it1.hasNext() && it2.hasNext()){ firstString = moveAheadIt1 ? it1.next() : firstString ; secondString = moveAheadIt2 ? it2.next() : secondString; if(firstString.compareTo(secondString) < 0){ System.out.println(firstString); moveAheadIt2 = false; moveAheadIt1 = true; }else { System.out.println(secondString); moveAheadIt1 = false; moveAheadIt2 = true; } } while(it1.hasNext()){ System.out.println(it1.next()); } while(it2.hasNext()){ System.out.println(it2.next()); } } ```