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
37,484,134
I have this table structure, where all the columns have a different click method to them. The first column is not so wide, so it's pretty hard to click on it in a mobile browser, but i want to keep it like that, because of the borders. Is there a way, where the clickable area of the first column could overlap invisibly the second column? Here's a picture where I try to show what I'm trying to achieve : [![enter image description here](https://i.stack.imgur.com/X6IJa.png)](https://i.stack.imgur.com/X6IJa.png) Here is the HTML (note i'm using special row and column elements because of the onsen UI i'm wrapping my application in) ``` <ons-row> <ons-col class="firstcolumn" width="32px"> <div class="item-thum" style="width:60px;" ng-click="confirm(item, item.id)"> <div style="overflow-x: hidden; overflow-y: hidden; padding-left: 3px;"> <ons-icon size="30px" icon="ok"></ons-icon> </div> </div> </ons-col> <ons-col ng-click="Details(item, item.id)" class="secondcolumn"> <div class="titlediv"> <header> <span class="item-title">{{item.name}}</span> </header> </div> </ons-col> </ons-row> ``` You can see that in my current code the **col2** has an click event handler which always fires if i click anywhere near the second column.
2016/05/27
[ "https://Stackoverflow.com/questions/37484134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3609107/" ]
The first thing that comes to mind is to: 1. Give the first col a greater z-index then the second col ``` .firstcolumn{ z-index : 2; } .secondcolumn{ z-index : 1; } ``` 2. Extend the padding-right of col1 to cover the bit of col2 you want to be clickable for col1. I think that's most of the work you would have to do, let me know how it goes. EDIT: Point 2 might not be needed/appropriate as per the comments below.
I have had a quick play with w3schools TryIt editor and have come up with the following as a start: ```html <!DOCTYPE html> <html> <head> <title>Page Title</title> <style type="text/css"> table td { position:relative; border:1px solid black; height:20px; width:200px; } .overLap { position:absolute; left:0px; top:0px; width:150%; height:100%; background-color:rgba(51,204,51,0.3); } .shorter { position:absolute; right:0px; top:0px; width:50%; height:100%; background-color:rgba(255,0,0,0.3); } </style> </head> <body> <table> <tr> <td> <div class="overLap"></div> <p>Data 1</p> </td> <td> <div class="shorter"></div> <p>Data 2</p> </td> </tr> </table> </body> </html> ``` Its pretty basic and just shows that each table cell contains a div which is sized according to the click space you want. The onclick would then be assigned to each div.
7,771,607
I've already do my research but I think I don't know how to ask so I'll try to explain... Im looking for a way to ask for the first entry saved on a Scaffold... Like If I have in the table Products: * Sweeter * Pants * Scarf * Tennis and I write `@first_prod = Products.first` (or something like that) on my model or in my view `<%= Products.each.first %>` (or something like that) Rails give me the first prouduct in this case - Sweeter... Thanks in advance...
2011/10/14
[ "https://Stackoverflow.com/questions/7771607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/992653/" ]
In rails you can define a few default ways to get the content from a model. In your case i would create a scope. in your model enter the following: ``` scope ordered, :order => "Product.created_at ASC" ``` When you call ``` Product.ordered ``` It will return all your products ordered by when they were created. If you then want the very first product you just to ``` Product.ordered.first ``` In the case you just want to get the item in one specific place you could do the following (instead of what i mentioned above) Product.find(:first, :order => 'created\_at ASC') If my explanation is not clear, just let me know and i'll try to refrase
Okay. Let's assume that when you call `Product.all` that it returns the products in the order you've specified above. So, to get Sweeter, you could call `Product.all.first`. Or, if in your controller you've done `@products = Product.all` and you want it in your view you can use `@products.first`. Or if you're looping through them and want to do something special with the first one you could do this: ``` <% @products.each_with_index do |product, i| %> <% if id == 0 %> do something special as this is the first product <% end %> <% end %> ```
7,771,607
I've already do my research but I think I don't know how to ask so I'll try to explain... Im looking for a way to ask for the first entry saved on a Scaffold... Like If I have in the table Products: * Sweeter * Pants * Scarf * Tennis and I write `@first_prod = Products.first` (or something like that) on my model or in my view `<%= Products.each.first %>` (or something like that) Rails give me the first prouduct in this case - Sweeter... Thanks in advance...
2011/10/14
[ "https://Stackoverflow.com/questions/7771607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/992653/" ]
In rails you can define a few default ways to get the content from a model. In your case i would create a scope. in your model enter the following: ``` scope ordered, :order => "Product.created_at ASC" ``` When you call ``` Product.ordered ``` It will return all your products ordered by when they were created. If you then want the very first product you just to ``` Product.ordered.first ``` In the case you just want to get the item in one specific place you could do the following (instead of what i mentioned above) Product.find(:first, :order => 'created\_at ASC') If my explanation is not clear, just let me know and i'll try to refrase
You answered your own question, I think... If you know you want access to the first saved item of a specific model, then you would just call `Product.first`. So, in the controller action for the view you want to access that data in, just type `@product = Product.first`... for example ``` def index @products = Product.all @product = Product.first end ``` That way you can access the first saved product as well as have access to the entire collection in your index view code.
16,308,375
I'm writing a simple MVC4 application in which I chose the internet application template when I created the project. When I right click **\_Layout.cshtml** and go to **view in page inspector**, I receive a screen in the page inspector view that says > > "Server Error in '/' Application. > --------------------------------- > > > The resource cannot be found. > Description: HTTP 404. The resource you are looking for (or one of its dependencies) > > could have been removed, had its name changed, or is temporarily unavailable. Please > review the following URL and make sure that it is spelled correctly. > > > **Requested URL: /Shared/\_Layout** > > > > > --- > > > Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18034 > > > However, the **\_layout.cshtml** shows up fine when launching debug mode for the solution. Also, the other cshtml pages are showing up fine in page inspector mode. Views/\_ViewStart.cshtml ------------------------ **Browse to URL property**: ~/Views/\_ViewStart.cshtml ``` @{ Layout = "~/Views/Shared/_Layout.cshtml"; } ``` Views/Shared/\_Layout.cshtml ---------------------------- **Browse to URL property**: ~/Views/Shared/\_Layout ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>@ViewBag.Title - Movie App</title> <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width" /> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <header> <div class="content-wrapper"> <div class="float-left"> <p class="site-title">@Html.ActionLink("MVC Movie", "Index", "Home")</p> </div> <div class="float-right"> <section id="login"> @Html.Partial("_LoginPartial") </section> <nav> <ul id="menu"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul> </nav> </div> </div> </header> <div id="body"> @RenderSection("featured", required: false) <section class="content-wrapper main-content clear-fix"> @RenderBody() </section> </div> <footer> <div class="content-wrapper"> <div class="float-left"> <p>&copy; @DateTime.Now.Year - My ASP.NET MVC Application</p> </div> </div> </footer> @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) </body> </html> ``` If you need more information to help solve this problem, please ask and I'll post it.
2013/04/30
[ "https://Stackoverflow.com/questions/16308375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1691849/" ]
Okay, I still stand by my comment that it is not meant to view the layout file as a standalone piece. However, I was a little curious as to the issue of viewing the layout. If you look at the provided link, you will see how to properly use the Page Inspector. Please look at item number 5. That will give you some details on how to view pieces of your \_layout file. <http://www.asp.net/mvc/tutorials/mvc-4/using-page-inspector-in-aspnet-mvc>
I also could not open .cshtml files. Maybe page inspector is not supposed to do that. I think it is supposed to load the website in your local host the same way a browser would. Instead of trying to open the .cshtml file, try opening the website by opening the namespace/assembly name. When I do that page inspector works. I also did some other things beforehand which may have helped. I read them [here](https://social.msdn.microsoft.com/Forums/vstudio/en-US/0a692461-10f2-4d97-a3e9-1d2df92dcc0b/server-error-in-application-could-not-load-file-or-assembly?forum=lightswitch). "I am getting this same error, and I tried to apply the proposed solution above. I still get the error after. And while I am using a 64-bit machine, I went on to try the same solution in the ...\Framework...\ folder. After editing and saving, the problem went away. /\*\*\* Open your root web.config, (in C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config) and comment (change 'add' to 'remove') this line referencing the assembly: \*\*\*/ PrfyVdlx"
1,520,231
I am trying to integrate a calendar plugin like google calendar with custom database and code with asp.net MVC in C#. It needs to handle Day/Week/Month Events in the Calendar as like google calendar. I found the similar plugin in jquery <http://www.webappers.com/2009/08/04/jquery-weekly-calendar-plugin-inspired-by-google-calendar/>. But it shows only the Week Do anyone have a reference to this? Please suggest
2009/10/05
[ "https://Stackoverflow.com/questions/1520231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111435/" ]
I answered a similar question a while ago, "[ASP.net weekly schedule control](https://stackoverflow.com/questions/700810/asp-net-weekly-schedule-control)", and the answer there would still be relevant to yourself. > > [DayPilot](http://www.daypilot.org/) is a pretty good general > purpose calendaring/schedule control. > > > The full version is not free, but > there is a "lite" version available > which is not only free but open > source! > > > The "lite" version will give you both Day and Week (and "Work" week) views of the calendar and will show a Month Scheduler view. Whilst the original DayPilot component is not meant for ASP.NET MVC, a guy called Craig Stuntz has adapted the DayPilot Lite component for ASP.NET MVC: [Using DayPilot with ASP.NET MVC](http://blogs.teamb.com/craigstuntz/2009/05/12/38297/)
Use Google's [Calendar API](http://code.google.com/apis/calendar/)
1,520,231
I am trying to integrate a calendar plugin like google calendar with custom database and code with asp.net MVC in C#. It needs to handle Day/Week/Month Events in the Calendar as like google calendar. I found the similar plugin in jquery <http://www.webappers.com/2009/08/04/jquery-weekly-calendar-plugin-inspired-by-google-calendar/>. But it shows only the Week Do anyone have a reference to this? Please suggest
2009/10/05
[ "https://Stackoverflow.com/questions/1520231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111435/" ]
I'd try [FullCalendar](http://arshaw.com/fullcalendar/)
I answered a similar question a while ago, "[ASP.net weekly schedule control](https://stackoverflow.com/questions/700810/asp-net-weekly-schedule-control)", and the answer there would still be relevant to yourself. > > [DayPilot](http://www.daypilot.org/) is a pretty good general > purpose calendaring/schedule control. > > > The full version is not free, but > there is a "lite" version available > which is not only free but open > source! > > > The "lite" version will give you both Day and Week (and "Work" week) views of the calendar and will show a Month Scheduler view. Whilst the original DayPilot component is not meant for ASP.NET MVC, a guy called Craig Stuntz has adapted the DayPilot Lite component for ASP.NET MVC: [Using DayPilot with ASP.NET MVC](http://blogs.teamb.com/craigstuntz/2009/05/12/38297/)
1,520,231
I am trying to integrate a calendar plugin like google calendar with custom database and code with asp.net MVC in C#. It needs to handle Day/Week/Month Events in the Calendar as like google calendar. I found the similar plugin in jquery <http://www.webappers.com/2009/08/04/jquery-weekly-calendar-plugin-inspired-by-google-calendar/>. But it shows only the Week Do anyone have a reference to this? Please suggest
2009/10/05
[ "https://Stackoverflow.com/questions/1520231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111435/" ]
I answered a similar question a while ago, "[ASP.net weekly schedule control](https://stackoverflow.com/questions/700810/asp-net-weekly-schedule-control)", and the answer there would still be relevant to yourself. > > [DayPilot](http://www.daypilot.org/) is a pretty good general > purpose calendaring/schedule control. > > > The full version is not free, but > there is a "lite" version available > which is not only free but open > source! > > > The "lite" version will give you both Day and Week (and "Work" week) views of the calendar and will show a Month Scheduler view. Whilst the original DayPilot component is not meant for ASP.NET MVC, a guy called Craig Stuntz has adapted the DayPilot Lite component for ASP.NET MVC: [Using DayPilot with ASP.NET MVC](http://blogs.teamb.com/craigstuntz/2009/05/12/38297/)
I am using this jquery plugin. <http://www.web-delicious.com/jquery-events-calendar-wdcalendar/> It provide php mvc sample, you can convert it to .net mvc
1,520,231
I am trying to integrate a calendar plugin like google calendar with custom database and code with asp.net MVC in C#. It needs to handle Day/Week/Month Events in the Calendar as like google calendar. I found the similar plugin in jquery <http://www.webappers.com/2009/08/04/jquery-weekly-calendar-plugin-inspired-by-google-calendar/>. But it shows only the Week Do anyone have a reference to this? Please suggest
2009/10/05
[ "https://Stackoverflow.com/questions/1520231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111435/" ]
I answered a similar question a while ago, "[ASP.net weekly schedule control](https://stackoverflow.com/questions/700810/asp-net-weekly-schedule-control)", and the answer there would still be relevant to yourself. > > [DayPilot](http://www.daypilot.org/) is a pretty good general > purpose calendaring/schedule control. > > > The full version is not free, but > there is a "lite" version available > which is not only free but open > source! > > > The "lite" version will give you both Day and Week (and "Work" week) views of the calendar and will show a Month Scheduler view. Whilst the original DayPilot component is not meant for ASP.NET MVC, a guy called Craig Stuntz has adapted the DayPilot Lite component for ASP.NET MVC: [Using DayPilot with ASP.NET MVC](http://blogs.teamb.com/craigstuntz/2009/05/12/38297/)
The best one I found is [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler/). It is highly customizable, fires events and works cross-browser. It is free for GPL projects, otherwise there are commercial licenses available with affordable prices. And their customer support is excellent!
1,520,231
I am trying to integrate a calendar plugin like google calendar with custom database and code with asp.net MVC in C#. It needs to handle Day/Week/Month Events in the Calendar as like google calendar. I found the similar plugin in jquery <http://www.webappers.com/2009/08/04/jquery-weekly-calendar-plugin-inspired-by-google-calendar/>. But it shows only the Week Do anyone have a reference to this? Please suggest
2009/10/05
[ "https://Stackoverflow.com/questions/1520231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111435/" ]
I'd try [FullCalendar](http://arshaw.com/fullcalendar/)
Use Google's [Calendar API](http://code.google.com/apis/calendar/)
1,520,231
I am trying to integrate a calendar plugin like google calendar with custom database and code with asp.net MVC in C#. It needs to handle Day/Week/Month Events in the Calendar as like google calendar. I found the similar plugin in jquery <http://www.webappers.com/2009/08/04/jquery-weekly-calendar-plugin-inspired-by-google-calendar/>. But it shows only the Week Do anyone have a reference to this? Please suggest
2009/10/05
[ "https://Stackoverflow.com/questions/1520231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111435/" ]
The best one I found is [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler/). It is highly customizable, fires events and works cross-browser. It is free for GPL projects, otherwise there are commercial licenses available with affordable prices. And their customer support is excellent!
Use Google's [Calendar API](http://code.google.com/apis/calendar/)
1,520,231
I am trying to integrate a calendar plugin like google calendar with custom database and code with asp.net MVC in C#. It needs to handle Day/Week/Month Events in the Calendar as like google calendar. I found the similar plugin in jquery <http://www.webappers.com/2009/08/04/jquery-weekly-calendar-plugin-inspired-by-google-calendar/>. But it shows only the Week Do anyone have a reference to this? Please suggest
2009/10/05
[ "https://Stackoverflow.com/questions/1520231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111435/" ]
I'd try [FullCalendar](http://arshaw.com/fullcalendar/)
I am using this jquery plugin. <http://www.web-delicious.com/jquery-events-calendar-wdcalendar/> It provide php mvc sample, you can convert it to .net mvc
1,520,231
I am trying to integrate a calendar plugin like google calendar with custom database and code with asp.net MVC in C#. It needs to handle Day/Week/Month Events in the Calendar as like google calendar. I found the similar plugin in jquery <http://www.webappers.com/2009/08/04/jquery-weekly-calendar-plugin-inspired-by-google-calendar/>. But it shows only the Week Do anyone have a reference to this? Please suggest
2009/10/05
[ "https://Stackoverflow.com/questions/1520231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111435/" ]
I'd try [FullCalendar](http://arshaw.com/fullcalendar/)
The best one I found is [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler/). It is highly customizable, fires events and works cross-browser. It is free for GPL projects, otherwise there are commercial licenses available with affordable prices. And their customer support is excellent!
1,520,231
I am trying to integrate a calendar plugin like google calendar with custom database and code with asp.net MVC in C#. It needs to handle Day/Week/Month Events in the Calendar as like google calendar. I found the similar plugin in jquery <http://www.webappers.com/2009/08/04/jquery-weekly-calendar-plugin-inspired-by-google-calendar/>. But it shows only the Week Do anyone have a reference to this? Please suggest
2009/10/05
[ "https://Stackoverflow.com/questions/1520231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111435/" ]
The best one I found is [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler/). It is highly customizable, fires events and works cross-browser. It is free for GPL projects, otherwise there are commercial licenses available with affordable prices. And their customer support is excellent!
I am using this jquery plugin. <http://www.web-delicious.com/jquery-events-calendar-wdcalendar/> It provide php mvc sample, you can convert it to .net mvc
41,282,587
I have a 2-dimensional lattice (L\*L) with fixed boundaries and considering N-S-W-E sites as 4 neighbours to each site. Each site is assigned an float value. For each site I am calculating average of values of its neighbouring sites added to its own value. I want to solve this using convolv2d from scipy.signal. Following is my code: ``` # xi_out = constant1*xi + constant2*(sum of xi's neighbours)/no_of_xi's_neighbours import numpy as np from scipy.signal import convolve2d L = 6 # each side of 2D lattice a, b = (0.1, 0.5) # two constants arr = np.random.rand(L, L) # example 2D array # (3,3) window representing 4 neighbours which slides over 'arr' kernel = np.array([[0, b, 0], [b, a, b], [0, b, 0]]) neighbors_sum = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) print(neighbors_sum) ``` I can not find a way to divide sum of neighbouring values for each site by number of its neighbours. In following manner I can find number of neighbours for each site but do not know how to incorporate these values into 'result'. Can somebody suggest me how can I achieve that or is there a simpler in-built method in convolve2d to do that ? ``` arr = np.ones((L,L), dtype=np.int) kernel = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) neighbors_count = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) print(neighbors_count) ```
2016/12/22
[ "https://Stackoverflow.com/questions/41282587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7245071/" ]
[jQuery.getJSON()](http://api.jquery.com/jquery.getjson/) load JSON-encoded data from the server using a GET HTTP request. As you post in your JSON structure you can access to the array by calling `json.data`: ``` $.getJSON("/ajax/data/myjasonfile.json", function(json) { console.log(json.data); // Logs your array }); ```
you can try this: ``` $.getJSON("test.json", function(json) { console.log(json); // this will show the info it in firebug console }); ``` I think, Some issue is in your path to call json file. you need to check again of path. You can check this link: [Loading local JSON file](https://stackoverflow.com/questions/7346563/loading-local-json-file)
41,282,587
I have a 2-dimensional lattice (L\*L) with fixed boundaries and considering N-S-W-E sites as 4 neighbours to each site. Each site is assigned an float value. For each site I am calculating average of values of its neighbouring sites added to its own value. I want to solve this using convolv2d from scipy.signal. Following is my code: ``` # xi_out = constant1*xi + constant2*(sum of xi's neighbours)/no_of_xi's_neighbours import numpy as np from scipy.signal import convolve2d L = 6 # each side of 2D lattice a, b = (0.1, 0.5) # two constants arr = np.random.rand(L, L) # example 2D array # (3,3) window representing 4 neighbours which slides over 'arr' kernel = np.array([[0, b, 0], [b, a, b], [0, b, 0]]) neighbors_sum = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) print(neighbors_sum) ``` I can not find a way to divide sum of neighbouring values for each site by number of its neighbours. In following manner I can find number of neighbours for each site but do not know how to incorporate these values into 'result'. Can somebody suggest me how can I achieve that or is there a simpler in-built method in convolve2d to do that ? ``` arr = np.ones((L,L), dtype=np.int) kernel = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) neighbors_count = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) print(neighbors_count) ```
2016/12/22
[ "https://Stackoverflow.com/questions/41282587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7245071/" ]
Try this to understand your response structure. ``` $.getJSON("myjasonfile.json", function(json) { console.log(json); // access the response object console.log(json.data); // access the array console.log(json.data[0]); // access the first object of the array console.log(json.data[0].number); // access the first object proprty of the array }); ```
[jQuery.getJSON()](http://api.jquery.com/jquery.getjson/) load JSON-encoded data from the server using a GET HTTP request. As you post in your JSON structure you can access to the array by calling `json.data`: ``` $.getJSON("/ajax/data/myjasonfile.json", function(json) { console.log(json.data); // Logs your array }); ```
41,282,587
I have a 2-dimensional lattice (L\*L) with fixed boundaries and considering N-S-W-E sites as 4 neighbours to each site. Each site is assigned an float value. For each site I am calculating average of values of its neighbouring sites added to its own value. I want to solve this using convolv2d from scipy.signal. Following is my code: ``` # xi_out = constant1*xi + constant2*(sum of xi's neighbours)/no_of_xi's_neighbours import numpy as np from scipy.signal import convolve2d L = 6 # each side of 2D lattice a, b = (0.1, 0.5) # two constants arr = np.random.rand(L, L) # example 2D array # (3,3) window representing 4 neighbours which slides over 'arr' kernel = np.array([[0, b, 0], [b, a, b], [0, b, 0]]) neighbors_sum = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) print(neighbors_sum) ``` I can not find a way to divide sum of neighbouring values for each site by number of its neighbours. In following manner I can find number of neighbours for each site but do not know how to incorporate these values into 'result'. Can somebody suggest me how can I achieve that or is there a simpler in-built method in convolve2d to do that ? ``` arr = np.ones((L,L), dtype=np.int) kernel = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) neighbors_count = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) print(neighbors_count) ```
2016/12/22
[ "https://Stackoverflow.com/questions/41282587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7245071/" ]
Try this to understand your response structure. ``` $.getJSON("myjasonfile.json", function(json) { console.log(json); // access the response object console.log(json.data); // access the array console.log(json.data[0]); // access the first object of the array console.log(json.data[0].number); // access the first object proprty of the array }); ```
you can try this: ``` $.getJSON("test.json", function(json) { console.log(json); // this will show the info it in firebug console }); ``` I think, Some issue is in your path to call json file. you need to check again of path. You can check this link: [Loading local JSON file](https://stackoverflow.com/questions/7346563/loading-local-json-file)
41,282,587
I have a 2-dimensional lattice (L\*L) with fixed boundaries and considering N-S-W-E sites as 4 neighbours to each site. Each site is assigned an float value. For each site I am calculating average of values of its neighbouring sites added to its own value. I want to solve this using convolv2d from scipy.signal. Following is my code: ``` # xi_out = constant1*xi + constant2*(sum of xi's neighbours)/no_of_xi's_neighbours import numpy as np from scipy.signal import convolve2d L = 6 # each side of 2D lattice a, b = (0.1, 0.5) # two constants arr = np.random.rand(L, L) # example 2D array # (3,3) window representing 4 neighbours which slides over 'arr' kernel = np.array([[0, b, 0], [b, a, b], [0, b, 0]]) neighbors_sum = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) print(neighbors_sum) ``` I can not find a way to divide sum of neighbouring values for each site by number of its neighbours. In following manner I can find number of neighbours for each site but do not know how to incorporate these values into 'result'. Can somebody suggest me how can I achieve that or is there a simpler in-built method in convolve2d to do that ? ``` arr = np.ones((L,L), dtype=np.int) kernel = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) neighbors_count = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) print(neighbors_count) ```
2016/12/22
[ "https://Stackoverflow.com/questions/41282587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7245071/" ]
Store The json Data in Array: ``` $.getJSON("/ajax/data/myjasonfile.json", function(Data) { var array=[]; for(var i=1;i<Data.length;i++) { var b=Data[i]; var c=[]; c.push(b.number); c.push(b.nameOne); c.push(b.type); c.push(b.flagName); c.push(b.buildDate); array.push(c); } console.log(array); }); ```
you can try this: ``` $.getJSON("test.json", function(json) { console.log(json); // this will show the info it in firebug console }); ``` I think, Some issue is in your path to call json file. you need to check again of path. You can check this link: [Loading local JSON file](https://stackoverflow.com/questions/7346563/loading-local-json-file)
41,282,587
I have a 2-dimensional lattice (L\*L) with fixed boundaries and considering N-S-W-E sites as 4 neighbours to each site. Each site is assigned an float value. For each site I am calculating average of values of its neighbouring sites added to its own value. I want to solve this using convolv2d from scipy.signal. Following is my code: ``` # xi_out = constant1*xi + constant2*(sum of xi's neighbours)/no_of_xi's_neighbours import numpy as np from scipy.signal import convolve2d L = 6 # each side of 2D lattice a, b = (0.1, 0.5) # two constants arr = np.random.rand(L, L) # example 2D array # (3,3) window representing 4 neighbours which slides over 'arr' kernel = np.array([[0, b, 0], [b, a, b], [0, b, 0]]) neighbors_sum = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) print(neighbors_sum) ``` I can not find a way to divide sum of neighbouring values for each site by number of its neighbours. In following manner I can find number of neighbours for each site but do not know how to incorporate these values into 'result'. Can somebody suggest me how can I achieve that or is there a simpler in-built method in convolve2d to do that ? ``` arr = np.ones((L,L), dtype=np.int) kernel = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) neighbors_count = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) print(neighbors_count) ```
2016/12/22
[ "https://Stackoverflow.com/questions/41282587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7245071/" ]
Try this to understand your response structure. ``` $.getJSON("myjasonfile.json", function(json) { console.log(json); // access the response object console.log(json.data); // access the array console.log(json.data[0]); // access the first object of the array console.log(json.data[0].number); // access the first object proprty of the array }); ```
Store The json Data in Array: ``` $.getJSON("/ajax/data/myjasonfile.json", function(Data) { var array=[]; for(var i=1;i<Data.length;i++) { var b=Data[i]; var c=[]; c.push(b.number); c.push(b.nameOne); c.push(b.type); c.push(b.flagName); c.push(b.buildDate); array.push(c); } console.log(array); }); ```
51,487
I have a document library containing a lot of personal information. Originally only admins could see the library but now it has been decided that users need to see their own information. Admins have Full Control and users have Read. The default view shows only documents where the user's name appears in a certain field. So Default View, Name="[Me]" so they can only see their own files. This works fine but it doesn't stop users from opening the library in Explorer view. How can I stop them doing this? Any suggestions? Note: I do not have access to Central Administration
2012/11/13
[ "https://sharepoint.stackexchange.com/questions/51487", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/7433/" ]
^ Disregard the first, I think I misread your question. The answer in this link may help you instead: <http://social.msdn.microsoft.com/Forums/gu-IN/sharepoint2010customization/thread/5faea89f-f3ea-4b4b-b4c0-2c0cc7e6ceee>
Fooling around with the SharePoint masterpage is a delicate matter if you don't understand its structure. Thus trying to remove the Quicklaunch from the masterpage is not a good idea. What I can recommend you do is to hide the quicklaunch with some CSS, and then on the pages that you actually want it to appear you insert preferably a HTML Form Web Part in which you insert some CSS to make it appear again. And if you want it to be placed any other place than its original place use some javascript to move it to the position of your choice.
1,266,731
I moved to Kubuntu 20.04 recently.Two days ago I installed pyenv and using pyenv i installed python(3.6.8) then I looked for available python versions from pyenv using this command. ``` samip@samip-Inspiron-3521:~$ pyenv versions 3.6.8 ``` But it only showed me this recently installed version but my system has python 3.8.2 installed but anyway i used the 3.6.8 as global version using this command ``` samip@samip-Inspiron-3521:~$ pyenv global 3.6.8 ``` But now i cannot switch back to system version. ``` samip@samip-Inspiron-3521:~$ pyenv global system pyenv: system version not found in PATH ``` I am new to linux and programming please give me step-by-step solution. ``` samip@samip-Inspiron-3521:~$ echo $PATH /home/samip/.pyenv/plugins/pyenv-virtualenv/shims:/home/samip/.pyenv/shims:/home/samip/.pyenv/bin:/home/samip/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin ```
2020/08/13
[ "https://askubuntu.com/questions/1266731", "https://askubuntu.com", "https://askubuntu.com/users/1116117/" ]
The problem on a fresh Kubuntu 20.04 installation is that there is no python executable. The `/usr/bin` only has `python2` and `python3` but pyenv checks for `python` to determine if a system version is available. As a workaround create a python executable yourself: ``` ln -s /usr/bin/python3 /usr/bin/python ```
The prior answers solve this manually; there is also a package that will make the link: `python-is-python3`. Useful for including in your standard set of packages to install when setting up a new system. Related GitHub bug thread: [Pyenv can't find system python (3.8) on Ubuntu 20.04 (#1613)](https://github.com/pyenv/pyenv/issues/1613)
24,762,520
We have the demo [here](http://angular-ui.github.io/ui-utils/#/mask) on the angular-ui page. Wondering how we can write a mask with optional extension number. `(999) 999-9999 ext. 999` will make the extension required.
2014/07/15
[ "https://Stackoverflow.com/questions/24762520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863637/" ]
I shared this same problem with you. There is a completely undocumented optional character feature for this component. I could only find it by reading the source code. The solution for your mask would be: ``` (999) 999-9999 ext. ?9?9?9 ``` Question marks in your mask will flag the next character as optional. Trust me, it works. Sorry for taking so long to answer.
Still no answer for this one after two weeks. I would assume all agreed this AngularUI is too limited in handling this situation. I ended up using `jquery.inputmask` (<http://github.com/RobinHerbots/jquery.inputmask>). We have been using this jQuery extension library since there is no Angular. It appears still the most powerful input mask. At least it has all functions I need. Here is my setup. 1. First, of course is to NuGet or download the library. The current version (3.0.55) separates functions into different js files. (date, numeric, phone...) Be sure to include all that you need. 2. Create a directive for input mask attribute or class. Use `link` in this directive to use jQuery to apply input mask: Here is the code: ``` (function(){ 'use strict'; var directiveId = 'myInputMask'; angular.module('myApp')..directive(directiveId, function() { return { restrict: 'AC', link: function (scope, el, attrs) { el.inputmask(scope.$eval(attrs.myInputMask)); el.on('change', function() { scope.$eval(attrs.ngModel + "='" + el.val() + "'"); // or scope[attrs.ngModel] = el.val() if your expression doesn't contain dot. }); } } }); })(); ``` 1. At last, apply this directive in attribute or class in our Html. Here is the Html: ``` <input type="text" id="phone" my-input-mask="{mask: '(999)999-9999[ ext. 9999]', greedy: false}" required="" ng-model="employee.phone"> ``` Of course, with `jquery.inputmask`, we can have much more complex input mask: ``` <input type="text" id="salary" dnr-input-mask="{'alias': 'numeric', 'groupSeparator': ',', 'autoGroup': true, 'digits': 2, 'digitsOptional': true, 'placeholder': '0'}" model="employee.salary"> ``` So the conclusion: AngularUI still has a long way to go to satisfy our need. At this moment, `jQuery.inputmask` still thrives.
24,762,520
We have the demo [here](http://angular-ui.github.io/ui-utils/#/mask) on the angular-ui page. Wondering how we can write a mask with optional extension number. `(999) 999-9999 ext. 999` will make the extension required.
2014/07/15
[ "https://Stackoverflow.com/questions/24762520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863637/" ]
Still no answer for this one after two weeks. I would assume all agreed this AngularUI is too limited in handling this situation. I ended up using `jquery.inputmask` (<http://github.com/RobinHerbots/jquery.inputmask>). We have been using this jQuery extension library since there is no Angular. It appears still the most powerful input mask. At least it has all functions I need. Here is my setup. 1. First, of course is to NuGet or download the library. The current version (3.0.55) separates functions into different js files. (date, numeric, phone...) Be sure to include all that you need. 2. Create a directive for input mask attribute or class. Use `link` in this directive to use jQuery to apply input mask: Here is the code: ``` (function(){ 'use strict'; var directiveId = 'myInputMask'; angular.module('myApp')..directive(directiveId, function() { return { restrict: 'AC', link: function (scope, el, attrs) { el.inputmask(scope.$eval(attrs.myInputMask)); el.on('change', function() { scope.$eval(attrs.ngModel + "='" + el.val() + "'"); // or scope[attrs.ngModel] = el.val() if your expression doesn't contain dot. }); } } }); })(); ``` 1. At last, apply this directive in attribute or class in our Html. Here is the Html: ``` <input type="text" id="phone" my-input-mask="{mask: '(999)999-9999[ ext. 9999]', greedy: false}" required="" ng-model="employee.phone"> ``` Of course, with `jquery.inputmask`, we can have much more complex input mask: ``` <input type="text" id="salary" dnr-input-mask="{'alias': 'numeric', 'groupSeparator': ',', 'autoGroup': true, 'digits': 2, 'digitsOptional': true, 'placeholder': '0'}" model="employee.salary"> ``` So the conclusion: AngularUI still has a long way to go to satisfy our need. At this moment, `jQuery.inputmask` still thrives.
A good solution for this problem is to use [ngMask](https://github.com/candreoliveira/ngMask) which allows you to do exactly what you want without jQuery. To do that just add an '?' after the character you want to be optional: `mask="9?9999-9999` This is great for inputs like Brazilian phone numbers, which can have both 8 or 9 characters.
24,762,520
We have the demo [here](http://angular-ui.github.io/ui-utils/#/mask) on the angular-ui page. Wondering how we can write a mask with optional extension number. `(999) 999-9999 ext. 999` will make the extension required.
2014/07/15
[ "https://Stackoverflow.com/questions/24762520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863637/" ]
I shared this same problem with you. There is a completely undocumented optional character feature for this component. I could only find it by reading the source code. The solution for your mask would be: ``` (999) 999-9999 ext. ?9?9?9 ``` Question marks in your mask will flag the next character as optional. Trust me, it works. Sorry for taking so long to answer.
A good solution for this problem is to use [ngMask](https://github.com/candreoliveira/ngMask) which allows you to do exactly what you want without jQuery. To do that just add an '?' after the character you want to be optional: `mask="9?9999-9999` This is great for inputs like Brazilian phone numbers, which can have both 8 or 9 characters.
24,762,520
We have the demo [here](http://angular-ui.github.io/ui-utils/#/mask) on the angular-ui page. Wondering how we can write a mask with optional extension number. `(999) 999-9999 ext. 999` will make the extension required.
2014/07/15
[ "https://Stackoverflow.com/questions/24762520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863637/" ]
I shared this same problem with you. There is a completely undocumented optional character feature for this component. I could only find it by reading the source code. The solution for your mask would be: ``` (999) 999-9999 ext. ?9?9?9 ``` Question marks in your mask will flag the next character as optional. Trust me, it works. Sorry for taking so long to answer.
``` (999) 999-9999 ext. ?9?9?9 ``` This will work good but if you want to clear on blur and put the mask back then you need a little more, I used like this ``` <input type='text' ng-model='customer.phone' ui-mask="{{phoneMask}}" ng-blur="removeMask()" ng-focus="placeMask()" /> ``` And in my controller: ``` $scope.phoneMask= "(999) 999-9999 ext. ?9?9?9"; $scope.removeMask = function () { if ($scope.rep.phone.length === 10) { $scope.phoneMask= "(999) 999-9999"; } }; $scope.placeMask = function () { $scope.phoneMask= "(999) 999-9999 ext. ?9?9?9"; } ``` Hope it will help!
24,762,520
We have the demo [here](http://angular-ui.github.io/ui-utils/#/mask) on the angular-ui page. Wondering how we can write a mask with optional extension number. `(999) 999-9999 ext. 999` will make the extension required.
2014/07/15
[ "https://Stackoverflow.com/questions/24762520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863637/" ]
``` (999) 999-9999 ext. ?9?9?9 ``` This will work good but if you want to clear on blur and put the mask back then you need a little more, I used like this ``` <input type='text' ng-model='customer.phone' ui-mask="{{phoneMask}}" ng-blur="removeMask()" ng-focus="placeMask()" /> ``` And in my controller: ``` $scope.phoneMask= "(999) 999-9999 ext. ?9?9?9"; $scope.removeMask = function () { if ($scope.rep.phone.length === 10) { $scope.phoneMask= "(999) 999-9999"; } }; $scope.placeMask = function () { $scope.phoneMask= "(999) 999-9999 ext. ?9?9?9"; } ``` Hope it will help!
A good solution for this problem is to use [ngMask](https://github.com/candreoliveira/ngMask) which allows you to do exactly what you want without jQuery. To do that just add an '?' after the character you want to be optional: `mask="9?9999-9999` This is great for inputs like Brazilian phone numbers, which can have both 8 or 9 characters.
84,796
I seem to be asking questions that often belong to other overflow sites. Where can I browse the list of current overflow sites so I can choose one where to ask the question?
2011/03/25
[ "https://meta.stackexchange.com/questions/84796", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/159333/" ]
Look up and left in this page. There you will see the Stack Exchange™ MultiCollider SuperDropdown™. Second tab is what you want. Or hop on over to <http://stackexchange.com> and check the [Sites tab](https://stackexchange.com/sites). The page footer also lists all sites which have been officially launched.
On Area 51 you can see the sites that have been launched and the ones which are currently in their beta phase, as well as proposals for new sites. However Area 51 does not list sites which were created without an Area 51 proposal (i.e. the main triology). You can see all non-Area 51 sites as well as the launched Area 51 sites in the list of links at the bottom of each page (though unlike Area 51 that list does not include any descriptions).
1,956,757
How can I replace the last two matched string `string s= "{\"test\":\"value\"}";` From this string "s" I need to remove the double quotes of the value. But I need generic, like the value may be any string in feature. I need this to be done in `C#`.
2009/12/24
[ "https://Stackoverflow.com/questions/1956757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/171365/" ]
This [example](http://answers.oreilly.com/topic/340-how-to-quickly-find-the-last-match-in-a-string-in-c/) shows how to search a string using regex from right to left. You might find it of use.
You could use [String.LastIndexOf](http://msdn.microsoft.com/en-us/library/system.string.lastindexof%28v=VS.71%29.aspx) and [String.Remove](http://msdn.microsoft.com/en-us/library/system.string.remove%28v=VS.71%29.aspx) methods: ``` for (int i = 0; i < 2; i++) { s = s.Remove(s.LastIndexOf("\""), 1); } ``` It will produce String `{"test":value}` from `{"test":"value"}`, and I believe that's what you wanted to achieve.
1,228,440
I am having trouble writing a typeof statement which would be using a variable from a config file the code is like this ``` Type t = new typeof ("My.other.class" + configValue[0]); ``` configValue being the dynamic value I get from the app.config file. The error I get is "type expected" it is fine if I type out the class directly so I am assuming my formatting is incorrect. How should this be written?
2009/08/04
[ "https://Stackoverflow.com/questions/1228440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/88765/" ]
The `typeof` keyword is for compile-time use. Use the [`Type.GetType(string)`](http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx) API instead.
To do this using just a namespace and class name (like in the question), you'll also need to know which assembly contains the class. If the currently running assembly (or mscorlib) contains the Type, then you can use [Type.GetType(string)](http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx) to get the Type. If the Type is contained in a different assembly (ie: a library), then you'll need to use [Assembly.GetType](http://msdn.microsoft.com/en-us/library/y0cd10tb.aspx) instead. This requires having an Assembly instance, however, which can be retrieved via Assembly.Load, or using another type within the assembly.
1,228,440
I am having trouble writing a typeof statement which would be using a variable from a config file the code is like this ``` Type t = new typeof ("My.other.class" + configValue[0]); ``` configValue being the dynamic value I get from the app.config file. The error I get is "type expected" it is fine if I type out the class directly so I am assuming my formatting is incorrect. How should this be written?
2009/08/04
[ "https://Stackoverflow.com/questions/1228440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/88765/" ]
The `typeof` keyword is for compile-time use. Use the [`Type.GetType(string)`](http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx) API instead.
Is this what you're looking for? ``` Type t = Type.GetType("spork"); object myspork = Activator.CreateInstance(t); ```
1,228,440
I am having trouble writing a typeof statement which would be using a variable from a config file the code is like this ``` Type t = new typeof ("My.other.class" + configValue[0]); ``` configValue being the dynamic value I get from the app.config file. The error I get is "type expected" it is fine if I type out the class directly so I am assuming my formatting is incorrect. How should this be written?
2009/08/04
[ "https://Stackoverflow.com/questions/1228440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/88765/" ]
Is this what you're looking for? ``` Type t = Type.GetType("spork"); object myspork = Activator.CreateInstance(t); ```
To do this using just a namespace and class name (like in the question), you'll also need to know which assembly contains the class. If the currently running assembly (or mscorlib) contains the Type, then you can use [Type.GetType(string)](http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx) to get the Type. If the Type is contained in a different assembly (ie: a library), then you'll need to use [Assembly.GetType](http://msdn.microsoft.com/en-us/library/y0cd10tb.aspx) instead. This requires having an Assembly instance, however, which can be retrieved via Assembly.Load, or using another type within the assembly.
45,797,025
This is my database table: [![Database table](https://i.stack.imgur.com/fXsjl.jpg)](https://i.stack.imgur.com/fXsjl.jpg) I want to display this table (5 columns) on my page when clicking a button (List Users). But I'm getting the following as output: [![Output table](https://i.stack.imgur.com/vMaLQ.jpg)](https://i.stack.imgur.com/vMaLQ.jpg) My code is: ``` <?php $db = "*"; //masked for security $host = "*"; //masked for security $user = "*";//masked for security $pwd = "*; //masked for security $con = mysqli_connect($host,$user,$pwd,$db); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } $sql="SELECT login_id,user_name,password,user_role,status_id FROM login"; $select = mysqli_query($con,$sql); $num_rows = mysqli_num_rows($select); echo "Number of rows : "; echo $num_rows; $row = mysqli_fetch_array($select, MYSQLI_ASSOC); echo "<table> <tr> <th>Login ID</th> <th>User name</th> <th>Password</th> <th>User Role</th> <th>Status ID</th> </tr>"; foreach ($row as $rows) { echo "<tr>"; echo "<td>" . $rows['login_id'] . "</td>"; echo "<td>" . $rows['user_name'] . "</td>"; echo "<td>" . $rows['password'] . "</td>"; echo "<td>" . $rows['user_role'] . "</td>"; echo "<td>" . $rows['status_id'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?> ``` Please help me find the error in this code.
2017/08/21
[ "https://Stackoverflow.com/questions/45797025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1745446/" ]
I've reached out to Fabric support and got an answer: > > The Latest Releases page shows all builds that have been used by at > least 10% of your Daily Active Users (DAU) on any single day in the > past 30 days or at least 4% of DAU on the current day. What's likely > happening is that 3.5.9 isn't hitting the criteria just yet. > > > As a workaround, if you manually add the version and build to the URL > i.e. ".../dashboard/latest\_release/launch\_status?build=3.5.9" you can > see the latest release information for that build. > > >
This might help you, can you see this [![fabric](https://i.stack.imgur.com/8MT0O.png)](https://i.stack.imgur.com/8MT0O.png)
6,529,505
I have a class that extends Activity and implements ViewFactory. I have found some tutorials and code examples that show how to setup a [textSwitcher](http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/TextSwitcher1.html) and [imageSwitcher](http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/ImageSwitcher1.html). With both examples you have to create: ``` public View makeView() { return x; } ``` Where x is either the textView or ImageView. Here is an example of what I tried to use: ``` @Override public View makeView() { ImageView iView = new ImageView(this); iView.setScaleType(ImageView.ScaleType.FIT_CENTER); iView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); iView.setBackgroundColor(0xFFFFFFFF); TextView t = new TextView(this); t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL); t.setTextSize(36); return iView; } ``` I can only return one of the views so I get a forced close when I try to run it with a textSwitcher called. Any ideas? Is there a better way to do this? Thank you, Neil
2011/06/30
[ "https://Stackoverflow.com/questions/6529505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/756623/" ]
As Stéphane stated before me, create an inner class implementing ViewFactory ``` public class TextSwitcherFactory implements ViewFactory { @Override public View makeView() { TextView t = new TextView(Latest.this); t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL); t.setTextSize(36); return t; } } ``` Then when calling the TextSwitcher from xml and setting the factory, instead of `mSwitcher.setFactory(this);`, use `mSwitcher.setFactory(new TextSwitcherFactory());` e.g. ``` mSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher1); mSwitcher.setFactory(new TextSwitcherFactory()); ```
You can't have the same object used as a `ViewFactory` and use it as two different factories for two different components. I never tried it, but it here is some solution from a OO perspective : * create two inner classes inside your activity * both of them will implement `ViewFactory`, * assign an instance of each inner class as the `ViewFactory` for your 2 components * make their `makeView` method provide the needed `View` for each component This should work, Stéphane
194,987
You are given a matrix of forward and back slashes, for instance: ``` //\\ \//\ //\/ ``` A slash cuts along the diagonal of its cell corner-to-corner, splitting it in two pieces. Pieces from adjacent (horizontally or vertically) cells are glued together. Your task is to count the number of resulting pieces. For the same example, the pieces are easier to see in this illustration - 8 of them: [![enter image description here](https://i.stack.imgur.com/XKYpq.png)](https://i.stack.imgur.com/XKYpq.png) Write a function or a complete program. Input is a non-empty matrix in any convenient form. You may choose any pair of values (characters or numbers) to represent `/` and `\`; in the tests below we use 0=`/` and 1=`\`. Loopholes forbidden. Shortest wins. ``` in: [[0,0,1,1], [1,0,0,1], [0,0,1,0]] out: 8 in: [[1]] out: 2 in: [[1,0], [1,1], [0,1], [0,0]] out: 6 in: [[1,0,1,1,0,1,0,0,0,1,1,1], [1,0,1,0,1,1,1,1,1,1,1,0], [1,1,1,0,1,1,0,1,1,1,1,0], [0,1,0,1,0,1,0,0,1,0,1,1], [1,1,1,1,0,0,1,1,1,0,0,1]] out: 19 in: [[1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1], [1,1,1,1,1,1,0,1,1,1,0,1,1,0,1,1,1], [1,0,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1], [1,0,0,1,1,1,0,0,1,0,0,1,0,1,1,1,1], [0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,1], [0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0], [0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,1,0]] out: 27 in: [[0,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0], [1,1,1,0,0,0,1,1,1,1,1,0,1,1,0,1,0], [1,0,0,1,1,1,0,0,0,1,0,1,0,0,1,1,1], [0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,0], [1,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,0], [0,1,0,1,0,0,0,1,0,1,0,1,0,1,1,0,0], [0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,1,1]] out: 32 ```
2019/10/28
[ "https://codegolf.stackexchange.com/questions/194987", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24908/" ]
[MATL](https://github.com/lmendo/MATL), 21 bytes ================================================ ``` 3XytPJ*-X*Xj~4&1ZIunq ``` The input is a matrix with `1` for `\` and `j` (imaginary unit) for `/`. [Try it online!](https://tio.run/##y00syfn/3ziisiTAS0s3Qisiq85EzTDKszSv8P//6CydLB1DHUNrBUMdMNNaASKSFQsA) Or [verify all test cases](https://tio.run/##dVE9C8IwEN39FZ0cyjkcunV10cnBoVgKuj5UEOrg4l@PttfkcklKKYTc@8h797gNd3d12/YznI71pq1bfHdrvhzez5fbn10HAjFxUzFNx6aSG/SrjsefMM6mexnK5UgSIM0SXsQP9RMFillhAFIOlO0ZrOpyWnZXISXHdsY85C2ZpxCOxgbknw@jtQDhAiwqgRMjA/mnzko1OMQlg5Dlh9@DjZR5yf5LBcNuE4VSgmK817Tm2VpTZ0n80/sf). With some extra code, you can [see the different pieces in random colours](https://matl.suever.net/?code=3XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0). Or [increase the resolution for a better looking result](https://matl.suever.net/?code=10XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0). Explanation ----------- Consider input `[1,j; 1,1; j,1; j,j]` as an example. This corresponds to ``` \/ \\ /\ // ``` `3Xy` creates a 3×3 identity matrix: ``` 1 0 0 0 1 0 0 0 1 ``` `tP` pushes a copy of this matrix and flips it vertically. `J*` multiplies each entry by the imaginary unit, to give ``` 0 0 j 0 j 0 j 0 0 ``` `-` subtracts the two matrices: ``` 1 0 -j 0 1-j 0 -j 0 1 ``` `X*` takes the input matrix implicitly and computes the Kronecker product. This replaces each entry in the input matrix by its product with the above 3×3 matrix: ``` 1 0 -j j 0 1 0 1-j 0 0 1+j 0 -j 0 1 1 0 j 1 0 -j 1 0 -j 0 1-j 0 0 1-j 0 -j 0 1 -j 0 1 j 0 1 1 0 -j 0 1+j 0 0 1-j 0 1 0 j -j 0 1 j 0 1 j 0 1 0 1+j 0 0 1+j 0 1 0 j 1 0 j ``` `Xj` takes the real part: ``` 1 0 0 0 0 1 0 1 0 0 1 0 0 0 1 1 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 1 1 0 0 0 1 0 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 ``` Note how the above matrix is a "pixelated" version of ``` \/ \\ /\ // ``` `~` applies logical negation, that is, swaps `0` and `1`: ``` 0 1 1 1 1 0 1 0 1 1 0 1 1 1 0 0 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 1 1 1 0 1 1 0 1 0 1 1 1 1 0 1 1 0 1 1 0 1 0 1 1 0 1 0 1 1 0 1 1 ``` `4&1ZI` specifies `4`-connectivity, and finds connected components considering `1` as foreground and `0` as background. The result is a matrix of labelled connected components, where each original `1` is replaced by an integer label: ``` 0 3 3 3 3 0 1 0 3 3 0 5 1 1 0 0 5 5 0 1 1 0 5 5 2 0 1 1 0 5 2 2 0 1 1 0 2 2 0 0 1 1 2 0 4 4 0 1 0 4 4 4 4 0 4 4 0 4 4 0 4 0 4 4 0 6 0 4 4 0 6 6 ``` `unq` computes the number of unique elements and subtracts `1`. This gives the number of components, which is implicitly displayed.
[Charcoal](https://github.com/somebody1234/Charcoal), 70 bytes ============================================================== ``` ≔׳Lθη≔׳L§θ⁰ζBζηψFLθ«J¹⊕׳ιF§θι«¿κP\²P/²M³→»»Fη«J⁰ιFζ«⊞υ¬℅KK¤#→»»⎚IΣυ ``` [Try it online!](https://tio.run/##dY5PT8JAFMTP7ad4wctrssZWb3BCEhOMaKPcag9Nu3Q3bLewfwjW8Nlrlw0pHDzOmzfzm5IVqmwL0fdzrXktcc0bqvGJwBuVtWG4jyICLJqF//hzs5QVPeKeQBy53274fW6P2A0xAj@D2rQKcKyD3zB4tc1u3WJCYClLRRsqDa3Gbj40zcLgHLwCcB8O@AZwG8HKCsN3ikuD028Cjy4SUKHpjfNwcVbtgbry6SevmXGnU3jy49j1qNiBLvTOE1OrGVoC763BD1VxWQhMKd1i5JcGL1wInNxNRtItZiFooXBQ6XnVotAGv2yD1uX7PsuymMQkIUlOQoAsIWfphXfiPM/7@4P4Aw "Charcoal – Try It Online") Link is to verbose version of code. Uses the same format as the examples (except Charcoal requires the list of inputs as an outer array). Explanation: ``` ≔׳Lθη≔׳L§θ⁰ζ ``` Like @LuisMendo, we're going to be drawing the matrix at 3x scale, so calculate that in advance. ``` Bζηψ ``` Draw an empty rectangle of that size so that we can fill the edge pieces. ``` FLθ«J¹⊕׳ιF§θι« ``` Loop over the rows and columns. ``` ¿κP\²P/²M³→»» ``` Draw each slash at triple size and move to the next one. ``` Fη«J⁰ιFζ« ``` Loop over all of the squares. ``` ⊞υ¬℅KK ``` Record whether this square was empty. ``` ¤#→»» ``` But try filling it anyway before moving on to the next square. (`Fill` does nothing if the current square is not empty.) ``` ⎚IΣυ ``` Clear the canvas and output the total number of empty squares found, which equals the number of pieces (because each piece would have been immediately filled in as soon as we counted it).
194,987
You are given a matrix of forward and back slashes, for instance: ``` //\\ \//\ //\/ ``` A slash cuts along the diagonal of its cell corner-to-corner, splitting it in two pieces. Pieces from adjacent (horizontally or vertically) cells are glued together. Your task is to count the number of resulting pieces. For the same example, the pieces are easier to see in this illustration - 8 of them: [![enter image description here](https://i.stack.imgur.com/XKYpq.png)](https://i.stack.imgur.com/XKYpq.png) Write a function or a complete program. Input is a non-empty matrix in any convenient form. You may choose any pair of values (characters or numbers) to represent `/` and `\`; in the tests below we use 0=`/` and 1=`\`. Loopholes forbidden. Shortest wins. ``` in: [[0,0,1,1], [1,0,0,1], [0,0,1,0]] out: 8 in: [[1]] out: 2 in: [[1,0], [1,1], [0,1], [0,0]] out: 6 in: [[1,0,1,1,0,1,0,0,0,1,1,1], [1,0,1,0,1,1,1,1,1,1,1,0], [1,1,1,0,1,1,0,1,1,1,1,0], [0,1,0,1,0,1,0,0,1,0,1,1], [1,1,1,1,0,0,1,1,1,0,0,1]] out: 19 in: [[1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1], [1,1,1,1,1,1,0,1,1,1,0,1,1,0,1,1,1], [1,0,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1], [1,0,0,1,1,1,0,0,1,0,0,1,0,1,1,1,1], [0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,1], [0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0], [0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,1,0]] out: 27 in: [[0,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0], [1,1,1,0,0,0,1,1,1,1,1,0,1,1,0,1,0], [1,0,0,1,1,1,0,0,0,1,0,1,0,0,1,1,1], [0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,0], [1,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,0], [0,1,0,1,0,0,0,1,0,1,0,1,0,1,1,0,0], [0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,1,1]] out: 32 ```
2019/10/28
[ "https://codegolf.stackexchange.com/questions/194987", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24908/" ]
[MATL](https://github.com/lmendo/MATL), 21 bytes ================================================ ``` 3XytPJ*-X*Xj~4&1ZIunq ``` The input is a matrix with `1` for `\` and `j` (imaginary unit) for `/`. [Try it online!](https://tio.run/##y00syfn/3ziisiTAS0s3Qisiq85EzTDKszSv8P//6CydLB1DHUNrBUMdMNNaASKSFQsA) Or [verify all test cases](https://tio.run/##dVE9C8IwEN39FZ0cyjkcunV10cnBoVgKuj5UEOrg4l@PttfkcklKKYTc@8h797gNd3d12/YznI71pq1bfHdrvhzez5fbn10HAjFxUzFNx6aSG/SrjsefMM6mexnK5UgSIM0SXsQP9RMFillhAFIOlO0ZrOpyWnZXISXHdsY85C2ZpxCOxgbknw@jtQDhAiwqgRMjA/mnzko1OMQlg5Dlh9@DjZR5yf5LBcNuE4VSgmK817Tm2VpTZ0n80/sf). With some extra code, you can [see the different pieces in random colours](https://matl.suever.net/?code=3XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0). Or [increase the resolution for a better looking result](https://matl.suever.net/?code=10XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0). Explanation ----------- Consider input `[1,j; 1,1; j,1; j,j]` as an example. This corresponds to ``` \/ \\ /\ // ``` `3Xy` creates a 3×3 identity matrix: ``` 1 0 0 0 1 0 0 0 1 ``` `tP` pushes a copy of this matrix and flips it vertically. `J*` multiplies each entry by the imaginary unit, to give ``` 0 0 j 0 j 0 j 0 0 ``` `-` subtracts the two matrices: ``` 1 0 -j 0 1-j 0 -j 0 1 ``` `X*` takes the input matrix implicitly and computes the Kronecker product. This replaces each entry in the input matrix by its product with the above 3×3 matrix: ``` 1 0 -j j 0 1 0 1-j 0 0 1+j 0 -j 0 1 1 0 j 1 0 -j 1 0 -j 0 1-j 0 0 1-j 0 -j 0 1 -j 0 1 j 0 1 1 0 -j 0 1+j 0 0 1-j 0 1 0 j -j 0 1 j 0 1 j 0 1 0 1+j 0 0 1+j 0 1 0 j 1 0 j ``` `Xj` takes the real part: ``` 1 0 0 0 0 1 0 1 0 0 1 0 0 0 1 1 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 1 1 0 0 0 1 0 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 ``` Note how the above matrix is a "pixelated" version of ``` \/ \\ /\ // ``` `~` applies logical negation, that is, swaps `0` and `1`: ``` 0 1 1 1 1 0 1 0 1 1 0 1 1 1 0 0 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 1 1 1 0 1 1 0 1 0 1 1 1 1 0 1 1 0 1 1 0 1 0 1 1 0 1 0 1 1 0 1 1 ``` `4&1ZI` specifies `4`-connectivity, and finds connected components considering `1` as foreground and `0` as background. The result is a matrix of labelled connected components, where each original `1` is replaced by an integer label: ``` 0 3 3 3 3 0 1 0 3 3 0 5 1 1 0 0 5 5 0 1 1 0 5 5 2 0 1 1 0 5 2 2 0 1 1 0 2 2 0 0 1 1 2 0 4 4 0 1 0 4 4 4 4 0 4 4 0 4 4 0 4 0 4 4 0 6 0 4 4 0 6 6 ``` `unq` computes the number of unique elements and subtracts `1`. This gives the number of components, which is implicitly displayed.
[C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 292 bytes ================================================================================================================= ```cs n=>{var x=n.SelectMany(l=>"\0".Select(g=>l.SelectMany(r=>r.Skip(g).Concat(r.Take(g))).ToList())).ToList();int i=0,j=0,t=0;for(;i<x.Count;i++)for(j=0;j<x[0].Count;k(i,j++))t+=x[i][j]%2;void k(int a,int b){try{if(x[a][b]<50){x[a][b]='2';k(a+1,b);k(a-1,b);k(a,b-1);k(a,b+1);}}catch{}}return t;} ``` The `\0` should be a literal null byte. `112` for `/`, `211` for `\` [Try it online!](https://tio.run/##ZZBBS8QwEIXRo7@iFGQTmi1twVOaXERBUBB2b7WHtKY13ZpKmq5dSn57Tdmoq3vI8DHv5Q0zZb8uezHfD7JMH@7k8M4VK1r@h3uthKwpRUJqWpFZEjrtmfJGIsMNb3mpn5g8gJZQ/yW6uPRdE9SEtqcGRagKNzvxAWoY3nayZBqocMt23DYgDLfdo@g1OEVsR3qCRKixT5MIV50CWKSj/T9IjUUQwKVlZdykYxblTtgBgRorQh2QMRN51uTXCd534tWzkg1lyzZeASetDpOowJixPCvy9CaCk2OySlY2iAUxKuAC629AxTp2EFgwxq5Svk3GKK4HJT2NzYyvnu3ZNKiA5J9ZPh2rH8eJj1xN4thV87Mxcr6j9t997jvPW/jXZ07Oiucv "C# (Visual C# Interactive Compiler) – Try It Online")
194,987
You are given a matrix of forward and back slashes, for instance: ``` //\\ \//\ //\/ ``` A slash cuts along the diagonal of its cell corner-to-corner, splitting it in two pieces. Pieces from adjacent (horizontally or vertically) cells are glued together. Your task is to count the number of resulting pieces. For the same example, the pieces are easier to see in this illustration - 8 of them: [![enter image description here](https://i.stack.imgur.com/XKYpq.png)](https://i.stack.imgur.com/XKYpq.png) Write a function or a complete program. Input is a non-empty matrix in any convenient form. You may choose any pair of values (characters or numbers) to represent `/` and `\`; in the tests below we use 0=`/` and 1=`\`. Loopholes forbidden. Shortest wins. ``` in: [[0,0,1,1], [1,0,0,1], [0,0,1,0]] out: 8 in: [[1]] out: 2 in: [[1,0], [1,1], [0,1], [0,0]] out: 6 in: [[1,0,1,1,0,1,0,0,0,1,1,1], [1,0,1,0,1,1,1,1,1,1,1,0], [1,1,1,0,1,1,0,1,1,1,1,0], [0,1,0,1,0,1,0,0,1,0,1,1], [1,1,1,1,0,0,1,1,1,0,0,1]] out: 19 in: [[1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1], [1,1,1,1,1,1,0,1,1,1,0,1,1,0,1,1,1], [1,0,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1], [1,0,0,1,1,1,0,0,1,0,0,1,0,1,1,1,1], [0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,1], [0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0], [0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,1,0]] out: 27 in: [[0,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0], [1,1,1,0,0,0,1,1,1,1,1,0,1,1,0,1,0], [1,0,0,1,1,1,0,0,0,1,0,1,0,0,1,1,1], [0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,0], [1,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,0], [0,1,0,1,0,0,0,1,0,1,0,1,0,1,1,0,0], [0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,1,1]] out: 32 ```
2019/10/28
[ "https://codegolf.stackexchange.com/questions/194987", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24908/" ]
[MATL](https://github.com/lmendo/MATL), 21 bytes ================================================ ``` 3XytPJ*-X*Xj~4&1ZIunq ``` The input is a matrix with `1` for `\` and `j` (imaginary unit) for `/`. [Try it online!](https://tio.run/##y00syfn/3ziisiTAS0s3Qisiq85EzTDKszSv8P//6CydLB1DHUNrBUMdMNNaASKSFQsA) Or [verify all test cases](https://tio.run/##dVE9C8IwEN39FZ0cyjkcunV10cnBoVgKuj5UEOrg4l@PttfkcklKKYTc@8h797gNd3d12/YznI71pq1bfHdrvhzez5fbn10HAjFxUzFNx6aSG/SrjsefMM6mexnK5UgSIM0SXsQP9RMFillhAFIOlO0ZrOpyWnZXISXHdsY85C2ZpxCOxgbknw@jtQDhAiwqgRMjA/mnzko1OMQlg5Dlh9@DjZR5yf5LBcNuE4VSgmK817Tm2VpTZ0n80/sf). With some extra code, you can [see the different pieces in random colours](https://matl.suever.net/?code=3XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0). Or [increase the resolution for a better looking result](https://matl.suever.net/?code=10XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0). Explanation ----------- Consider input `[1,j; 1,1; j,1; j,j]` as an example. This corresponds to ``` \/ \\ /\ // ``` `3Xy` creates a 3×3 identity matrix: ``` 1 0 0 0 1 0 0 0 1 ``` `tP` pushes a copy of this matrix and flips it vertically. `J*` multiplies each entry by the imaginary unit, to give ``` 0 0 j 0 j 0 j 0 0 ``` `-` subtracts the two matrices: ``` 1 0 -j 0 1-j 0 -j 0 1 ``` `X*` takes the input matrix implicitly and computes the Kronecker product. This replaces each entry in the input matrix by its product with the above 3×3 matrix: ``` 1 0 -j j 0 1 0 1-j 0 0 1+j 0 -j 0 1 1 0 j 1 0 -j 1 0 -j 0 1-j 0 0 1-j 0 -j 0 1 -j 0 1 j 0 1 1 0 -j 0 1+j 0 0 1-j 0 1 0 j -j 0 1 j 0 1 j 0 1 0 1+j 0 0 1+j 0 1 0 j 1 0 j ``` `Xj` takes the real part: ``` 1 0 0 0 0 1 0 1 0 0 1 0 0 0 1 1 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 1 1 0 0 0 1 0 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 ``` Note how the above matrix is a "pixelated" version of ``` \/ \\ /\ // ``` `~` applies logical negation, that is, swaps `0` and `1`: ``` 0 1 1 1 1 0 1 0 1 1 0 1 1 1 0 0 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 1 1 1 0 1 1 0 1 0 1 1 1 1 0 1 1 0 1 1 0 1 0 1 1 0 1 0 1 1 0 1 1 ``` `4&1ZI` specifies `4`-connectivity, and finds connected components considering `1` as foreground and `0` as background. The result is a matrix of labelled connected components, where each original `1` is replaced by an integer label: ``` 0 3 3 3 3 0 1 0 3 3 0 5 1 1 0 0 5 5 0 1 1 0 5 5 2 0 1 1 0 5 2 2 0 1 1 0 2 2 0 0 1 1 2 0 4 4 0 1 0 4 4 4 4 0 4 4 0 4 4 0 4 0 4 4 0 6 0 4 4 0 6 6 ``` `unq` computes the number of unique elements and subtracts `1`. This gives the number of components, which is implicitly displayed.
JavaScript (ES6), ~~175~~ 174 bytes =================================== This is probably overcomplicated. ```javascript a=>a.map((r,y)=>r.map((v,x)=>[2,4].map(s=>v&s||(n++,g=(x,y,s,i,v=(r=a[y])&&r[x])=>!(v&(s^=i%2==v%2&&6))/v&&g(x+1-(r[x]|=s,s&2),y++,s^6)|g(x,y-=v%2*2^s&2,s,v))(x,y,s))),n=0)|n ``` [Try it online!](https://tio.run/##fZLvaoMwFMW/@xTuQ0Oy3rY32eg2RvoiYkG6VhydFjOCgu/u/NcmUSeCcM25v3s8N9@RjtQpT26/mzT7OtcXWUfyEG1/ohulOZRMHvK@0FA0RSDgNew@KHnQRFUVTddriCUtoAQFCWhJcxkFZcgIyYMibJqeqCZUHWWyElLqlSBkz9hOExLTYs03tJVVUoEigkHZ4NRxz6q4RW5a/bM4NkcNXTPWz2GMQSqRVWl9ylKVXc/baxbTCw383c5/93w/QEDgwENoCw5d2Rf9CYZeyNin580ARNezINgP0Dv9QTYjFrr5x90Th/6NMNi1Dd8F5jHzwO52DhFMLxqK3cnNtCGXhSjeFryaUS7eNubYdLYxZ3NOxi2JI7R/GB3mgozPSEfx8dFQV/Z/Vi9iTJhScLxEBJykhvau3RAmjsydnlsRTm8OzsT5II/v0HhRgw03q8kfPpLvsqr/AA "JavaScript (Node.js) – Try It Online")
194,987
You are given a matrix of forward and back slashes, for instance: ``` //\\ \//\ //\/ ``` A slash cuts along the diagonal of its cell corner-to-corner, splitting it in two pieces. Pieces from adjacent (horizontally or vertically) cells are glued together. Your task is to count the number of resulting pieces. For the same example, the pieces are easier to see in this illustration - 8 of them: [![enter image description here](https://i.stack.imgur.com/XKYpq.png)](https://i.stack.imgur.com/XKYpq.png) Write a function or a complete program. Input is a non-empty matrix in any convenient form. You may choose any pair of values (characters or numbers) to represent `/` and `\`; in the tests below we use 0=`/` and 1=`\`. Loopholes forbidden. Shortest wins. ``` in: [[0,0,1,1], [1,0,0,1], [0,0,1,0]] out: 8 in: [[1]] out: 2 in: [[1,0], [1,1], [0,1], [0,0]] out: 6 in: [[1,0,1,1,0,1,0,0,0,1,1,1], [1,0,1,0,1,1,1,1,1,1,1,0], [1,1,1,0,1,1,0,1,1,1,1,0], [0,1,0,1,0,1,0,0,1,0,1,1], [1,1,1,1,0,0,1,1,1,0,0,1]] out: 19 in: [[1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1], [1,1,1,1,1,1,0,1,1,1,0,1,1,0,1,1,1], [1,0,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1], [1,0,0,1,1,1,0,0,1,0,0,1,0,1,1,1,1], [0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,1], [0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0], [0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,1,0]] out: 27 in: [[0,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0], [1,1,1,0,0,0,1,1,1,1,1,0,1,1,0,1,0], [1,0,0,1,1,1,0,0,0,1,0,1,0,0,1,1,1], [0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,0], [1,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,0], [0,1,0,1,0,0,0,1,0,1,0,1,0,1,1,0,0], [0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,1,1]] out: 32 ```
2019/10/28
[ "https://codegolf.stackexchange.com/questions/194987", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24908/" ]
[MATL](https://github.com/lmendo/MATL), 21 bytes ================================================ ``` 3XytPJ*-X*Xj~4&1ZIunq ``` The input is a matrix with `1` for `\` and `j` (imaginary unit) for `/`. [Try it online!](https://tio.run/##y00syfn/3ziisiTAS0s3Qisiq85EzTDKszSv8P//6CydLB1DHUNrBUMdMNNaASKSFQsA) Or [verify all test cases](https://tio.run/##dVE9C8IwEN39FZ0cyjkcunV10cnBoVgKuj5UEOrg4l@PttfkcklKKYTc@8h797gNd3d12/YznI71pq1bfHdrvhzez5fbn10HAjFxUzFNx6aSG/SrjsefMM6mexnK5UgSIM0SXsQP9RMFillhAFIOlO0ZrOpyWnZXISXHdsY85C2ZpxCOxgbknw@jtQDhAiwqgRMjA/mnzko1OMQlg5Dlh9@DjZR5yf5LBcNuE4VSgmK817Tm2VpTZ0n80/sf). With some extra code, you can [see the different pieces in random colours](https://matl.suever.net/?code=3XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0). Or [increase the resolution for a better looking result](https://matl.suever.net/?code=10XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0). Explanation ----------- Consider input `[1,j; 1,1; j,1; j,j]` as an example. This corresponds to ``` \/ \\ /\ // ``` `3Xy` creates a 3×3 identity matrix: ``` 1 0 0 0 1 0 0 0 1 ``` `tP` pushes a copy of this matrix and flips it vertically. `J*` multiplies each entry by the imaginary unit, to give ``` 0 0 j 0 j 0 j 0 0 ``` `-` subtracts the two matrices: ``` 1 0 -j 0 1-j 0 -j 0 1 ``` `X*` takes the input matrix implicitly and computes the Kronecker product. This replaces each entry in the input matrix by its product with the above 3×3 matrix: ``` 1 0 -j j 0 1 0 1-j 0 0 1+j 0 -j 0 1 1 0 j 1 0 -j 1 0 -j 0 1-j 0 0 1-j 0 -j 0 1 -j 0 1 j 0 1 1 0 -j 0 1+j 0 0 1-j 0 1 0 j -j 0 1 j 0 1 j 0 1 0 1+j 0 0 1+j 0 1 0 j 1 0 j ``` `Xj` takes the real part: ``` 1 0 0 0 0 1 0 1 0 0 1 0 0 0 1 1 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 1 1 0 0 0 1 0 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 ``` Note how the above matrix is a "pixelated" version of ``` \/ \\ /\ // ``` `~` applies logical negation, that is, swaps `0` and `1`: ``` 0 1 1 1 1 0 1 0 1 1 0 1 1 1 0 0 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 1 1 1 0 1 1 0 1 0 1 1 1 1 0 1 1 0 1 1 0 1 0 1 1 0 1 0 1 1 0 1 1 ``` `4&1ZI` specifies `4`-connectivity, and finds connected components considering `1` as foreground and `0` as background. The result is a matrix of labelled connected components, where each original `1` is replaced by an integer label: ``` 0 3 3 3 3 0 1 0 3 3 0 5 1 1 0 0 5 5 0 1 1 0 5 5 2 0 1 1 0 5 2 2 0 1 1 0 2 2 0 0 1 1 2 0 4 4 0 1 0 4 4 4 4 0 4 4 0 4 4 0 4 0 4 4 0 6 0 4 4 0 6 6 ``` `unq` computes the number of unique elements and subtracts `1`. This gives the number of components, which is implicitly displayed.
[Jelly](https://github.com/DennisMitchell/jelly), ~~50~~ 46 bytes ================================================================= ``` ®_ż+¥"SƝż€"Jż‘$$ḞṖ ZJḤ©Żż‘$;€þJ;ÇẎfƇ@Ẏ¥€`Q$ÐLL ``` [Try it online!](https://tio.run/##y0rNyan8///Quvije7QPLVUKPjb36J5HTWuUvIBUwwwVlYc75j3cOY0ryuvhjiWHVh7dDRG2Bio5vM/L@nD7w119acfaHYDUoaVAwYRAlcMTfHz@u1s/aphzaJuCrp3Co4a5QHVcQP2PGmZ6PNyx2ORwO1Bl1qPGfYe2Hdr2/380V3S0gY6BjqGOYawOl0K0oQ6YB2ZDxA1igZzoaEMoBeRD1MHUwNXCFYAMg2jVgRqNZDhMHgHhBuog60WWM9BB6DRAmIGkzxBhE9QD@ByDMA7FCGSrURyCHDLYHIJFlSGSChR1SB4yQDERtypDLCpRA8cQzUZUVeCgwAh1FKUGaLFgoGOAESgGSHGF6kkMS@HJB1vwG2DEuwGWwIKbi5YC0CMB6gaUoMDwGzxYY7liAQ "Jelly – Try It Online") A full program taking a matrix as its input with `-0.5` as `/` and `0.5` as `\`. Returns an integer with the number of pieces. Full explanation to follow, but works by generating a list of all the pairs of connected cells, and then merging overlapping sets until there’s no change. The final number of sets is the desired answer.
194,987
You are given a matrix of forward and back slashes, for instance: ``` //\\ \//\ //\/ ``` A slash cuts along the diagonal of its cell corner-to-corner, splitting it in two pieces. Pieces from adjacent (horizontally or vertically) cells are glued together. Your task is to count the number of resulting pieces. For the same example, the pieces are easier to see in this illustration - 8 of them: [![enter image description here](https://i.stack.imgur.com/XKYpq.png)](https://i.stack.imgur.com/XKYpq.png) Write a function or a complete program. Input is a non-empty matrix in any convenient form. You may choose any pair of values (characters or numbers) to represent `/` and `\`; in the tests below we use 0=`/` and 1=`\`. Loopholes forbidden. Shortest wins. ``` in: [[0,0,1,1], [1,0,0,1], [0,0,1,0]] out: 8 in: [[1]] out: 2 in: [[1,0], [1,1], [0,1], [0,0]] out: 6 in: [[1,0,1,1,0,1,0,0,0,1,1,1], [1,0,1,0,1,1,1,1,1,1,1,0], [1,1,1,0,1,1,0,1,1,1,1,0], [0,1,0,1,0,1,0,0,1,0,1,1], [1,1,1,1,0,0,1,1,1,0,0,1]] out: 19 in: [[1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1], [1,1,1,1,1,1,0,1,1,1,0,1,1,0,1,1,1], [1,0,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1], [1,0,0,1,1,1,0,0,1,0,0,1,0,1,1,1,1], [0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,1], [0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0], [0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,1,0]] out: 27 in: [[0,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0], [1,1,1,0,0,0,1,1,1,1,1,0,1,1,0,1,0], [1,0,0,1,1,1,0,0,0,1,0,1,0,0,1,1,1], [0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,0], [1,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,0], [0,1,0,1,0,0,0,1,0,1,0,1,0,1,1,0,0], [0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,1,1]] out: 32 ```
2019/10/28
[ "https://codegolf.stackexchange.com/questions/194987", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/24908/" ]
[MATL](https://github.com/lmendo/MATL), 21 bytes ================================================ ``` 3XytPJ*-X*Xj~4&1ZIunq ``` The input is a matrix with `1` for `\` and `j` (imaginary unit) for `/`. [Try it online!](https://tio.run/##y00syfn/3ziisiTAS0s3Qisiq85EzTDKszSv8P//6CydLB1DHUNrBUMdMNNaASKSFQsA) Or [verify all test cases](https://tio.run/##dVE9C8IwEN39FZ0cyjkcunV10cnBoVgKuj5UEOrg4l@PttfkcklKKYTc@8h797gNd3d12/YznI71pq1bfHdrvhzez5fbn10HAjFxUzFNx6aSG/SrjsefMM6mexnK5UgSIM0SXsQP9RMFillhAFIOlO0ZrOpyWnZXISXHdsY85C2ZpxCOxgbknw@jtQDhAiwqgRMjA/mnzko1OMQlg5Dlh9@DjZR5yf5LBcNuE4VSgmK817Tm2VpTZ0n80/sf). With some extra code, you can [see the different pieces in random colours](https://matl.suever.net/?code=3XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0). Or [increase the resolution for a better looking result](https://matl.suever.net/?code=10XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0). Explanation ----------- Consider input `[1,j; 1,1; j,1; j,j]` as an example. This corresponds to ``` \/ \\ /\ // ``` `3Xy` creates a 3×3 identity matrix: ``` 1 0 0 0 1 0 0 0 1 ``` `tP` pushes a copy of this matrix and flips it vertically. `J*` multiplies each entry by the imaginary unit, to give ``` 0 0 j 0 j 0 j 0 0 ``` `-` subtracts the two matrices: ``` 1 0 -j 0 1-j 0 -j 0 1 ``` `X*` takes the input matrix implicitly and computes the Kronecker product. This replaces each entry in the input matrix by its product with the above 3×3 matrix: ``` 1 0 -j j 0 1 0 1-j 0 0 1+j 0 -j 0 1 1 0 j 1 0 -j 1 0 -j 0 1-j 0 0 1-j 0 -j 0 1 -j 0 1 j 0 1 1 0 -j 0 1+j 0 0 1-j 0 1 0 j -j 0 1 j 0 1 j 0 1 0 1+j 0 0 1+j 0 1 0 j 1 0 j ``` `Xj` takes the real part: ``` 1 0 0 0 0 1 0 1 0 0 1 0 0 0 1 1 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 1 1 0 0 0 1 0 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 ``` Note how the above matrix is a "pixelated" version of ``` \/ \\ /\ // ``` `~` applies logical negation, that is, swaps `0` and `1`: ``` 0 1 1 1 1 0 1 0 1 1 0 1 1 1 0 0 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 1 0 0 1 1 1 0 1 1 0 1 0 1 1 1 1 0 1 1 0 1 1 0 1 0 1 1 0 1 0 1 1 0 1 1 ``` `4&1ZI` specifies `4`-connectivity, and finds connected components considering `1` as foreground and `0` as background. The result is a matrix of labelled connected components, where each original `1` is replaced by an integer label: ``` 0 3 3 3 3 0 1 0 3 3 0 5 1 1 0 0 5 5 0 1 1 0 5 5 2 0 1 1 0 5 2 2 0 1 1 0 2 2 0 0 1 1 2 0 4 4 0 1 0 4 4 4 4 0 4 4 0 4 4 0 4 0 4 4 0 6 0 4 4 0 6 6 ``` `unq` computes the number of unique elements and subtracts `1`. This gives the number of components, which is implicitly displayed.
MSX-BASIC, ~~226~~ 199 bytes ============================ ``` 1SCREEN2:READC,L:W=256/C:H=192/L:FORJ=1TOL:FORI=1TOC:A=H:B=H:READD:IFDTHENA=0:B=-H 2LINE(I*W,J*H-A)-STEP(-W,B):NEXTI,J:FORY=0TO191:FORX=0TO255:IFPOINT(X,Y)=4THENR=R+1:PAINT(X,Y) 3NEXTX,Y:SCREEN0:?R ``` This script draw slashes on a whole screen and use PAINT operator to count closed areas. [![The MSX-BASIC script in process](https://i.stack.imgur.com/RLYso.png)](https://i.stack.imgur.com/RLYso.png) [![Result](https://i.stack.imgur.com/jmlri.png)](https://i.stack.imgur.com/jmlri.png) To test: * copy to clipboard the script with test cases data (see below) * open online emulator <https://webmsx.org/> * press `Alt-V` and `Ctrl+V` to past test script into MSX * press `Enter` and `F5` to run test script * wait a some time to see a result (press `Shift-Alt-T` to switch in `CPU Turbo 8X` mode to save your time) ``` 1SCREEN2:READC,L:W=256/C:H=192/L:FORJ=1TOL:FORI=1TOC:A=H:B=H:READD:IFDTHENA=0:B=-H 2LINE(I*W,J*H-A)-STEP(-W,B):NEXTI,J:FORY=0TO191:FORX=0TO255:IFPOINT(X,Y)=4THENR=R+1:PAINT(X,Y) 3NEXTX,Y:SCREEN0:?R 10 ' this and below lines are not counted 20 ' the script runs first uncommented test case. 30 ' comment unnecessary test cases 100 ' 110 'test case 1: expected output=8 120 'DATA 4,3 130 'DATA 0,0,1,1,1,0,0,1,0,0,1,0 200 ' 210 'test case 2: expected output=2 220 'DATA 1,1 230 'DATA 1 300 ' 310 'test case 3: expected output=6 320 'DATA 2,4 330 'DATA 1,0,1,1,0,1,0,0 400 ' 410 'test case 4: expected output=19 420 'DATA 12,5 430 'DATA 1,0,1,1,0,1,0,0,0,1,1,1 440 'DATA 1,0,1,0,1,1,1,1,1,1,1,0 450 'DATA 1,1,1,0,1,1,0,1,1,1,1,0 460 'DATA 0,1,0,1,0,1,0,0,1,0,1,1 470 'DATA 1,1,1,1,0,0,1,1,1,0,0,1 500 ' 510 'test case 5: expected output=27 520 DATA 17,7 530 DATA 1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1 540 DATA 1,1,1,1,1,1,0,1,1,1,0,1,1,0,1,1,1 550 DATA 1,0,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1 560 DATA 1,0,0,1,1,1,0,0,1,0,0,1,0,1,1,1,1 570 DATA 0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,1 580 DATA 0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0 590 DATA 0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,1,0 600 ' 610 'test case 5: expected output=32 620 DATA 17, 7 630 DATA 0,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0 640 DATA 1,1,1,0,0,0,1,1,1,1,1,0,1,1,0,1,0 650 DATA 1,0,0,1,1,1,0,0,0,1,0,1,0,0,1,1,1 660 DATA 0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,0 670 DATA 1,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,0 680 DATA 0,1,0,1,0,0,0,1,0,1,0,1,0,1,1,0,0 690 DATA 0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,1,1 ```
9,329,114
Does anyone know of a 'pluck' plugin that matches the underscore array method? ``` pluck_.pluck(list, propertyName) ``` A convenient version of what is perhaps the most common use-case for map: extracting a list of property values. ``` var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; _.pluck(stooges, 'name'); => ["moe", "larry", "curly"] ``` Google is not helping me much today. Any pointers much appreciated
2012/02/17
[ "https://Stackoverflow.com/questions/9329114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135687/" ]
You can do it with an expression; ``` var arr = $.map(stooges, function(o) { return o["name"]; }) ```
It's quite simple to implement this functionality yourself: ``` function pluck(originalArr, prop) { var newArr = []; for(var i = 0; i < originalArr.length; i++) { newArr[i] = originalArr[i][prop]; } return newArr; } ``` All it does is iterate over the elements of the original array (each of which is an object), get the property you specify from that object, and place it in a new array.
9,329,114
Does anyone know of a 'pluck' plugin that matches the underscore array method? ``` pluck_.pluck(list, propertyName) ``` A convenient version of what is perhaps the most common use-case for map: extracting a list of property values. ``` var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; _.pluck(stooges, 'name'); => ["moe", "larry", "curly"] ``` Google is not helping me much today. Any pointers much appreciated
2012/02/17
[ "https://Stackoverflow.com/questions/9329114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135687/" ]
just write your own ``` $.pluck = function(arr, key) { return $.map(arr, function(e) { return e[key]; }) } ```
It's quite simple to implement this functionality yourself: ``` function pluck(originalArr, prop) { var newArr = []; for(var i = 0; i < originalArr.length; i++) { newArr[i] = originalArr[i][prop]; } return newArr; } ``` All it does is iterate over the elements of the original array (each of which is an object), get the property you specify from that object, and place it in a new array.
9,329,114
Does anyone know of a 'pluck' plugin that matches the underscore array method? ``` pluck_.pluck(list, propertyName) ``` A convenient version of what is perhaps the most common use-case for map: extracting a list of property values. ``` var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; _.pluck(stooges, 'name'); => ["moe", "larry", "curly"] ``` Google is not helping me much today. Any pointers much appreciated
2012/02/17
[ "https://Stackoverflow.com/questions/9329114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135687/" ]
It's quite simple to implement this functionality yourself: ``` function pluck(originalArr, prop) { var newArr = []; for(var i = 0; i < originalArr.length; i++) { newArr[i] = originalArr[i][prop]; } return newArr; } ``` All it does is iterate over the elements of the original array (each of which is an object), get the property you specify from that object, and place it in a new array.
In simple case: ``` var arr = stooges.map(function(v) { return v.name; }); ``` More generalized: ``` function pluck(list, propertyName) { return list.map(function (v) { return v[propertyName]; }) } ``` But, IMHO, you should not implement it as tool function, but use the simple case *always*. 2018 update: ``` var arr = stooges.map(({ name }) => name); ```
9,329,114
Does anyone know of a 'pluck' plugin that matches the underscore array method? ``` pluck_.pluck(list, propertyName) ``` A convenient version of what is perhaps the most common use-case for map: extracting a list of property values. ``` var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; _.pluck(stooges, 'name'); => ["moe", "larry", "curly"] ``` Google is not helping me much today. Any pointers much appreciated
2012/02/17
[ "https://Stackoverflow.com/questions/9329114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135687/" ]
You can do it with an expression; ``` var arr = $.map(stooges, function(o) { return o["name"]; }) ```
just write your own ``` $.pluck = function(arr, key) { return $.map(arr, function(e) { return e[key]; }) } ```
9,329,114
Does anyone know of a 'pluck' plugin that matches the underscore array method? ``` pluck_.pluck(list, propertyName) ``` A convenient version of what is perhaps the most common use-case for map: extracting a list of property values. ``` var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; _.pluck(stooges, 'name'); => ["moe", "larry", "curly"] ``` Google is not helping me much today. Any pointers much appreciated
2012/02/17
[ "https://Stackoverflow.com/questions/9329114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135687/" ]
You can do it with an expression; ``` var arr = $.map(stooges, function(o) { return o["name"]; }) ```
In simple case: ``` var arr = stooges.map(function(v) { return v.name; }); ``` More generalized: ``` function pluck(list, propertyName) { return list.map(function (v) { return v[propertyName]; }) } ``` But, IMHO, you should not implement it as tool function, but use the simple case *always*. 2018 update: ``` var arr = stooges.map(({ name }) => name); ```
9,329,114
Does anyone know of a 'pluck' plugin that matches the underscore array method? ``` pluck_.pluck(list, propertyName) ``` A convenient version of what is perhaps the most common use-case for map: extracting a list of property values. ``` var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; _.pluck(stooges, 'name'); => ["moe", "larry", "curly"] ``` Google is not helping me much today. Any pointers much appreciated
2012/02/17
[ "https://Stackoverflow.com/questions/9329114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135687/" ]
just write your own ``` $.pluck = function(arr, key) { return $.map(arr, function(e) { return e[key]; }) } ```
In simple case: ``` var arr = stooges.map(function(v) { return v.name; }); ``` More generalized: ``` function pluck(list, propertyName) { return list.map(function (v) { return v[propertyName]; }) } ``` But, IMHO, you should not implement it as tool function, but use the simple case *always*. 2018 update: ``` var arr = stooges.map(({ name }) => name); ```
28,914
I have read Steven Pinker's Sense of Style, which is a great book. In chapter 4, he talks about how to form lucid coherent sentences, and in chapter 5, called "Arcs of Coherence", he extends his analysis of coherence to relations between sentences within a paragraph (and also somewhat about coherence between subsequent paragraphs). I think his analysis is truly brilliant, about how a text is not merely tree-like, because there are connections between sentences apart from the tree-like structure of chapter -> paragraph -> Sentence -> words. His analysis of how to make a paragraph coherent by connecting sentences in specific ways is truly very helpful. Also he has a brilliant analysis (more in chapter 4) of how lucid prose is created by taking into account the effect that the order of words has on the memory of the reader. However, he does not really extend this analysis to the level of chapters/pages. He does not really address the question of "how do we write entire chapters so as to make them coherent with each other". "How do we make connections between sentences in different sections/chapters, so as to make them coherent". **So my question is: For people who have read Steven Pinker's chapter on Arcs of Coherence and found it as useful as I did, do you know any other writers who have similar insights, but about how to connect elements of a larger text, to make the larger structure of the text more coherent?**
2017/06/26
[ "https://writers.stackexchange.com/questions/28914", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/24575/" ]
It seems to me that what Pinker is describing at the sentence and paragraph level is substantially what most books on story are describing at the level of a document as a whole. Stories have a coherent shape and that shape has been mapped in various ways by different authors, but broadly the same shape underlies what all or most of them describe. Coherence, the property of all the bits of a thing going together in a way that makes sense, is a fundamental property of writing at any scale. The ways in which coherence works, however, may be different at different scales. That is, how the pieces are connected and how long you have to connect the pieces up before you lose the reader may differ as you scale up or down. Some of the most prominent books on the shape of stories are: * *Story* by Robert McKee * *The Writer's Journey* by Christopher Vogler * *Aspects of the Novel* by EM Forster But there are many such works, covering both fiction and non fiction.
The misconception at the heart of your question is that there has to be coherence between chapters, similar to the coherence between paragraphs. In **technical and academic writing** there is indeed coherence, usually, and then *the same principles apply* for the transition from the last paragraph of the preceding chapter to the first paragraph of the current chapter as between two paragraphs within one chapter. In other words: The chapter break is nothing but a paragraph break, and you connect chapters in the same way that you connect paragraphs. In **fiction**, the break between chapters is often a break in time, place, person, viewpoint, or chronology as well. What happens at the beginning of the current chapter appears, at first, to be totally unrelated to what we have read at the end of the preceding chapter. Only as we continue reading do we gather more and more clues as to how what we read now relates to what we have read before. A paragraph *always* establishes a connection (signified by an arrow in the schema below) to the preceding paragraph by referring to the topic ("A") of the preceding paragraph before beginning its own ("B"): [![enter image description here](https://i.stack.imgur.com/kcUxn.png)](https://i.stack.imgur.com/kcUxn.png) A chapter, on the other hand, *can* begin with a topic completely unrelated to any of the topics of the preceding chapter(s) and connect to the preceding text at a later point: [![enter image description here](https://i.stack.imgur.com/p4Zys.png)](https://i.stack.imgur.com/p4Zys.png) In my schema, forward arrows signify a topic being *continued* in a following sentence or paragraph, while a backward arrow signifies a *backward reference*. In reality, of course, every continuation is also a backward reference, and all arrows should point both ways. I just found unidirectional forward arrows to be less confusing, as they correspond to the forward movement of the reader through the text – who might want to browse back to where "X" was mentioned at at first, when it comes up in the second chapter again.
28,914
I have read Steven Pinker's Sense of Style, which is a great book. In chapter 4, he talks about how to form lucid coherent sentences, and in chapter 5, called "Arcs of Coherence", he extends his analysis of coherence to relations between sentences within a paragraph (and also somewhat about coherence between subsequent paragraphs). I think his analysis is truly brilliant, about how a text is not merely tree-like, because there are connections between sentences apart from the tree-like structure of chapter -> paragraph -> Sentence -> words. His analysis of how to make a paragraph coherent by connecting sentences in specific ways is truly very helpful. Also he has a brilliant analysis (more in chapter 4) of how lucid prose is created by taking into account the effect that the order of words has on the memory of the reader. However, he does not really extend this analysis to the level of chapters/pages. He does not really address the question of "how do we write entire chapters so as to make them coherent with each other". "How do we make connections between sentences in different sections/chapters, so as to make them coherent". **So my question is: For people who have read Steven Pinker's chapter on Arcs of Coherence and found it as useful as I did, do you know any other writers who have similar insights, but about how to connect elements of a larger text, to make the larger structure of the text more coherent?**
2017/06/26
[ "https://writers.stackexchange.com/questions/28914", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/24575/" ]
[My PhD thesis](http://etheses.whiterose.ac.uk/12277/1/Infrared%20problem%20in%20the%20Faddeev--Popov%20sector%20in%20Yang--Mills%20Theory%20and%20Perturbative%20Gravity%20-%20Jos%20Gibbons%20-%20PhD%20-%202015.pdf) was divided in a nested manner into parts, chapters, sections and subsections. Whatever you're working on, I hope some of what helped me will help you: * Divide the work into numbered components, even if the reader never sees the numbers (although they can help the work reference other parts of itself). * Write a description of what each component's components do; for example, what do the sections in a given chapter do? Then zoom down even further. My thesis benefited from this for three reasons: I knew what to write (which helped me push on through the slog), I knew how I would explain it, and enclosing these descriptions in the thesis itself helped the readers follow. Whether you should enclose the descriptions I'll leave up to you, but write them at least. * As you write or redraft, think carefully about whether you've really explained things in the right order. If you have to move things around, fair enough; I know I certainly did. But if you've done the work above, you'll more readily notice better ideas, more easily think through how to do it, and know how to explain the revised structure. I know this doesn't read like advice Pinker would have written, but it complements his advice well enough. If you do everything I suggest at the large-scale level and everything he suggests at the small-scale level, you should be fine. I linked to my thesis above in case my advice is easier to follow when you see a worked example. And if unfamiliarity with the terminology used therein threatens to distract you from seeing what role such sentences play, just [nurble](https://www.smbc-comics.com/?id=2779) your way through everything but the section numbers.
The misconception at the heart of your question is that there has to be coherence between chapters, similar to the coherence between paragraphs. In **technical and academic writing** there is indeed coherence, usually, and then *the same principles apply* for the transition from the last paragraph of the preceding chapter to the first paragraph of the current chapter as between two paragraphs within one chapter. In other words: The chapter break is nothing but a paragraph break, and you connect chapters in the same way that you connect paragraphs. In **fiction**, the break between chapters is often a break in time, place, person, viewpoint, or chronology as well. What happens at the beginning of the current chapter appears, at first, to be totally unrelated to what we have read at the end of the preceding chapter. Only as we continue reading do we gather more and more clues as to how what we read now relates to what we have read before. A paragraph *always* establishes a connection (signified by an arrow in the schema below) to the preceding paragraph by referring to the topic ("A") of the preceding paragraph before beginning its own ("B"): [![enter image description here](https://i.stack.imgur.com/kcUxn.png)](https://i.stack.imgur.com/kcUxn.png) A chapter, on the other hand, *can* begin with a topic completely unrelated to any of the topics of the preceding chapter(s) and connect to the preceding text at a later point: [![enter image description here](https://i.stack.imgur.com/p4Zys.png)](https://i.stack.imgur.com/p4Zys.png) In my schema, forward arrows signify a topic being *continued* in a following sentence or paragraph, while a backward arrow signifies a *backward reference*. In reality, of course, every continuation is also a backward reference, and all arrows should point both ways. I just found unidirectional forward arrows to be less confusing, as they correspond to the forward movement of the reader through the text – who might want to browse back to where "X" was mentioned at at first, when it comes up in the second chapter again.
13,623,126
I have a two variables: ``` boost::array my_boost_array_variable_1<float, 3>; boost::array my_boost_array_variable_2<float, 3>; ``` now I want to call a C function with the following signature: ``` int MPI_Allreduce ( void *sendbuf, void *recvbuf, ...); ``` I want to pass the address of a particular element of my `my_boost_array_variable_1` and `my_boost_array_variable_2` as a first and second parameter of MPI\_Allreduce: ``` MPI_Allreduce(&my_boost_array_variable_1[2], &my_boost_array_variable_2[2], ... ``` or should I rather do: ``` MPI_Allreduce(my_boost_array_variable_1.c_array() + 2, my_boost_array_variable_2.c_array() + 2, ... ``` UPDATE: The C functions expect a continuous chunk of data, that starts at void \*sendbuf. The question here if these two calls are correct in this regard. Does &my\_boost\_array\_variable\_1[2] point to the same location as my\_boost\_array\_variable\_1.c\_array() + 2 ? Are these calls equivalent?
2012/11/29
[ "https://Stackoverflow.com/questions/13623126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18775/" ]
For me first is more clear then second. But in reality i think they are equal.
It is system-depended which one is faster, you can see the assembly code for your self. First method is safer, since it will throw you exception if you will try to address not legal index. Second method usually is faster, since you have only a single de-reference.
13,623,126
I have a two variables: ``` boost::array my_boost_array_variable_1<float, 3>; boost::array my_boost_array_variable_2<float, 3>; ``` now I want to call a C function with the following signature: ``` int MPI_Allreduce ( void *sendbuf, void *recvbuf, ...); ``` I want to pass the address of a particular element of my `my_boost_array_variable_1` and `my_boost_array_variable_2` as a first and second parameter of MPI\_Allreduce: ``` MPI_Allreduce(&my_boost_array_variable_1[2], &my_boost_array_variable_2[2], ... ``` or should I rather do: ``` MPI_Allreduce(my_boost_array_variable_1.c_array() + 2, my_boost_array_variable_2.c_array() + 2, ... ``` UPDATE: The C functions expect a continuous chunk of data, that starts at void \*sendbuf. The question here if these two calls are correct in this regard. Does &my\_boost\_array\_variable\_1[2] point to the same location as my\_boost\_array\_variable\_1.c\_array() + 2 ? Are these calls equivalent?
2012/11/29
[ "https://Stackoverflow.com/questions/13623126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18775/" ]
according to <http://www.boost.org/doc/libs/1_52_0/doc/html/boost/array.html> NEITHER version will throw. (could not comment with my little reputation :-))
It is system-depended which one is faster, you can see the assembly code for your self. First method is safer, since it will throw you exception if you will try to address not legal index. Second method usually is faster, since you have only a single de-reference.
4,757,392
I need fast way for generating random strings a-Z0-9 in PHP. I've been doing some thinking and testing, this is what I've got so far: ``` function randStr($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } ``` Function seems to be working fast compared to functions which iterate and choose random ASCII value for each char, but I'm concerned with 'quality' of my implementation. I do not know much about cryptography, so I'd like to ask whether this kind of function creates 'good' random values or not. 1. `mcrypt_create_iv` seems to return some kind of random binary values, actually used for encrypting/decrypting data with mcrypt library. What is base64\_encode effect on this kind of binary data, do I actually decrease entropy, when I base64\_encode it? 2. How does second parameter for `mcrypt_create_iv` affect my results? php.net manual states that `MCRYPT_RAND` is 'system random number generator'. Is it OS specific and if so, how good values are created?
2011/01/21
[ "https://Stackoverflow.com/questions/4757392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294696/" ]
I usually work with this one. Also I can choose if I don't want certain characters ``` function rstr5($length = 1) { return substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", $length)), 0, $length); } ```
This is how I'm doing it, though it's not exactly cryptographic; The Mersenne Twister is fast and reliable, but not the most secure. ``` function str_rand($chars, $len) { $str = ''; for ($max = strlen($chars) - 1, $i = 0; $i < $len; ++$i) { $str .= $chars[mt_rand(0, $max)]; } return $str; } $strRand = str_rand('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 40); ```
4,757,392
I need fast way for generating random strings a-Z0-9 in PHP. I've been doing some thinking and testing, this is what I've got so far: ``` function randStr($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } ``` Function seems to be working fast compared to functions which iterate and choose random ASCII value for each char, but I'm concerned with 'quality' of my implementation. I do not know much about cryptography, so I'd like to ask whether this kind of function creates 'good' random values or not. 1. `mcrypt_create_iv` seems to return some kind of random binary values, actually used for encrypting/decrypting data with mcrypt library. What is base64\_encode effect on this kind of binary data, do I actually decrease entropy, when I base64\_encode it? 2. How does second parameter for `mcrypt_create_iv` affect my results? php.net manual states that `MCRYPT_RAND` is 'system random number generator'. Is it OS specific and if so, how good values are created?
2011/01/21
[ "https://Stackoverflow.com/questions/4757392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294696/" ]
This supposed to be secure on most of the systems and fast: ``` bin2hex(openssl_random_pseudo_bytes($length / 2)); ``` benchmarks (1000000 records, string length 100 chars) ``` rstr1: 198.93383002281 rstr2: 35.5827729702 rstr3: 6.8811790943146 rstr4: 5.4545040130615 this:: 3.9310231208801 ```
I usually work with this one. Also I can choose if I don't want certain characters ``` function rstr5($length = 1) { return substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", $length)), 0, $length); } ```
4,757,392
I need fast way for generating random strings a-Z0-9 in PHP. I've been doing some thinking and testing, this is what I've got so far: ``` function randStr($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } ``` Function seems to be working fast compared to functions which iterate and choose random ASCII value for each char, but I'm concerned with 'quality' of my implementation. I do not know much about cryptography, so I'd like to ask whether this kind of function creates 'good' random values or not. 1. `mcrypt_create_iv` seems to return some kind of random binary values, actually used for encrypting/decrypting data with mcrypt library. What is base64\_encode effect on this kind of binary data, do I actually decrease entropy, when I base64\_encode it? 2. How does second parameter for `mcrypt_create_iv` affect my results? php.net manual states that `MCRYPT_RAND` is 'system random number generator'. Is it OS specific and if so, how good values are created?
2011/01/21
[ "https://Stackoverflow.com/questions/4757392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294696/" ]
For anyone looking for an updated version of the "best" algorithm: ``` function randomString($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(random_bytes($length))); } return substr($result, 0, $length); } ``` I use the term "best" because it is faster than the random string manipulations of `rstr1` and `rstr2` and in comparison to the other solutions offers a full spectrum of letters (lower- and uppercased).
I usually work with this one. Also I can choose if I don't want certain characters ``` function rstr5($length = 1) { return substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", $length)), 0, $length); } ```
4,757,392
I need fast way for generating random strings a-Z0-9 in PHP. I've been doing some thinking and testing, this is what I've got so far: ``` function randStr($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } ``` Function seems to be working fast compared to functions which iterate and choose random ASCII value for each char, but I'm concerned with 'quality' of my implementation. I do not know much about cryptography, so I'd like to ask whether this kind of function creates 'good' random values or not. 1. `mcrypt_create_iv` seems to return some kind of random binary values, actually used for encrypting/decrypting data with mcrypt library. What is base64\_encode effect on this kind of binary data, do I actually decrease entropy, when I base64\_encode it? 2. How does second parameter for `mcrypt_create_iv` affect my results? php.net manual states that `MCRYPT_RAND` is 'system random number generator'. Is it OS specific and if so, how good values are created?
2011/01/21
[ "https://Stackoverflow.com/questions/4757392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294696/" ]
From my tests, your function is already very fast, but i managed to get to a faster one, even if it decreases the entropy ``` fcn time rstr1: 1.074s (slowest) rstr2: 0.917s rstr3: 0.028s (yours) rstr4: 0.022s (mine) ``` In my scenario, i needed 1k strings, as fast as possible. ``` function rstr1($length) { // @see http://stackoverflow.com/a/853846/11301 $alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; return substr(str_shuffle(str_repeat($alphabet, $length)), 0, $length); } function rstr2($length) { // @see http://stackoverflow.com/a/853870/11301 $alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $str = ''; $count = strlen($alphabet); while ($length--) { $str .= $alphabet[mt_rand(0, $count-1)]; } return $str; } function rstr3($length) { // @see http://stackoverflow.com/q/4757392/11301 $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } function rstr4($length) { // uses md5 & mt_rand. Not as "random" as it could be, but it works, and its fastest from my tests return str_shuffle(substr(str_repeat(md5(mt_rand()), 2+$length/32), 0, $length)); } // test the functions for($i=0; $i<1000; $i++){ #$x = rstr1(1024); # #$x = rstr2(1024); # 0.917s #$x = rstr3(1024); # 0.028s #$x = rstr4(1024); # 0.022s #dlog($x); return; } ```
This is how I'm doing it, though it's not exactly cryptographic; The Mersenne Twister is fast and reliable, but not the most secure. ``` function str_rand($chars, $len) { $str = ''; for ($max = strlen($chars) - 1, $i = 0; $i < $len; ++$i) { $str .= $chars[mt_rand(0, $max)]; } return $str; } $strRand = str_rand('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 40); ```
4,757,392
I need fast way for generating random strings a-Z0-9 in PHP. I've been doing some thinking and testing, this is what I've got so far: ``` function randStr($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } ``` Function seems to be working fast compared to functions which iterate and choose random ASCII value for each char, but I'm concerned with 'quality' of my implementation. I do not know much about cryptography, so I'd like to ask whether this kind of function creates 'good' random values or not. 1. `mcrypt_create_iv` seems to return some kind of random binary values, actually used for encrypting/decrypting data with mcrypt library. What is base64\_encode effect on this kind of binary data, do I actually decrease entropy, when I base64\_encode it? 2. How does second parameter for `mcrypt_create_iv` affect my results? php.net manual states that `MCRYPT_RAND` is 'system random number generator'. Is it OS specific and if so, how good values are created?
2011/01/21
[ "https://Stackoverflow.com/questions/4757392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294696/" ]
1. base64\_encoding won't decrease entropy, it is just a different representation of the same data. 2. It is OS specific, but I think the random values created are good enough with this function. Under PHP 5.3 you have to seed the generator beforehand, it can be a problem if you use this code on different servers.
From my tests, your function is already very fast, but i managed to get to a faster one, even if it decreases the entropy ``` fcn time rstr1: 1.074s (slowest) rstr2: 0.917s rstr3: 0.028s (yours) rstr4: 0.022s (mine) ``` In my scenario, i needed 1k strings, as fast as possible. ``` function rstr1($length) { // @see http://stackoverflow.com/a/853846/11301 $alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; return substr(str_shuffle(str_repeat($alphabet, $length)), 0, $length); } function rstr2($length) { // @see http://stackoverflow.com/a/853870/11301 $alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $str = ''; $count = strlen($alphabet); while ($length--) { $str .= $alphabet[mt_rand(0, $count-1)]; } return $str; } function rstr3($length) { // @see http://stackoverflow.com/q/4757392/11301 $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } function rstr4($length) { // uses md5 & mt_rand. Not as "random" as it could be, but it works, and its fastest from my tests return str_shuffle(substr(str_repeat(md5(mt_rand()), 2+$length/32), 0, $length)); } // test the functions for($i=0; $i<1000; $i++){ #$x = rstr1(1024); # #$x = rstr2(1024); # 0.917s #$x = rstr3(1024); # 0.028s #$x = rstr4(1024); # 0.022s #dlog($x); return; } ```
4,757,392
I need fast way for generating random strings a-Z0-9 in PHP. I've been doing some thinking and testing, this is what I've got so far: ``` function randStr($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } ``` Function seems to be working fast compared to functions which iterate and choose random ASCII value for each char, but I'm concerned with 'quality' of my implementation. I do not know much about cryptography, so I'd like to ask whether this kind of function creates 'good' random values or not. 1. `mcrypt_create_iv` seems to return some kind of random binary values, actually used for encrypting/decrypting data with mcrypt library. What is base64\_encode effect on this kind of binary data, do I actually decrease entropy, when I base64\_encode it? 2. How does second parameter for `mcrypt_create_iv` affect my results? php.net manual states that `MCRYPT_RAND` is 'system random number generator'. Is it OS specific and if so, how good values are created?
2011/01/21
[ "https://Stackoverflow.com/questions/4757392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294696/" ]
1. base64\_encoding won't decrease entropy, it is just a different representation of the same data. 2. It is OS specific, but I think the random values created are good enough with this function. Under PHP 5.3 you have to seed the generator beforehand, it can be a problem if you use this code on different servers.
I usually work with this one. Also I can choose if I don't want certain characters ``` function rstr5($length = 1) { return substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", $length)), 0, $length); } ```
4,757,392
I need fast way for generating random strings a-Z0-9 in PHP. I've been doing some thinking and testing, this is what I've got so far: ``` function randStr($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } ``` Function seems to be working fast compared to functions which iterate and choose random ASCII value for each char, but I'm concerned with 'quality' of my implementation. I do not know much about cryptography, so I'd like to ask whether this kind of function creates 'good' random values or not. 1. `mcrypt_create_iv` seems to return some kind of random binary values, actually used for encrypting/decrypting data with mcrypt library. What is base64\_encode effect on this kind of binary data, do I actually decrease entropy, when I base64\_encode it? 2. How does second parameter for `mcrypt_create_iv` affect my results? php.net manual states that `MCRYPT_RAND` is 'system random number generator'. Is it OS specific and if so, how good values are created?
2011/01/21
[ "https://Stackoverflow.com/questions/4757392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294696/" ]
For anyone looking for an updated version of the "best" algorithm: ``` function randomString($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(random_bytes($length))); } return substr($result, 0, $length); } ``` I use the term "best" because it is faster than the random string manipulations of `rstr1` and `rstr2` and in comparison to the other solutions offers a full spectrum of letters (lower- and uppercased).
This is how I'm doing it, though it's not exactly cryptographic; The Mersenne Twister is fast and reliable, but not the most secure. ``` function str_rand($chars, $len) { $str = ''; for ($max = strlen($chars) - 1, $i = 0; $i < $len; ++$i) { $str .= $chars[mt_rand(0, $max)]; } return $str; } $strRand = str_rand('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 40); ```
4,757,392
I need fast way for generating random strings a-Z0-9 in PHP. I've been doing some thinking and testing, this is what I've got so far: ``` function randStr($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } ``` Function seems to be working fast compared to functions which iterate and choose random ASCII value for each char, but I'm concerned with 'quality' of my implementation. I do not know much about cryptography, so I'd like to ask whether this kind of function creates 'good' random values or not. 1. `mcrypt_create_iv` seems to return some kind of random binary values, actually used for encrypting/decrypting data with mcrypt library. What is base64\_encode effect on this kind of binary data, do I actually decrease entropy, when I base64\_encode it? 2. How does second parameter for `mcrypt_create_iv` affect my results? php.net manual states that `MCRYPT_RAND` is 'system random number generator'. Is it OS specific and if so, how good values are created?
2011/01/21
[ "https://Stackoverflow.com/questions/4757392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294696/" ]
For anyone looking for an updated version of the "best" algorithm: ``` function randomString($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(random_bytes($length))); } return substr($result, 0, $length); } ``` I use the term "best" because it is faster than the random string manipulations of `rstr1` and `rstr2` and in comparison to the other solutions offers a full spectrum of letters (lower- and uppercased).
From my tests, your function is already very fast, but i managed to get to a faster one, even if it decreases the entropy ``` fcn time rstr1: 1.074s (slowest) rstr2: 0.917s rstr3: 0.028s (yours) rstr4: 0.022s (mine) ``` In my scenario, i needed 1k strings, as fast as possible. ``` function rstr1($length) { // @see http://stackoverflow.com/a/853846/11301 $alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; return substr(str_shuffle(str_repeat($alphabet, $length)), 0, $length); } function rstr2($length) { // @see http://stackoverflow.com/a/853870/11301 $alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $str = ''; $count = strlen($alphabet); while ($length--) { $str .= $alphabet[mt_rand(0, $count-1)]; } return $str; } function rstr3($length) { // @see http://stackoverflow.com/q/4757392/11301 $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } function rstr4($length) { // uses md5 & mt_rand. Not as "random" as it could be, but it works, and its fastest from my tests return str_shuffle(substr(str_repeat(md5(mt_rand()), 2+$length/32), 0, $length)); } // test the functions for($i=0; $i<1000; $i++){ #$x = rstr1(1024); # #$x = rstr2(1024); # 0.917s #$x = rstr3(1024); # 0.028s #$x = rstr4(1024); # 0.022s #dlog($x); return; } ```
4,757,392
I need fast way for generating random strings a-Z0-9 in PHP. I've been doing some thinking and testing, this is what I've got so far: ``` function randStr($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } ``` Function seems to be working fast compared to functions which iterate and choose random ASCII value for each char, but I'm concerned with 'quality' of my implementation. I do not know much about cryptography, so I'd like to ask whether this kind of function creates 'good' random values or not. 1. `mcrypt_create_iv` seems to return some kind of random binary values, actually used for encrypting/decrypting data with mcrypt library. What is base64\_encode effect on this kind of binary data, do I actually decrease entropy, when I base64\_encode it? 2. How does second parameter for `mcrypt_create_iv` affect my results? php.net manual states that `MCRYPT_RAND` is 'system random number generator'. Is it OS specific and if so, how good values are created?
2011/01/21
[ "https://Stackoverflow.com/questions/4757392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294696/" ]
1. base64\_encoding won't decrease entropy, it is just a different representation of the same data. 2. It is OS specific, but I think the random values created are good enough with this function. Under PHP 5.3 you have to seed the generator beforehand, it can be a problem if you use this code on different servers.
This is how I'm doing it, though it's not exactly cryptographic; The Mersenne Twister is fast and reliable, but not the most secure. ``` function str_rand($chars, $len) { $str = ''; for ($max = strlen($chars) - 1, $i = 0; $i < $len; ++$i) { $str .= $chars[mt_rand(0, $max)]; } return $str; } $strRand = str_rand('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 40); ```
4,757,392
I need fast way for generating random strings a-Z0-9 in PHP. I've been doing some thinking and testing, this is what I've got so far: ``` function randStr($length) { $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } ``` Function seems to be working fast compared to functions which iterate and choose random ASCII value for each char, but I'm concerned with 'quality' of my implementation. I do not know much about cryptography, so I'd like to ask whether this kind of function creates 'good' random values or not. 1. `mcrypt_create_iv` seems to return some kind of random binary values, actually used for encrypting/decrypting data with mcrypt library. What is base64\_encode effect on this kind of binary data, do I actually decrease entropy, when I base64\_encode it? 2. How does second parameter for `mcrypt_create_iv` affect my results? php.net manual states that `MCRYPT_RAND` is 'system random number generator'. Is it OS specific and if so, how good values are created?
2011/01/21
[ "https://Stackoverflow.com/questions/4757392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294696/" ]
This supposed to be secure on most of the systems and fast: ``` bin2hex(openssl_random_pseudo_bytes($length / 2)); ``` benchmarks (1000000 records, string length 100 chars) ``` rstr1: 198.93383002281 rstr2: 35.5827729702 rstr3: 6.8811790943146 rstr4: 5.4545040130615 this:: 3.9310231208801 ```
This is how I'm doing it, though it's not exactly cryptographic; The Mersenne Twister is fast and reliable, but not the most secure. ``` function str_rand($chars, $len) { $str = ''; for ($max = strlen($chars) - 1, $i = 0; $i < $len; ++$i) { $str .= $chars[mt_rand(0, $max)]; } return $str; } $strRand = str_rand('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 40); ```
18,471
According to Catholic thought, if we are washed of Original Sin at the time of baptism, why do we transmit Original Sin to our children? In other words, how is it that my child is born with Original Sin when I was freed from Original Sin at the time of my baptism?
2013/08/18
[ "https://christianity.stackexchange.com/questions/18471", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/5459/" ]
I think you misunderstood the role of Baptism in Catholicism. Cathecism of the Catholic Church-1263 says > > [1263] By Baptism all sins are **forgiven**, original sin and all personal > sins, as well as all punishment for sin. In those who have been > reborn nothing remains that would impede their entry into the Kingdom > of God, neither Adam's sin, nor personal sin, nor the consequences of > sin, the gravest of which is separation from God. > > > It doesn't say original sin is washed away, it says it is forgiven. Forgiven doesn't mean you don't have original sin anymore; it only means your sins are forgiven. Our sins cannot be washed away by merely washing with water nor any kind of Baptism. Only the blood of Jesus Christ can wash away our sins. > > *1 John 1:7 (NIV)* But if we walk in the light, as he is in the light, > we have fellowship with one another, and the **blood of Jesus**, his Son, > **purifies us from all sin**. > > > *Revelation 7:14 (NKJV)* And I said to him, “Sir, you know.” So he said > to me, “These are the ones who come out of the great tribulation, and > **washed their robes** and made them white **in the blood of the Lamb**. > > > *Revelation 22:14 (DRA)* Blessed are they that **wash their robes in the > blood of the Lamb**: that they may have a right to the tree of life, and > may enter in by the gates into the city. > > >
Not being a Roman Catholic, I cannot give you an answer from the RC perspective and tradition. I can, however, give you a brief overview about what the Bible has to say about Christian baptism. As a wise man once told me, > > "Baptism doesn't *make* you a Christian; it *marks* you as a Christian." > > > As good as infant baptism may be as a way for Christian parents to "sanctify" their offspring through a well-established rite (which exists in both the Catholic and Protestant traditions), nowhere in the New Testament is there any indication that infant baptism cleanses the infant from "original sin." If the RC church teaches this, all I can say is, the teaching is not biblical. On the basis of Scripture, I say confidently but lovingly, the physical act of being baptized neither forgives us of sin nor frees us from sin. To say otherwise is to contradict the clear teaching of Scripture. If, however, Scripture is not the ultimate guide for your life and practice, then none of the following will be of help to you, and will certainly not answer your question--though I am glad you asked it! There are two baptisms in the New Testament, each having two aspects, both *spiritual* and *literal/physical*. The first is the baptism of John. John the Baptizer fulfilled two roles: the first as a herald for the Messiah, and the second as a forerunner for the Messiah. > > (1) John as a herald. In John's day, just as the king's servant who preceded his king during royal tours from city to city would announce in a loud voice, "The king is coming, the king is coming, get ready for the coming of your king," so too did John announce the coming of the King Jesus, the Messiah. > > > John, however, shouted > > "Repent, the kingdom of heaven is at hand, the kingdom of heaven is at hand, the kingdom of heaven is at hand" (Matthew 3:2). > > > John certainly attracted the attention of the people with his announcement of the coming kingdom, and they came to him in great numbers. > > (2) John as a forerunner. Historically, when a king was scheduled to enter a city, he was not only preceded by a herald, but he also sent servants called *forerunners* ahead of him to remove any obstacles such as rocks, tree branches, or potholes--anything that would impede his path as he was being carried by litter into the city. > > > What was hindering the entrance of Jesus the Messiah into the hearts of the people? Sin. John therefore had to tell the people > > "'Make ready the way of the LORD, Make His paths straight'" (Matthew 3:3; Isaiah 40:3). > > > Just as the forerunners of old were responsible to remove obstacles from the road, so too was John responsible to get people to repent of their sins, removing anything that would hinder the entrance of Messiah into their hearts and lives. John's message to the crowds who came to hear him was a simple one: > > "Repent" > > > And repent the crowds did! Repentance is simply a change of mind resulting in changed behavior. It's doing an "about face": you are going in one direction, but you make a 180-degree turn and go in the opposite direction. > > " . . . and [the people from Jerusalem and the surrounding areas] were being baptized by him in the Jordan River, as they confessed their sins" (Matthew 3:2,6). > > > Before a watching world, the people baptized by John were declaring openly in the waters of the Jordan River--that's the *literal/physical* part of baptism--what had transpired inside their hearts--that's the *spiritual* part of baptism; namely, that they were turning their backs on their sins in preparation for the appearance of the coming Messiah, whose coming John foretold. Being baptized did not cleanse anyone of sin, it merely bore witness to their repentance. On the other hand, the baptism of the Messiah was completely different. As John himself said of Jesus, the coming Messiah and king: > > ". . . this is the One who baptizes in the Holy Spirit" (John 1:33). > > > The second baptism, then, is Christian baptism. Like John's baptism, it has both a literal/physical aspect and a spiritual aspect. The physical aspect is the outward act of being immersed in (or sprinkled by) actual water in the presence of witnesses, and > > ". . . in the name of the Father and the Son and the Holy Spirit" (Matthew 28:19). > > > The spiritual aspect is the inward process of conversion by the Holy Spirit, which takes place *before* we are baptized. Call it regeneration, as in > > ". . . the washing of regeneration and renewing by the Holy Spirit" (Titus 3:5), > > > or call it being born again or born from above, as in Jesus' words, > > "Truly, truly, I say to you, unless one is born again he cannot see the kingdom of God. . . . [and] unless one is born of water and the Spirit he cannot enter into the kingdom of God" (John 3:3,5). > > > Christian baptism is for believers in Jesus Christ who have been regenerated within their spirits by the Spirit of Christ, whom Jesus called a "Helper," "the Spirit of truth" who "teaches us all things," and the presence of Christ within us "forever" (see John 14:16 and ff.). Believers who are indwelt by the Holy Spirit want to bear witness to that transformation by obeying the command of our Lord to be baptized. To this day, in some countries of the world, being baptized openly and publicly is to invite persecution and even death! As Paul tells us in Romans 6, Christian baptism is a symbol of our having died to our old way of life. When we die, we need to be buried. Baptism, then, is a picture of burial that is enacted symbolically by immersing ("burying") a person in water. As the person comes up out of the water, symbolically he is coming alive in the Spirit of God, just as Jesus came alive in His glorious resurrection from the dead (vv.3-5 and ff.). Does being baptized mean we will never sin again? No. Neither an infant who has been baptized nor a person who has experienced the new birth and has been baptized will cease to sin (see 1 John 1:8-10). We can, however, have victory over sin in our lives, since as believers in Jesus > > ". . . our old self was crucified with Him, in order that our body of sin might be done away with, so that we would no longer be slaves to sin" (Romans 6:6). > > > Furthermore, we have the responsibility as baptized believers (literally and spiritually) to > > ". . . consider [ourselves] to be dead to sin, but alive to God in Christ Jesus"; > > > "not [to] let sin reign in [our] mortal body so that [we] obey its lusts"; > > > "[to] present [ourselves] to God as those alive from the dead, and [our] members as instruments of righteousness to God"; > > > "[because] sin shall not be master over [us], for [we] are not under law but under grace" (Romans 6:11-14). > > > In conclusion, being baptized with water neither cleanses us from sin nor takes away our ability to sin. It is, however, a way of telling both God and man that we have become new creatures in Christ, that > > "the old things passed away; behold, new things have come" (2 Corinthians 5:17). > > >
18,471
According to Catholic thought, if we are washed of Original Sin at the time of baptism, why do we transmit Original Sin to our children? In other words, how is it that my child is born with Original Sin when I was freed from Original Sin at the time of my baptism?
2013/08/18
[ "https://christianity.stackexchange.com/questions/18471", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/5459/" ]
Original sin is a state of human nature passed to all mankind, but it is not like a gene passed on from our immediate parents. It affects the nature of all humans. The Catholic Catechism discusses this in and around paragraphs 396 to 408. In paragraph 404 talks a bit about what Original Sin is and its source: > > But we do know by Revelation that Adam had received original holiness and justice not for himself alone, but for all human nature. By yielding to the tempter, Adam and Eve committed a personal sin, but **this sin affected the human nature that they [Adam and Eve] would then transmit in a fallen state**. It is a sin which will be transmitted by propagation to all mankind, that is, by the transmission of a human nature deprived of original holiness and justice. > > > In paragraph 405 talks about what Original Sin is and the effects of Baptism on it: > > Although it is proper to each individual, original sin does not have the character of a personal fault in any of Adam's descendants. It is a **deprivation of original holiness and justice**, but human nature has not been totally corrupted: it is wounded in the natural powers proper to it, subject to ignorance, suffering and the dominion of death, and inclined to sin — **an inclination to evil that is called concupiscence**". Baptism, by imparting the life of Christ's grace, **erases original sin and turns a man back towards God, but the consequences for nature, weakened and inclined to evil, persist in man and summon him to spiritual battle**. > > > On the effects of Baptism, paragraph 978 says: > > "When we made our first profession of faith while receiving the holy Baptism that cleansed us, the forgiveness we received then was so full and complete that there remained in us absolutely nothing left to efface, neither original sin nor offenses committed by our own will, nor was there left any penalty to suffer in order to expiate them. ... **Yet the grace of Baptism delivers no one from all the weakness of nature**. On the contrary, we must still combat the movements of concupiscence that never cease leading us into evil " > > > Finally, in talking about Baptism of Infants in paragraph 1250: > > Born with a fallen human nature and tainted by original sin, children also have need of the new birth in Baptism to be freed from the power of darkness and brought into the realm of the freedom of the children of God, to which all men are called. The sheer gratuitousness of the grace of salvation is particularly manifest in infant Baptism. The Church and the parents would deny a child the priceless grace of becoming a child of God were they not to confer Baptism shortly after birth. > > >
Not being a Roman Catholic, I cannot give you an answer from the RC perspective and tradition. I can, however, give you a brief overview about what the Bible has to say about Christian baptism. As a wise man once told me, > > "Baptism doesn't *make* you a Christian; it *marks* you as a Christian." > > > As good as infant baptism may be as a way for Christian parents to "sanctify" their offspring through a well-established rite (which exists in both the Catholic and Protestant traditions), nowhere in the New Testament is there any indication that infant baptism cleanses the infant from "original sin." If the RC church teaches this, all I can say is, the teaching is not biblical. On the basis of Scripture, I say confidently but lovingly, the physical act of being baptized neither forgives us of sin nor frees us from sin. To say otherwise is to contradict the clear teaching of Scripture. If, however, Scripture is not the ultimate guide for your life and practice, then none of the following will be of help to you, and will certainly not answer your question--though I am glad you asked it! There are two baptisms in the New Testament, each having two aspects, both *spiritual* and *literal/physical*. The first is the baptism of John. John the Baptizer fulfilled two roles: the first as a herald for the Messiah, and the second as a forerunner for the Messiah. > > (1) John as a herald. In John's day, just as the king's servant who preceded his king during royal tours from city to city would announce in a loud voice, "The king is coming, the king is coming, get ready for the coming of your king," so too did John announce the coming of the King Jesus, the Messiah. > > > John, however, shouted > > "Repent, the kingdom of heaven is at hand, the kingdom of heaven is at hand, the kingdom of heaven is at hand" (Matthew 3:2). > > > John certainly attracted the attention of the people with his announcement of the coming kingdom, and they came to him in great numbers. > > (2) John as a forerunner. Historically, when a king was scheduled to enter a city, he was not only preceded by a herald, but he also sent servants called *forerunners* ahead of him to remove any obstacles such as rocks, tree branches, or potholes--anything that would impede his path as he was being carried by litter into the city. > > > What was hindering the entrance of Jesus the Messiah into the hearts of the people? Sin. John therefore had to tell the people > > "'Make ready the way of the LORD, Make His paths straight'" (Matthew 3:3; Isaiah 40:3). > > > Just as the forerunners of old were responsible to remove obstacles from the road, so too was John responsible to get people to repent of their sins, removing anything that would hinder the entrance of Messiah into their hearts and lives. John's message to the crowds who came to hear him was a simple one: > > "Repent" > > > And repent the crowds did! Repentance is simply a change of mind resulting in changed behavior. It's doing an "about face": you are going in one direction, but you make a 180-degree turn and go in the opposite direction. > > " . . . and [the people from Jerusalem and the surrounding areas] were being baptized by him in the Jordan River, as they confessed their sins" (Matthew 3:2,6). > > > Before a watching world, the people baptized by John were declaring openly in the waters of the Jordan River--that's the *literal/physical* part of baptism--what had transpired inside their hearts--that's the *spiritual* part of baptism; namely, that they were turning their backs on their sins in preparation for the appearance of the coming Messiah, whose coming John foretold. Being baptized did not cleanse anyone of sin, it merely bore witness to their repentance. On the other hand, the baptism of the Messiah was completely different. As John himself said of Jesus, the coming Messiah and king: > > ". . . this is the One who baptizes in the Holy Spirit" (John 1:33). > > > The second baptism, then, is Christian baptism. Like John's baptism, it has both a literal/physical aspect and a spiritual aspect. The physical aspect is the outward act of being immersed in (or sprinkled by) actual water in the presence of witnesses, and > > ". . . in the name of the Father and the Son and the Holy Spirit" (Matthew 28:19). > > > The spiritual aspect is the inward process of conversion by the Holy Spirit, which takes place *before* we are baptized. Call it regeneration, as in > > ". . . the washing of regeneration and renewing by the Holy Spirit" (Titus 3:5), > > > or call it being born again or born from above, as in Jesus' words, > > "Truly, truly, I say to you, unless one is born again he cannot see the kingdom of God. . . . [and] unless one is born of water and the Spirit he cannot enter into the kingdom of God" (John 3:3,5). > > > Christian baptism is for believers in Jesus Christ who have been regenerated within their spirits by the Spirit of Christ, whom Jesus called a "Helper," "the Spirit of truth" who "teaches us all things," and the presence of Christ within us "forever" (see John 14:16 and ff.). Believers who are indwelt by the Holy Spirit want to bear witness to that transformation by obeying the command of our Lord to be baptized. To this day, in some countries of the world, being baptized openly and publicly is to invite persecution and even death! As Paul tells us in Romans 6, Christian baptism is a symbol of our having died to our old way of life. When we die, we need to be buried. Baptism, then, is a picture of burial that is enacted symbolically by immersing ("burying") a person in water. As the person comes up out of the water, symbolically he is coming alive in the Spirit of God, just as Jesus came alive in His glorious resurrection from the dead (vv.3-5 and ff.). Does being baptized mean we will never sin again? No. Neither an infant who has been baptized nor a person who has experienced the new birth and has been baptized will cease to sin (see 1 John 1:8-10). We can, however, have victory over sin in our lives, since as believers in Jesus > > ". . . our old self was crucified with Him, in order that our body of sin might be done away with, so that we would no longer be slaves to sin" (Romans 6:6). > > > Furthermore, we have the responsibility as baptized believers (literally and spiritually) to > > ". . . consider [ourselves] to be dead to sin, but alive to God in Christ Jesus"; > > > "not [to] let sin reign in [our] mortal body so that [we] obey its lusts"; > > > "[to] present [ourselves] to God as those alive from the dead, and [our] members as instruments of righteousness to God"; > > > "[because] sin shall not be master over [us], for [we] are not under law but under grace" (Romans 6:11-14). > > > In conclusion, being baptized with water neither cleanses us from sin nor takes away our ability to sin. It is, however, a way of telling both God and man that we have become new creatures in Christ, that > > "the old things passed away; behold, new things have come" (2 Corinthians 5:17). > > >
18,471
According to Catholic thought, if we are washed of Original Sin at the time of baptism, why do we transmit Original Sin to our children? In other words, how is it that my child is born with Original Sin when I was freed from Original Sin at the time of my baptism?
2013/08/18
[ "https://christianity.stackexchange.com/questions/18471", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/5459/" ]
I think you misunderstood the role of Baptism in Catholicism. Cathecism of the Catholic Church-1263 says > > [1263] By Baptism all sins are **forgiven**, original sin and all personal > sins, as well as all punishment for sin. In those who have been > reborn nothing remains that would impede their entry into the Kingdom > of God, neither Adam's sin, nor personal sin, nor the consequences of > sin, the gravest of which is separation from God. > > > It doesn't say original sin is washed away, it says it is forgiven. Forgiven doesn't mean you don't have original sin anymore; it only means your sins are forgiven. Our sins cannot be washed away by merely washing with water nor any kind of Baptism. Only the blood of Jesus Christ can wash away our sins. > > *1 John 1:7 (NIV)* But if we walk in the light, as he is in the light, > we have fellowship with one another, and the **blood of Jesus**, his Son, > **purifies us from all sin**. > > > *Revelation 7:14 (NKJV)* And I said to him, “Sir, you know.” So he said > to me, “These are the ones who come out of the great tribulation, and > **washed their robes** and made them white **in the blood of the Lamb**. > > > *Revelation 22:14 (DRA)* Blessed are they that **wash their robes in the > blood of the Lamb**: that they may have a right to the tree of life, and > may enter in by the gates into the city. > > >
Original sin is a state of human nature passed to all mankind, but it is not like a gene passed on from our immediate parents. It affects the nature of all humans. The Catholic Catechism discusses this in and around paragraphs 396 to 408. In paragraph 404 talks a bit about what Original Sin is and its source: > > But we do know by Revelation that Adam had received original holiness and justice not for himself alone, but for all human nature. By yielding to the tempter, Adam and Eve committed a personal sin, but **this sin affected the human nature that they [Adam and Eve] would then transmit in a fallen state**. It is a sin which will be transmitted by propagation to all mankind, that is, by the transmission of a human nature deprived of original holiness and justice. > > > In paragraph 405 talks about what Original Sin is and the effects of Baptism on it: > > Although it is proper to each individual, original sin does not have the character of a personal fault in any of Adam's descendants. It is a **deprivation of original holiness and justice**, but human nature has not been totally corrupted: it is wounded in the natural powers proper to it, subject to ignorance, suffering and the dominion of death, and inclined to sin — **an inclination to evil that is called concupiscence**". Baptism, by imparting the life of Christ's grace, **erases original sin and turns a man back towards God, but the consequences for nature, weakened and inclined to evil, persist in man and summon him to spiritual battle**. > > > On the effects of Baptism, paragraph 978 says: > > "When we made our first profession of faith while receiving the holy Baptism that cleansed us, the forgiveness we received then was so full and complete that there remained in us absolutely nothing left to efface, neither original sin nor offenses committed by our own will, nor was there left any penalty to suffer in order to expiate them. ... **Yet the grace of Baptism delivers no one from all the weakness of nature**. On the contrary, we must still combat the movements of concupiscence that never cease leading us into evil " > > > Finally, in talking about Baptism of Infants in paragraph 1250: > > Born with a fallen human nature and tainted by original sin, children also have need of the new birth in Baptism to be freed from the power of darkness and brought into the realm of the freedom of the children of God, to which all men are called. The sheer gratuitousness of the grace of salvation is particularly manifest in infant Baptism. The Church and the parents would deny a child the priceless grace of becoming a child of God were they not to confer Baptism shortly after birth. > > >
11,369,040
I need to return the actual text description of the db connection, and any other relevant info about the DB. Why? I call a service and the expected data comes back perfectly. Now, when I do the same call inside of a secure tunnel, I get completely different results. All indications say that the code is working in both cases. So, I can only imagine that it's hooking up to a different DB... So...I would like to have the function return the server name and the actual db being queried against - even the path where the DB resides would be awesome!
2012/07/06
[ "https://Stackoverflow.com/questions/11369040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/777828/" ]
I hope I've understood correctly: ``` function test() { var db = ScriptDb.getMyDb(); var result = db.query({id: 434}) var quals = result.next().qualifications; var hasQual = false; for (var i = 0; i < quals.length; i++) { if (quals[i].name == 'QUAL1' && quals[i].issueDate > 20050101) { hasQual = true; break; } } Logger.log(hasQual); } ```
It isn't currently possible to construct a query that looks for a value within an array. You can file a feature request for that on the [issue tracker](http://code.google.com/p/google-apps-script-issues/issues/list).
32,876,250
I downloaded a Pycharm community mac OSX version. But after installation, each time I try to open it. It gives me this error. I can't find any information about this error after I google the error. [![enter image description here](https://i.stack.imgur.com/QzNEO.png)](https://i.stack.imgur.com/QzNEO.png) Thank you.
2015/09/30
[ "https://Stackoverflow.com/questions/32876250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1076975/" ]
OK. It turn out be a permission problem. Just chmod 777 the directory(mkdir before). Then this problem is solved
Start --> Search "idea.log". In this file change the path.
56,100,559
I've migrated to `androidx` and after a ton of time with it, I can't move away from the error below. I've integrated `multidex` but I still get the error. This is the exception: > > FAILURE: Build failed with an exception. > > > > What went wrong: > > Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForBetaDebug'. > java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex > > > I can't make it work. Here's my build.gradle. Any ideas? ``` buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'io.fabric.tools:gradle:1.+' } } apply plugin: 'com.android.application' apply plugin: 'io.fabric' repositories { maven { url 'https://maven.fabric.io/public' } } android { compileSdkVersion 28 buildToolsVersion '27.0.3' signingConfigs { releaseSign { storeFile file("$rootProject.projectDir/keystore_release.jks") storePassword 'xxxxxxx' keyAlias 'xxxxxxx' keyPassword 'xxxxxxx' } } // Butterknife requires Java 8. compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "com.xxxxxxx.xxxxxxx" minSdkVersion 19 targetSdkVersion 28 versionCode 10 versionName "1.0.10" renderscriptTargetApi 19 renderscriptSupportModeEnabled true multiDexEnabled true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.releaseSign } } flavorDimensions "default" productFlavors { beta { applicationId "com.xxxxxxx.xxxxxxx.beta" dimension "default" resValue "string", "app_name", "xxxxxxx Beta" buildConfigField "String", "BASE_URL", '"http://xxxxxxx.net"' buildConfigField "Boolean", "IS_BETA", "true" buildConfigField "String", "TENANT", '"xxxxxxx"' } production { applicationId "com.xxxxxxx.driver" dimension "default" resValue "string", "app_name", "Driver" buildConfigField "String", "BASE_URL", '"http://apxxxxxxx"' buildConfigField "Boolean", "IS_BETA", "false" buildConfigField "String", "TENANT", '"xxxxxxx"' } } packagingOptions { exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/notice' exclude 'META-INF/notice.txt' exclude 'META-INF/license' exclude 'META-INF/license.txt' } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.1.0-alpha05' implementation 'androidx.cardview:cardview:1.0.0' implementation 'com.google.android.material:material:1.1.0-alpha06' implementation 'com.jakewharton:butterknife:10.1.0' annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0' implementation 'com.google.code.gson:gson:2.8.5' implementation 'me.grantland:autofittextview:0.2.1' implementation 'com.android.volley:volley:1.1.1' implementation 'org.greenrobot:eventbus:3.1.1' implementation 'com.github.ybq:Android-SpinKit:1.2.0' implementation 'com.google.android.gms:play-services-location:16.0.0' implementation 'com.crashlytics.sdk.android:crashlytics:2.10.0' implementation 'com.google.firebase:firebase-core:16.0.9' implementation 'com.google.firebase:firebase-messaging:18.0.0' implementation 'androidx.multidex:multidex:2.0.1' def work_version = "2.0.1" implementation "androidx.work:work-runtime:$work_version" // Optional - RxJava2 support implementation "androidx.work:work-rxjava2:$work_version" def futures_version = "1.0.0-beta01" implementation "androidx.concurrent:concurrent-futures:$futures_version" } apply plugin: 'com.google.gms.google-services' ```
2019/05/12
[ "https://Stackoverflow.com/questions/56100559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2064171/" ]
This is a great question! Your rectangle can be thought of as 4 lines: ``` (x, y) → (x+width, y) # top (x+width, y) → (x+width, y+height) # right (x, y+height) → (x+width, y+height) # bottom (x, y) → (x, y+height) # left ``` Taking your intersecting line, it's possible to use the [two-lines intersecting formula](https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection) to determine if any of these lines intersect (but be careful of parallel lines!) However the formula (specified in linked Wikipedia article) determines if the lines intersect anywhere on the 2D plane, so it needs to be further refined. Obviously the code can quickly throw away any intersections that occur outside the window dimensions. Once the "infinite-plane" collision-point has been determined (which is a reasonably quick determination), then a more fine-grained intersection can be determined. Using [Bresenham's algorithm](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm), enumerate all the points in the intersecting line, and compare them with a 1-pixel rectangle based on each side of your square. This will tell you which side of the rectangle intersected. If you only need to know if the rectangle was hit, just check the whole rectangle with `pygame.Rect.collidepoint()` for each point in the line. [![enter image description here](https://i.stack.imgur.com/47K0D.gif)](https://i.stack.imgur.com/47K0D.gif) Of course once you have all those points generated, it's easily to not bother with the 2D line collision, but for long lines the code must make a lot of checks. So testing the 2D intersection first really speeds it up.
Basically, is doesn't exist a method nor any pygame functionality to detect collisions with lines, that's why I had to come up with the solution I'm about to show. Using the following [link](https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection), at section *formulas / Given two points on each line segment*, you can find a formula to know if two lines intersect each other, and if they do, where exactly. The basic idea is to check if for every ray in the lightsource there is an intersection with any of the four sides of the rectangle, if so, the lightray should end at that same side of the rectangle. ``` import pygame, math pygame.init() screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Rays') pygame.mouse.set_visible(False) DENSITY = 500 RADIUS = 1000 run = True while run: screen.fill('black') rect = pygame.Rect(50, 200, 100, 50) pygame.draw.rect(screen, 'red', rect) for i in range(DENSITY): mouse_pos = pygame.mouse.get_pos() pos_fin = (RADIUS * math.cos(2*math.pi / DENSITY * i) + mouse_pos[0], RADIUS * math.sin(2*math.pi / DENSITY * i) + mouse_pos[1]) if rect.collidepoint(mouse_pos) == False: for extrem_1, extrem_2 in [(rect.bottomright, rect.topright), (rect.topright, rect.topleft), (rect.topleft, rect.bottomleft), (rect.bottomleft, rect.bottomright)]: deno = (mouse_pos[0] - pos_fin[0]) * (extrem_1[1] - extrem_2[1]) - (mouse_pos[1] - pos_fin[1]) * (extrem_1[0] - extrem_2[0]) if deno != 0: param_1 = ((extrem_2[0] - mouse_pos[0]) * (mouse_pos[1] - pos_fin[1]) - (extrem_2[1] - mouse_pos[1]) * (mouse_pos[0] - pos_fin[0]))/deno param_2 = ((extrem_2[0] - mouse_pos[0]) * (extrem_2[1] - extrem_1[1]) - (extrem_2[1] - mouse_pos[1]) * (extrem_2[0] - extrem_1[0]))/deno if 0 <= param_1 <= 1 and 0 <= param_2 <= 1: p_x = mouse_pos[0] + param_2 * (pos_fin[0] - mouse_pos[0]) p_y = mouse_pos[1] + param_2 * (pos_fin[1] - mouse_pos[1]) pos_fin = (p_x, p_y) pygame.draw.aaline(screen, 'white', mouse_pos, pos_fin) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.display.update() pygame.quit() ``` It is maybe not the best, and most optimised piece of code but at the end you should get something that works.
56,100,559
I've migrated to `androidx` and after a ton of time with it, I can't move away from the error below. I've integrated `multidex` but I still get the error. This is the exception: > > FAILURE: Build failed with an exception. > > > > What went wrong: > > Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForBetaDebug'. > java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex > > > I can't make it work. Here's my build.gradle. Any ideas? ``` buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'io.fabric.tools:gradle:1.+' } } apply plugin: 'com.android.application' apply plugin: 'io.fabric' repositories { maven { url 'https://maven.fabric.io/public' } } android { compileSdkVersion 28 buildToolsVersion '27.0.3' signingConfigs { releaseSign { storeFile file("$rootProject.projectDir/keystore_release.jks") storePassword 'xxxxxxx' keyAlias 'xxxxxxx' keyPassword 'xxxxxxx' } } // Butterknife requires Java 8. compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "com.xxxxxxx.xxxxxxx" minSdkVersion 19 targetSdkVersion 28 versionCode 10 versionName "1.0.10" renderscriptTargetApi 19 renderscriptSupportModeEnabled true multiDexEnabled true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.releaseSign } } flavorDimensions "default" productFlavors { beta { applicationId "com.xxxxxxx.xxxxxxx.beta" dimension "default" resValue "string", "app_name", "xxxxxxx Beta" buildConfigField "String", "BASE_URL", '"http://xxxxxxx.net"' buildConfigField "Boolean", "IS_BETA", "true" buildConfigField "String", "TENANT", '"xxxxxxx"' } production { applicationId "com.xxxxxxx.driver" dimension "default" resValue "string", "app_name", "Driver" buildConfigField "String", "BASE_URL", '"http://apxxxxxxx"' buildConfigField "Boolean", "IS_BETA", "false" buildConfigField "String", "TENANT", '"xxxxxxx"' } } packagingOptions { exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/notice' exclude 'META-INF/notice.txt' exclude 'META-INF/license' exclude 'META-INF/license.txt' } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.1.0-alpha05' implementation 'androidx.cardview:cardview:1.0.0' implementation 'com.google.android.material:material:1.1.0-alpha06' implementation 'com.jakewharton:butterknife:10.1.0' annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0' implementation 'com.google.code.gson:gson:2.8.5' implementation 'me.grantland:autofittextview:0.2.1' implementation 'com.android.volley:volley:1.1.1' implementation 'org.greenrobot:eventbus:3.1.1' implementation 'com.github.ybq:Android-SpinKit:1.2.0' implementation 'com.google.android.gms:play-services-location:16.0.0' implementation 'com.crashlytics.sdk.android:crashlytics:2.10.0' implementation 'com.google.firebase:firebase-core:16.0.9' implementation 'com.google.firebase:firebase-messaging:18.0.0' implementation 'androidx.multidex:multidex:2.0.1' def work_version = "2.0.1" implementation "androidx.work:work-runtime:$work_version" // Optional - RxJava2 support implementation "androidx.work:work-rxjava2:$work_version" def futures_version = "1.0.0-beta01" implementation "androidx.concurrent:concurrent-futures:$futures_version" } apply plugin: 'com.google.gms.google-services' ```
2019/05/12
[ "https://Stackoverflow.com/questions/56100559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2064171/" ]
This is a great question! Your rectangle can be thought of as 4 lines: ``` (x, y) → (x+width, y) # top (x+width, y) → (x+width, y+height) # right (x, y+height) → (x+width, y+height) # bottom (x, y) → (x, y+height) # left ``` Taking your intersecting line, it's possible to use the [two-lines intersecting formula](https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection) to determine if any of these lines intersect (but be careful of parallel lines!) However the formula (specified in linked Wikipedia article) determines if the lines intersect anywhere on the 2D plane, so it needs to be further refined. Obviously the code can quickly throw away any intersections that occur outside the window dimensions. Once the "infinite-plane" collision-point has been determined (which is a reasonably quick determination), then a more fine-grained intersection can be determined. Using [Bresenham's algorithm](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm), enumerate all the points in the intersecting line, and compare them with a 1-pixel rectangle based on each side of your square. This will tell you which side of the rectangle intersected. If you only need to know if the rectangle was hit, just check the whole rectangle with `pygame.Rect.collidepoint()` for each point in the line. [![enter image description here](https://i.stack.imgur.com/47K0D.gif)](https://i.stack.imgur.com/47K0D.gif) Of course once you have all those points generated, it's easily to not bother with the 2D line collision, but for long lines the code must make a lot of checks. So testing the 2D intersection first really speeds it up.
The easiest way to detect the collision between a rectangle and a line is to use [`pygame.Rect.clipline`](https://www.pygame.org/docs/ref/rect.html#pygame.Rect.clipline): > > Returns the coordinates of a line that is cropped to be completely inside the rectangle. **If the line does not overlap the rectangle, then an empty tuple is returned.** > > > e.g.: ```py rect = pygme.Rect(x, y, width, height) if rect.clipline((x1, y1), (x2, y2)): print("hit") ``` --- Minimal example [![](https://i.stack.imgur.com/YrZKU.gif)](https://i.stack.imgur.com/YrZKU.gif) ```py import pygame pygame.init() window = pygame.display.set_mode((400, 400)) clock = pygame.time.Clock() rect = pygame.Rect(180, 180, 40, 40) speed = 5 lines = [((20, 300), (150, 20)), ((250, 20), (380, 250)), ((50, 350), (350, 300))] run = True while run: clock.tick(100) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * speed rect.centerx %= window.get_width() rect.centery %= window.get_height() color = "red" if any(rect.clipline(*line) for line in lines) else "green" window.fill(0) pygame.draw.rect(window, color, rect) for line in lines: pygame.draw.line(window, "white", *line) pygame.display.flip() pygame.quit() exit() ```
42,504
Ce [proverbe](http://www.linternaute.fr/proverbe/377/au-royaume-des-aveugles-les-borgnes-sont-rois/#:%7E:text=Au%20royaume%20des%20aveugles%2C%20les%20borgnes%20sont%20rois.%22&text=Entour%C3%A9%20de%20personnes%20ignorantes%20ou,intelligence%20passe%20pour%20un%20g%C3%A9nie.&text=Ce%20proverbe%20provient%20de%20la,par%20%C3%89rasme.) provient de la Grèce antique, et il est cité en français dès le XVIème s. par Érasme. Il signifie : > > Un médiocre paraît remarquable parmi des gens sans valeur ; > il est facile pour un ignorant de briller parmi de plus ignorants que lui ; > entouré de personnes ignorantes ou stupides, un individu doté d'un maigre savoir ou d'une maigre intelligence passe pour un génie ; etc. > > > Peut-on l'utiliser couramment ou son emploi est considéré non politiquement correct ? > > P.ex. : Dans une classe tous les élèves hormis un ont obtenu une note > inférieure à 11 en maths. La meilleure note est 12 sur 20. Peut-on > dire pour cet élève que "*au royaume des aveugles, le borgne est roi*" > ? > > >
2020/07/08
[ "https://french.stackexchange.com/questions/42504", "https://french.stackexchange.com", "https://french.stackexchange.com/users/16020/" ]
J’ai déjà entendu plusieurs fois cette expression et elle est pour moi toujours couramment utilisée, en tout cas comprise. En revanche, elle est effectivement politiquement peu correcte. Pour cela, je ne la vois être utilisée que dans certains cas : car (1) elle dénote toujours un certain sarcasme et (2) relève plutôt d’un style littéraire. Donc une manière de l’utiliser serait dans cet esprit : > > Dans une classe tous les élèves hormis un ont obtenu une note inférieure à 11 en maths. La meilleure note est 12 sur 20. X, qui a eu la meilleure note, est très heureux, même si sa note reste passable. Mais comme le proverbe le dit, **au royaume des aveugles, le borgne est roi**. > > >
As far as I understand there is also the old saying > > Leur savoir n’estoit que besterie et leur sapience n’estoit que moufles ([Rabelais](http://agora.qc.ca/documents/Francois_Rabelais--Leducation_selon_Rabelais_par_Gabriel_Compayre#:%7E:text=Car%20leur%20savoir%20n%27estoit,meilleur%20langagee%20que%20votre%20fils.)) > > > conveys also the same meaning. > > Leur savoir n'était que bêterie (bêtise) et leur sagesse n'était que moufle. > > > Voir <https://www.france-pittoresque.com/spip.php?article5169>
8,228,047
Well, I'm a linux newbie, and I'm having an issue with a simple bash script. I've got a program that adds to a log file while it's running. Over time that log file gets huge. I'd like to create a startup script which will rename and move the log file before each run, effectively creating separate log files for each run of the program. Here's what I've got so far: [pastebin](http://pastebin.com/mDVuSZ5k) ``` DATE=$(date +"%Y%m%d%H%M") mv server.log logs/$DATE.log echo program ``` When run, I see this: ``` : command not found program ``` When I cd to the logs directory and run dir, I see this: ``` 201111211437\r.log\r ``` What's going on? I'm assuming there's some syntax issue I'm missing, but I can't seem to figure it out. --- UPDATE: Thanks to shellter's comment below, I've found the problem to be due to the fact that I'm editing the .sh file in Notepad++ in windows, and then sending via ftp to the server, where I run the file via ssh. After running dos2unix on the file, it works. New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?
2011/11/22
[ "https://Stackoverflow.com/questions/8228047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023673/" ]
I use this command for simple rotate a file: ``` mv output.log `date +%F`-output.log ``` In local folder I have `2019-09-25-output.log`
First, thanks for the answers above! They lead to my solution. I added this alias to my .bashrc file: ``` alias now='date +%Y-%m-%d-%H.%M.%S' ``` Now when I want to put a time stamp on a file such as a build log I can do this: ``` mvn clean install | tee build-$(now).log ``` and I get a file name like: build-2021-02-04-03.12.12.log
8,228,047
Well, I'm a linux newbie, and I'm having an issue with a simple bash script. I've got a program that adds to a log file while it's running. Over time that log file gets huge. I'd like to create a startup script which will rename and move the log file before each run, effectively creating separate log files for each run of the program. Here's what I've got so far: [pastebin](http://pastebin.com/mDVuSZ5k) ``` DATE=$(date +"%Y%m%d%H%M") mv server.log logs/$DATE.log echo program ``` When run, I see this: ``` : command not found program ``` When I cd to the logs directory and run dir, I see this: ``` 201111211437\r.log\r ``` What's going on? I'm assuming there's some syntax issue I'm missing, but I can't seem to figure it out. --- UPDATE: Thanks to shellter's comment below, I've found the problem to be due to the fact that I'm editing the .sh file in Notepad++ in windows, and then sending via ftp to the server, where I run the file via ssh. After running dos2unix on the file, it works. New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?
2011/11/22
[ "https://Stackoverflow.com/questions/8228047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023673/" ]
``` mv server.log logs/$(date -d "today" +"%Y%m%d%H%M").log ```
Well, it's not a direct answer to your question, but there's a tool in GNU/Linux whose job is to rotate log files on regular basis, keeping old ones zipped up to a certain limit. It's `logrotate`
8,228,047
Well, I'm a linux newbie, and I'm having an issue with a simple bash script. I've got a program that adds to a log file while it's running. Over time that log file gets huge. I'd like to create a startup script which will rename and move the log file before each run, effectively creating separate log files for each run of the program. Here's what I've got so far: [pastebin](http://pastebin.com/mDVuSZ5k) ``` DATE=$(date +"%Y%m%d%H%M") mv server.log logs/$DATE.log echo program ``` When run, I see this: ``` : command not found program ``` When I cd to the logs directory and run dir, I see this: ``` 201111211437\r.log\r ``` What's going on? I'm assuming there's some syntax issue I'm missing, but I can't seem to figure it out. --- UPDATE: Thanks to shellter's comment below, I've found the problem to be due to the fact that I'm editing the .sh file in Notepad++ in windows, and then sending via ftp to the server, where I run the file via ssh. After running dos2unix on the file, it works. New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?
2011/11/22
[ "https://Stackoverflow.com/questions/8228047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023673/" ]
The few lines you posted from your script look okay to me. It's probably something a bit deeper. You need to find which line is giving you this error. Add `set -xv` to the top of your script. This will print out the line number and the command that's being executed to *STDERR*. This will help you identify where in your script you're getting this particular error. BTW, do you have a [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had `#! /bin/bash` on top, but your bash interpreter is located in `/usr/bin/bash`, you'll see this error. EDIT ==== > > New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file? > > > Two ways: 1. Select the *Edit->EOL Conversion->Unix Format* menu item when you edit a file. Once it has the correct line endings, Notepad++ will keep them. 2. To make sure all new files have the correct line endings, go to the *Settings->Preferences* menu item, and pull up the *Preferences* dialog box. Select the *New Document/Default Directory* tab. Under *New Document* and *Format*, select the *Unix* radio button. Click the *Close* button.
Well, it's not a direct answer to your question, but there's a tool in GNU/Linux whose job is to rotate log files on regular basis, keeping old ones zipped up to a certain limit. It's `logrotate`
8,228,047
Well, I'm a linux newbie, and I'm having an issue with a simple bash script. I've got a program that adds to a log file while it's running. Over time that log file gets huge. I'd like to create a startup script which will rename and move the log file before each run, effectively creating separate log files for each run of the program. Here's what I've got so far: [pastebin](http://pastebin.com/mDVuSZ5k) ``` DATE=$(date +"%Y%m%d%H%M") mv server.log logs/$DATE.log echo program ``` When run, I see this: ``` : command not found program ``` When I cd to the logs directory and run dir, I see this: ``` 201111211437\r.log\r ``` What's going on? I'm assuming there's some syntax issue I'm missing, but I can't seem to figure it out. --- UPDATE: Thanks to shellter's comment below, I've found the problem to be due to the fact that I'm editing the .sh file in Notepad++ in windows, and then sending via ftp to the server, where I run the file via ssh. After running dos2unix on the file, it works. New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?
2011/11/22
[ "https://Stackoverflow.com/questions/8228047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023673/" ]
A single line method within bash works like this. [some out put] >$(date "+%Y.%m.%d-%H.%M.%S").ver will create a file with a timestamp name with ver extension. A working file listing snap shot to a date stamp file name as follows can show it working. `find . -type f -exec ls -la {} \; | cut -d ' ' -f 6- >$(date "+%Y.%m.%d-%H.%M.%S").ver` Of course `cat somefile.log > $(date "+%Y.%m.%d-%H.%M.%S").ver` or even simpler `ls > $(date "+%Y.%m.%d-%H.%M.%S").ver`
Well, it's not a direct answer to your question, but there's a tool in GNU/Linux whose job is to rotate log files on regular basis, keeping old ones zipped up to a certain limit. It's `logrotate`
8,228,047
Well, I'm a linux newbie, and I'm having an issue with a simple bash script. I've got a program that adds to a log file while it's running. Over time that log file gets huge. I'd like to create a startup script which will rename and move the log file before each run, effectively creating separate log files for each run of the program. Here's what I've got so far: [pastebin](http://pastebin.com/mDVuSZ5k) ``` DATE=$(date +"%Y%m%d%H%M") mv server.log logs/$DATE.log echo program ``` When run, I see this: ``` : command not found program ``` When I cd to the logs directory and run dir, I see this: ``` 201111211437\r.log\r ``` What's going on? I'm assuming there's some syntax issue I'm missing, but I can't seem to figure it out. --- UPDATE: Thanks to shellter's comment below, I've found the problem to be due to the fact that I'm editing the .sh file in Notepad++ in windows, and then sending via ftp to the server, where I run the file via ssh. After running dos2unix on the file, it works. New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?
2011/11/22
[ "https://Stackoverflow.com/questions/8228047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023673/" ]
I use this command for simple rotate a file: ``` mv output.log `date +%F`-output.log ``` In local folder I have `2019-09-25-output.log`
You can write your scripts in notepad but just make sure you convert them using this -> $ sed -i 's/\r$//' yourscripthere I use it all they time when I'm working in cygwin and it works. Hope this helps
8,228,047
Well, I'm a linux newbie, and I'm having an issue with a simple bash script. I've got a program that adds to a log file while it's running. Over time that log file gets huge. I'd like to create a startup script which will rename and move the log file before each run, effectively creating separate log files for each run of the program. Here's what I've got so far: [pastebin](http://pastebin.com/mDVuSZ5k) ``` DATE=$(date +"%Y%m%d%H%M") mv server.log logs/$DATE.log echo program ``` When run, I see this: ``` : command not found program ``` When I cd to the logs directory and run dir, I see this: ``` 201111211437\r.log\r ``` What's going on? I'm assuming there's some syntax issue I'm missing, but I can't seem to figure it out. --- UPDATE: Thanks to shellter's comment below, I've found the problem to be due to the fact that I'm editing the .sh file in Notepad++ in windows, and then sending via ftp to the server, where I run the file via ssh. After running dos2unix on the file, it works. New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?
2011/11/22
[ "https://Stackoverflow.com/questions/8228047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023673/" ]
``` mv server.log logs/$(date -d "today" +"%Y%m%d%H%M").log ```
A single line method within bash works like this. [some out put] >$(date "+%Y.%m.%d-%H.%M.%S").ver will create a file with a timestamp name with ver extension. A working file listing snap shot to a date stamp file name as follows can show it working. `find . -type f -exec ls -la {} \; | cut -d ' ' -f 6- >$(date "+%Y.%m.%d-%H.%M.%S").ver` Of course `cat somefile.log > $(date "+%Y.%m.%d-%H.%M.%S").ver` or even simpler `ls > $(date "+%Y.%m.%d-%H.%M.%S").ver`
8,228,047
Well, I'm a linux newbie, and I'm having an issue with a simple bash script. I've got a program that adds to a log file while it's running. Over time that log file gets huge. I'd like to create a startup script which will rename and move the log file before each run, effectively creating separate log files for each run of the program. Here's what I've got so far: [pastebin](http://pastebin.com/mDVuSZ5k) ``` DATE=$(date +"%Y%m%d%H%M") mv server.log logs/$DATE.log echo program ``` When run, I see this: ``` : command not found program ``` When I cd to the logs directory and run dir, I see this: ``` 201111211437\r.log\r ``` What's going on? I'm assuming there's some syntax issue I'm missing, but I can't seem to figure it out. --- UPDATE: Thanks to shellter's comment below, I've found the problem to be due to the fact that I'm editing the .sh file in Notepad++ in windows, and then sending via ftp to the server, where I run the file via ssh. After running dos2unix on the file, it works. New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?
2011/11/22
[ "https://Stackoverflow.com/questions/8228047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023673/" ]
The few lines you posted from your script look okay to me. It's probably something a bit deeper. You need to find which line is giving you this error. Add `set -xv` to the top of your script. This will print out the line number and the command that's being executed to *STDERR*. This will help you identify where in your script you're getting this particular error. BTW, do you have a [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had `#! /bin/bash` on top, but your bash interpreter is located in `/usr/bin/bash`, you'll see this error. EDIT ==== > > New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file? > > > Two ways: 1. Select the *Edit->EOL Conversion->Unix Format* menu item when you edit a file. Once it has the correct line endings, Notepad++ will keep them. 2. To make sure all new files have the correct line endings, go to the *Settings->Preferences* menu item, and pull up the *Preferences* dialog box. Select the *New Document/Default Directory* tab. Under *New Document* and *Format*, select the *Unix* radio button. Click the *Close* button.
You can write your scripts in notepad but just make sure you convert them using this -> $ sed -i 's/\r$//' yourscripthere I use it all they time when I'm working in cygwin and it works. Hope this helps
8,228,047
Well, I'm a linux newbie, and I'm having an issue with a simple bash script. I've got a program that adds to a log file while it's running. Over time that log file gets huge. I'd like to create a startup script which will rename and move the log file before each run, effectively creating separate log files for each run of the program. Here's what I've got so far: [pastebin](http://pastebin.com/mDVuSZ5k) ``` DATE=$(date +"%Y%m%d%H%M") mv server.log logs/$DATE.log echo program ``` When run, I see this: ``` : command not found program ``` When I cd to the logs directory and run dir, I see this: ``` 201111211437\r.log\r ``` What's going on? I'm assuming there's some syntax issue I'm missing, but I can't seem to figure it out. --- UPDATE: Thanks to shellter's comment below, I've found the problem to be due to the fact that I'm editing the .sh file in Notepad++ in windows, and then sending via ftp to the server, where I run the file via ssh. After running dos2unix on the file, it works. New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?
2011/11/22
[ "https://Stackoverflow.com/questions/8228047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023673/" ]
``` mv server.log logs/$(date -d "today" +"%Y%m%d%H%M").log ```
The few lines you posted from your script look okay to me. It's probably something a bit deeper. You need to find which line is giving you this error. Add `set -xv` to the top of your script. This will print out the line number and the command that's being executed to *STDERR*. This will help you identify where in your script you're getting this particular error. BTW, do you have a [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had `#! /bin/bash` on top, but your bash interpreter is located in `/usr/bin/bash`, you'll see this error. EDIT ==== > > New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file? > > > Two ways: 1. Select the *Edit->EOL Conversion->Unix Format* menu item when you edit a file. Once it has the correct line endings, Notepad++ will keep them. 2. To make sure all new files have the correct line endings, go to the *Settings->Preferences* menu item, and pull up the *Preferences* dialog box. Select the *New Document/Default Directory* tab. Under *New Document* and *Format*, select the *Unix* radio button. Click the *Close* button.
8,228,047
Well, I'm a linux newbie, and I'm having an issue with a simple bash script. I've got a program that adds to a log file while it's running. Over time that log file gets huge. I'd like to create a startup script which will rename and move the log file before each run, effectively creating separate log files for each run of the program. Here's what I've got so far: [pastebin](http://pastebin.com/mDVuSZ5k) ``` DATE=$(date +"%Y%m%d%H%M") mv server.log logs/$DATE.log echo program ``` When run, I see this: ``` : command not found program ``` When I cd to the logs directory and run dir, I see this: ``` 201111211437\r.log\r ``` What's going on? I'm assuming there's some syntax issue I'm missing, but I can't seem to figure it out. --- UPDATE: Thanks to shellter's comment below, I've found the problem to be due to the fact that I'm editing the .sh file in Notepad++ in windows, and then sending via ftp to the server, where I run the file via ssh. After running dos2unix on the file, it works. New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?
2011/11/22
[ "https://Stackoverflow.com/questions/8228047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023673/" ]
The few lines you posted from your script look okay to me. It's probably something a bit deeper. You need to find which line is giving you this error. Add `set -xv` to the top of your script. This will print out the line number and the command that's being executed to *STDERR*. This will help you identify where in your script you're getting this particular error. BTW, do you have a [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had `#! /bin/bash` on top, but your bash interpreter is located in `/usr/bin/bash`, you'll see this error. EDIT ==== > > New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file? > > > Two ways: 1. Select the *Edit->EOL Conversion->Unix Format* menu item when you edit a file. Once it has the correct line endings, Notepad++ will keep them. 2. To make sure all new files have the correct line endings, go to the *Settings->Preferences* menu item, and pull up the *Preferences* dialog box. Select the *New Document/Default Directory* tab. Under *New Document* and *Format*, select the *Unix* radio button. Click the *Close* button.
First, thanks for the answers above! They lead to my solution. I added this alias to my .bashrc file: ``` alias now='date +%Y-%m-%d-%H.%M.%S' ``` Now when I want to put a time stamp on a file such as a build log I can do this: ``` mvn clean install | tee build-$(now).log ``` and I get a file name like: build-2021-02-04-03.12.12.log
8,228,047
Well, I'm a linux newbie, and I'm having an issue with a simple bash script. I've got a program that adds to a log file while it's running. Over time that log file gets huge. I'd like to create a startup script which will rename and move the log file before each run, effectively creating separate log files for each run of the program. Here's what I've got so far: [pastebin](http://pastebin.com/mDVuSZ5k) ``` DATE=$(date +"%Y%m%d%H%M") mv server.log logs/$DATE.log echo program ``` When run, I see this: ``` : command not found program ``` When I cd to the logs directory and run dir, I see this: ``` 201111211437\r.log\r ``` What's going on? I'm assuming there's some syntax issue I'm missing, but I can't seem to figure it out. --- UPDATE: Thanks to shellter's comment below, I've found the problem to be due to the fact that I'm editing the .sh file in Notepad++ in windows, and then sending via ftp to the server, where I run the file via ssh. After running dos2unix on the file, it works. New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?
2011/11/22
[ "https://Stackoverflow.com/questions/8228047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023673/" ]
``` mv server.log logs/$(date -d "today" +"%Y%m%d%H%M").log ```
First, thanks for the answers above! They lead to my solution. I added this alias to my .bashrc file: ``` alias now='date +%Y-%m-%d-%H.%M.%S' ``` Now when I want to put a time stamp on a file such as a build log I can do this: ``` mvn clean install | tee build-$(now).log ``` and I get a file name like: build-2021-02-04-03.12.12.log
34,372,419
I would like to make an ImageView ? AND WHEN i touch it it change background, when i drag finger far of it it become normal i don't know how to do, thanks ``` imgButton.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { cmp++; txt2.setText(" " + cmp); //Quant on touche l'image : if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { imgButton.getDrawable().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP); } // si Je bouge le dois sur l'image et .... if (event.getActionMasked() == MotionEvent.ACTION_MOVE) { //... et que le doit quitte l'image if (event.getX() < 0 || event.getX() > v.getWidth() || event.getY() < 0 || event.getY() > v.getHeight()) { imgButton.getDrawable().setColorFilter(0x00000001, PorterDuff.Mode.SRC_ATOP); } if (event.getX() > 0 && event.getX() < v.getWidth() && event.getY() > 0 && event.getY() < v.getHeight()) { // ... et que le doit revient vers L'image imgButton.getDrawable().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP); } } // Si je lève le doits et... if (event.getActionMasked() == MotionEvent.ACTION_UP) { // .... sur l'image : if (event.getX() > 0 && event.getX() < v.getWidth() && event.getY() > 0 && event.getY() < v.getHeight()) { //Finger back to the view imgButton.getDrawable().setColorFilter(0x00000001, PorterDuff.Mode.SRC_ATOP); Intent i = new Intent(MainActivity.this, game.class); startActivity(i); } } return true; } }); ```
2015/12/19
[ "https://Stackoverflow.com/questions/34372419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872660/" ]
You could go with `serverVersion`. But as you can see in the picture, you still get `Glassfish V3.1` with Glassfish 4.1. [![serverVersion screen](https://i.stack.imgur.com/WwqDv.png)](https://i.stack.imgur.com/WwqDv.png) Now, `ApplicationServerFullVersion` will bring better results: `GlassFish Server Open Source Edition 4.1 (build 13)` [![ApplicationServerFullVersion screen](https://i.stack.imgur.com/P0KNN.png)](https://i.stack.imgur.com/P0KNN.png)
If you want to get the GlassFish version from code not via JMX there is a Version class in package com.sun.appserv.server.util this has many version related methods; [See the source on GitHub](https://github.com/payara/Payara/blob/8a403bf75d3734e564a9fb95d60498987cc4287e/nucleus/common/common-util/src/main/java/com/sun/appserv/server/util/Version.java)
414,742
In [J.J. Sakurai's](https://en.wikipedia.org/wiki/J._J._Sakurai) *[Modern Quantum Mechanics](https://en.wikipedia.org/wiki/J._J._Sakurai#Textbooks)*, the same operator $X$ acts on both, elements of the [ket](https://en.wikipedia.org/wiki/Bra%E2%80%93ket_notation#Ket_notation) space and the [bra](https://en.wikipedia.org/wiki/Bra%E2%80%93ket_notation) space to produce elements of the ket and bra space, respectively. Mathematically, an operator is simply a map between two spaces. So, how can *the same operator* act on the ket as well as the bra space?
2018/07/02
[ "https://physics.stackexchange.com/questions/414742", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/170225/" ]
The action (to the right) on the ket space naturally induces an action (to the left) on the bra space. The bra space is the dual space of the ket space (that is the space of linear functionals over the kets). We can simply define $\left< \psi \right| X$ by its action on kets (or, since it's linear, on a basis of ket space and linear extension): $$ \big(\left< \psi \right| X\big) \left| \phi \right> := \left< \psi \right| \big( X \left| \phi \right>\big).$$ Such definitions are also common in pure mathematics. If you want to be pedantic, you can use some notation, e.g. $\iota(X)$, for die induced operator on the dual space.
Just think of the operator as a matrix (as per your "matrix-elements" tag). Then it operates to the right on a column-vector $\left|\mbox{ket}\right>$, and to the left on a row-vector $\left<\mbox{bra}\right|$
414,742
In [J.J. Sakurai's](https://en.wikipedia.org/wiki/J._J._Sakurai) *[Modern Quantum Mechanics](https://en.wikipedia.org/wiki/J._J._Sakurai#Textbooks)*, the same operator $X$ acts on both, elements of the [ket](https://en.wikipedia.org/wiki/Bra%E2%80%93ket_notation#Ket_notation) space and the [bra](https://en.wikipedia.org/wiki/Bra%E2%80%93ket_notation) space to produce elements of the ket and bra space, respectively. Mathematically, an operator is simply a map between two spaces. So, how can *the same operator* act on the ket as well as the bra space?
2018/07/02
[ "https://physics.stackexchange.com/questions/414742", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/170225/" ]
This is what computer scientists would call [(ad-hoc) polymorphic](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)) or “overloaded” functions: basically, an operator $X$ on the Hilbert space $\mathcal{H}$ is not just one function $X: \mathcal{H}\to\mathcal{H}$, but a family of two functions $$ X = \{ X\_{\mathcal{H}}, \quad X\_{\mathcal{H}^\ast} \} $$ with $$ X\_{\mathcal{H}}: \mathcal{H}\to\mathcal{H}, \quad X\_{\mathcal{H}^\ast}: \mathcal{H}^\ast\to\mathcal{H}^\ast $$ Since a Hilbert space's dual space (the “space of bra-vectors”) is a different space from $\mathcal{H}$ itself, it's always unambiguous which of the two functions you mean when applying $X$ to either a ket or a bra. And the definition of $X\_{\mathcal{H}^\ast}$ follows directly from the one of $X\_{\mathcal{H}}$ vice versa. This is easy to see in one direction: $$ \bigl(X\_{\mathcal{H}^\ast}(\langle f|)\bigr)(|v\rangle) = \langle f| \bigl(X\_\mathcal{H}(|v\rangle)\bigr) $$ In the other direction, we need to invoke the [Riesz representation theorem](https://en.wikipedia.org/wiki/Riesz_representation_theorem): for any $|v\rangle \in \mathcal{H}$, let $$\begin{align} \langle X\_v^\ast| & \in\mathcal{H}^\ast \\ \langle X\_v^\ast| &:= X\_{\mathcal{H}^\ast}\bigl(\langle . , v\rangle\bigr). \end{align}$$ where by $\langle . , v\rangle$ I mean the function $$\begin{align} v^\ast & \in \mathcal{H}^\ast \\ v^\ast(w) & := \langle w,v\rangle \end{align}$$ (This is now *not* an application of dual-vectors, but the actual scalar product that comes with the Hilbert space!) Then Riesz tells us that this corresponds to one unique element $X\_v\in\mathcal{H}$, so we can define $$ X\_{\mathcal H}(|v\rangle) := X\_v. $$ And because physicists are lazy (good trait, although some overdo it), they avoid all the “obvious” parentheses etc., and just assume the reader will know how the operator needs to be applied, which space it lives in, etc.. Swapping between a bra- and a ket-version of a state implicitly always invokes the Riesz representation theorem, but this is seldom talked about.
The action (to the right) on the ket space naturally induces an action (to the left) on the bra space. The bra space is the dual space of the ket space (that is the space of linear functionals over the kets). We can simply define $\left< \psi \right| X$ by its action on kets (or, since it's linear, on a basis of ket space and linear extension): $$ \big(\left< \psi \right| X\big) \left| \phi \right> := \left< \psi \right| \big( X \left| \phi \right>\big).$$ Such definitions are also common in pure mathematics. If you want to be pedantic, you can use some notation, e.g. $\iota(X)$, for die induced operator on the dual space.
414,742
In [J.J. Sakurai's](https://en.wikipedia.org/wiki/J._J._Sakurai) *[Modern Quantum Mechanics](https://en.wikipedia.org/wiki/J._J._Sakurai#Textbooks)*, the same operator $X$ acts on both, elements of the [ket](https://en.wikipedia.org/wiki/Bra%E2%80%93ket_notation#Ket_notation) space and the [bra](https://en.wikipedia.org/wiki/Bra%E2%80%93ket_notation) space to produce elements of the ket and bra space, respectively. Mathematically, an operator is simply a map between two spaces. So, how can *the same operator* act on the ket as well as the bra space?
2018/07/02
[ "https://physics.stackexchange.com/questions/414742", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/170225/" ]
This is what computer scientists would call [(ad-hoc) polymorphic](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)) or “overloaded” functions: basically, an operator $X$ on the Hilbert space $\mathcal{H}$ is not just one function $X: \mathcal{H}\to\mathcal{H}$, but a family of two functions $$ X = \{ X\_{\mathcal{H}}, \quad X\_{\mathcal{H}^\ast} \} $$ with $$ X\_{\mathcal{H}}: \mathcal{H}\to\mathcal{H}, \quad X\_{\mathcal{H}^\ast}: \mathcal{H}^\ast\to\mathcal{H}^\ast $$ Since a Hilbert space's dual space (the “space of bra-vectors”) is a different space from $\mathcal{H}$ itself, it's always unambiguous which of the two functions you mean when applying $X$ to either a ket or a bra. And the definition of $X\_{\mathcal{H}^\ast}$ follows directly from the one of $X\_{\mathcal{H}}$ vice versa. This is easy to see in one direction: $$ \bigl(X\_{\mathcal{H}^\ast}(\langle f|)\bigr)(|v\rangle) = \langle f| \bigl(X\_\mathcal{H}(|v\rangle)\bigr) $$ In the other direction, we need to invoke the [Riesz representation theorem](https://en.wikipedia.org/wiki/Riesz_representation_theorem): for any $|v\rangle \in \mathcal{H}$, let $$\begin{align} \langle X\_v^\ast| & \in\mathcal{H}^\ast \\ \langle X\_v^\ast| &:= X\_{\mathcal{H}^\ast}\bigl(\langle . , v\rangle\bigr). \end{align}$$ where by $\langle . , v\rangle$ I mean the function $$\begin{align} v^\ast & \in \mathcal{H}^\ast \\ v^\ast(w) & := \langle w,v\rangle \end{align}$$ (This is now *not* an application of dual-vectors, but the actual scalar product that comes with the Hilbert space!) Then Riesz tells us that this corresponds to one unique element $X\_v\in\mathcal{H}$, so we can define $$ X\_{\mathcal H}(|v\rangle) := X\_v. $$ And because physicists are lazy (good trait, although some overdo it), they avoid all the “obvious” parentheses etc., and just assume the reader will know how the operator needs to be applied, which space it lives in, etc.. Swapping between a bra- and a ket-version of a state implicitly always invokes the Riesz representation theorem, but this is seldom talked about.
Just think of the operator as a matrix (as per your "matrix-elements" tag). Then it operates to the right on a column-vector $\left|\mbox{ket}\right>$, and to the left on a row-vector $\left<\mbox{bra}\right|$
19,440,525
I have a bean whose business logic loads beans of a certain type from the ApplicationContext in order to process them. For my jUnit tests, I would like to create some dummy beans within my unit test class and see if my bean under test properly processes them. However, I am not sure what the best way to accomplish this is. If I just declare my inner class within my test class, Spring will not have it as part of its application context. I realize that I could inject my application context within my jUnit class, and then use appContext.registerPrototype() to add it, however, I thought there might be a cleaner way using annotations. I've tried to annotate the internal class with @Component, but not surprisingly, it did not work. ``` public class PatchEngineTest extends TestBase { @Component protected class Patch1 extends PatchBaseImpl implements Patch{ public void applyPatch() throws Exception { // does nothing } } @Autowired PatchRepository patchRepository; @Autowired Patch1 patch1; @Test public void test() { fail("Not yet implemented"); } } ``` Not surprisingly, I get the following error message: ``` Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ia.patch.PatchEngineTest$Patch1] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} ``` Is there any way of doing this?
2013/10/18
[ "https://Stackoverflow.com/questions/19440525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/827480/" ]
You need to make your inner class `static`; Spring can't instantiate a non-`static` inner class as a bean. If there really is a valid reason why it needs to be non-`static`, you could create it manually in an `@Bean` method.
I also met this problem, and below is my solution : ``` @RunWith(SpringRunner.class) @SpringBootTest @ComponentScan @ImportAutoConfiguration public class FooTest { @Component public static class Bar { } } ``` I used spring boot `2.1.4.RELEASE`
724,698
I have genuine windows 10 in my lappy. I tried to dual boot with Ubuntu but accidentally I replaced my windows with ubuntu. So now I have only ubuntu in my pc and I lost my genuine windows. How to get back my windows OS.I dont even have my back up image of my windows
2016/01/23
[ "https://askubuntu.com/questions/724698", "https://askubuntu.com", "https://askubuntu.com/users/496793/" ]
If you really deleted the Windows partition, Ubuntu is not going to get it back for you. Sorry. Not knowing if this computer originally came with Windows 10, I will make the assumption it's fairly new and did. You could post more info per <https://askubuntu.com/help/how-to-ask> :>) When you start there should be a recovery partition. Look for the option to choose a boot device, perhaps F12, hold that key down and see if a recovery partition is a choice for bootup. Some computers hide this info at the start, and it's manufacturer specific, so you should consult your computer manual, again we don't know what model you have. If you really overwrote everything then your best best is likely to contact the manufacturer. I am not aware that you can download windows 10 cold from the Internet. If for example you bought it from Best Buy or another retailer perhaps they can help. This is probably a question for a more Windows oriented StackExchange site like <https://superuser.com/> The only option that's relevant to askubuntu is that you could open a terminal window and run the command `fdisk -l` and see if there's still a recovery partition. If you are not familiar with Linux be very careful running fdisk, you should not need to use `sudo` to get this listing.
Download testdisk from : <http://www.cgsecurity.org/wiki/TestDisk_Download> unpack it, launch ubuntu from live, change to folder where testdisk was unpacked and run: ``` sudo ./testdisk_static ``` from program menu chose analyse and try to recover your partition This tutorial will help: <http://www.cgsecurity.org/wiki/TestDisk_Step_By_Step> It will be hard, or even not possible but worth to try.
148,438
My home’s A/C has an external circuit breaker. Do I need to switch it off for the winter?
2018/10/10
[ "https://diy.stackexchange.com/questions/148438", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/44694/" ]
There is no need to switch off the external breaker serving the outside condensing unit. I have never done so in 40 years at our house. I have never heard of anyone doing so, and I have never heard it recommended. In our installation the external box adjacent to the condensing unit contains a double pole switch, not a breaker, but I only shut this off to service the unit. However, my experience is in the relatively warm winters of Dallas, Texas.
No, you should not be doing that. It will have no advantage to switch it off. Many of the houses run for long time with external circuit breaker that is working along the HVAC system.
148,438
My home’s A/C has an external circuit breaker. Do I need to switch it off for the winter?
2018/10/10
[ "https://diy.stackexchange.com/questions/148438", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/44694/" ]
There is no need to switch off the external breaker serving the outside condensing unit. I have never done so in 40 years at our house. I have never heard of anyone doing so, and I have never heard it recommended. In our installation the external box adjacent to the condensing unit contains a double pole switch, not a breaker, but I only shut this off to service the unit. However, my experience is in the relatively warm winters of Dallas, Texas.
No, there's no benefit to it whatsoever. Also, on most split systems, the compressor is still in use when the heat is on. For split gas systems, they normally "steal" power from a leg on the compressor circuit to power the blower.
148,438
My home’s A/C has an external circuit breaker. Do I need to switch it off for the winter?
2018/10/10
[ "https://diy.stackexchange.com/questions/148438", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/44694/" ]
No, there's no benefit to it whatsoever. Also, on most split systems, the compressor is still in use when the heat is on. For split gas systems, they normally "steal" power from a leg on the compressor circuit to power the blower.
No, you should not be doing that. It will have no advantage to switch it off. Many of the houses run for long time with external circuit breaker that is working along the HVAC system.
29,619,208
I implement `GoogleApiClient` as bellow: ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` But in `onConnected` method I check mGoogleApiClient => value null. In this case I try to re-build googleApiClient but I get error: ``` java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0 ``` Please help me understand why mGoogleApiClient is sometimes NULL althought it's connected :|. (Notes. I checked all source code, I never set GoogleApiClient to NULL). Thanks! **Update** My problem now solved after I try use latest version of play-service. Thanks everybody for help.
2015/04/14
[ "https://Stackoverflow.com/questions/29619208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205503/" ]
I had the same problem. All I did to solve it is remove `.enableAutoManage(this, 0 /* clientId */, this)` because it just doesn't work properly from what I assumed. Then, override these methods in your activity: ``` @Override public void onStart() { super.onStart(); if (mGoogleApiClient != null) { mGoogleApiClient.connect(); } } @Override public void onStop() { if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } super.onStop(); } ``` Technically, that is what `.enableAutoManage(this, 0 /* clientId */, this)` was supposed to do, except that now, everything works as it should.
I think you'd better watch this reference. [reference page of "public GoogleApiClient.Builder enableAutoManage"](https://developer.android.com/reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html#enableAutoManage(android.support.v4.app.FragmentActivity,%20int,%20com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener)) In this page shows that, through IllegalStateException if clientId is already being auto-managed. So, check on your code with ``` .enableAutoManage(this, 0 /* clientId */, this) ``` I think if exception on your code, it could return zero as not completed.
29,619,208
I implement `GoogleApiClient` as bellow: ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` But in `onConnected` method I check mGoogleApiClient => value null. In this case I try to re-build googleApiClient but I get error: ``` java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0 ``` Please help me understand why mGoogleApiClient is sometimes NULL althought it's connected :|. (Notes. I checked all source code, I never set GoogleApiClient to NULL). Thanks! **Update** My problem now solved after I try use latest version of play-service. Thanks everybody for help.
2015/04/14
[ "https://Stackoverflow.com/questions/29619208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205503/" ]
I think you'd better watch this reference. [reference page of "public GoogleApiClient.Builder enableAutoManage"](https://developer.android.com/reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html#enableAutoManage(android.support.v4.app.FragmentActivity,%20int,%20com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener)) In this page shows that, through IllegalStateException if clientId is already being auto-managed. So, check on your code with ``` .enableAutoManage(this, 0 /* clientId */, this) ``` I think if exception on your code, it could return zero as not completed.
If u are facing this problem when u try to reinitialize mGoogleApiClient, then just remove `.enableAutoManage(this, 0 /* clientId */, this)` Use ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` and it will work fine
29,619,208
I implement `GoogleApiClient` as bellow: ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` But in `onConnected` method I check mGoogleApiClient => value null. In this case I try to re-build googleApiClient but I get error: ``` java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0 ``` Please help me understand why mGoogleApiClient is sometimes NULL althought it's connected :|. (Notes. I checked all source code, I never set GoogleApiClient to NULL). Thanks! **Update** My problem now solved after I try use latest version of play-service. Thanks everybody for help.
2015/04/14
[ "https://Stackoverflow.com/questions/29619208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205503/" ]
If u are facing this problem when u try to reinitialize mGoogleApiClient, then just remove `.enableAutoManage(this, 0 /* clientId */, this)` Use ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` and it will work fine
`build()` calls `onConnected` immediately if you are already connected. Therefore, your variable might be null. Better use ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this); mGoogleApiClient.build(); ```
29,619,208
I implement `GoogleApiClient` as bellow: ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` But in `onConnected` method I check mGoogleApiClient => value null. In this case I try to re-build googleApiClient but I get error: ``` java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0 ``` Please help me understand why mGoogleApiClient is sometimes NULL althought it's connected :|. (Notes. I checked all source code, I never set GoogleApiClient to NULL). Thanks! **Update** My problem now solved after I try use latest version of play-service. Thanks everybody for help.
2015/04/14
[ "https://Stackoverflow.com/questions/29619208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205503/" ]
[Documentation](https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.Builder) says: At any given time, only one auto-managed client is allowed per id. To reuse an id you must first call `stopAutoManage(FragmentActivity)` on the previous client. What I personally do is making a call to bellow method before I leave the activity, in which I am using the Google Api Client. ``` private void stopAutoManage() { if (mGoogleApiClient != null) mGoogleApiClient.stopAutoManage(mActivity); } ```
`build()` calls `onConnected` immediately if you are already connected. Therefore, your variable might be null. Better use ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this); mGoogleApiClient.build(); ```
29,619,208
I implement `GoogleApiClient` as bellow: ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` But in `onConnected` method I check mGoogleApiClient => value null. In this case I try to re-build googleApiClient but I get error: ``` java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0 ``` Please help me understand why mGoogleApiClient is sometimes NULL althought it's connected :|. (Notes. I checked all source code, I never set GoogleApiClient to NULL). Thanks! **Update** My problem now solved after I try use latest version of play-service. Thanks everybody for help.
2015/04/14
[ "https://Stackoverflow.com/questions/29619208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205503/" ]
I think you'd better watch this reference. [reference page of "public GoogleApiClient.Builder enableAutoManage"](https://developer.android.com/reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html#enableAutoManage(android.support.v4.app.FragmentActivity,%20int,%20com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener)) In this page shows that, through IllegalStateException if clientId is already being auto-managed. So, check on your code with ``` .enableAutoManage(this, 0 /* clientId */, this) ``` I think if exception on your code, it could return zero as not completed.
I had the same problem (Already managing a GoogleApiClient with id 0) in a fragment, and finally I resolved it : * Override `onStart()` and `onStop()` normally * Add in `onStop()` call `yourApiGoogle.stopAutoManage(context);` Have a nice day...
29,619,208
I implement `GoogleApiClient` as bellow: ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` But in `onConnected` method I check mGoogleApiClient => value null. In this case I try to re-build googleApiClient but I get error: ``` java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0 ``` Please help me understand why mGoogleApiClient is sometimes NULL althought it's connected :|. (Notes. I checked all source code, I never set GoogleApiClient to NULL). Thanks! **Update** My problem now solved after I try use latest version of play-service. Thanks everybody for help.
2015/04/14
[ "https://Stackoverflow.com/questions/29619208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205503/" ]
[Documentation](https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.Builder) says: At any given time, only one auto-managed client is allowed per id. To reuse an id you must first call `stopAutoManage(FragmentActivity)` on the previous client. What I personally do is making a call to bellow method before I leave the activity, in which I am using the Google Api Client. ``` private void stopAutoManage() { if (mGoogleApiClient != null) mGoogleApiClient.stopAutoManage(mActivity); } ```
I think you'd better watch this reference. [reference page of "public GoogleApiClient.Builder enableAutoManage"](https://developer.android.com/reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html#enableAutoManage(android.support.v4.app.FragmentActivity,%20int,%20com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener)) In this page shows that, through IllegalStateException if clientId is already being auto-managed. So, check on your code with ``` .enableAutoManage(this, 0 /* clientId */, this) ``` I think if exception on your code, it could return zero as not completed.
29,619,208
I implement `GoogleApiClient` as bellow: ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` But in `onConnected` method I check mGoogleApiClient => value null. In this case I try to re-build googleApiClient but I get error: ``` java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0 ``` Please help me understand why mGoogleApiClient is sometimes NULL althought it's connected :|. (Notes. I checked all source code, I never set GoogleApiClient to NULL). Thanks! **Update** My problem now solved after I try use latest version of play-service. Thanks everybody for help.
2015/04/14
[ "https://Stackoverflow.com/questions/29619208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205503/" ]
[Documentation](https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.Builder) says: At any given time, only one auto-managed client is allowed per id. To reuse an id you must first call `stopAutoManage(FragmentActivity)` on the previous client. What I personally do is making a call to bellow method before I leave the activity, in which I am using the Google Api Client. ``` private void stopAutoManage() { if (mGoogleApiClient != null) mGoogleApiClient.stopAutoManage(mActivity); } ```
If u are facing this problem when u try to reinitialize mGoogleApiClient, then just remove `.enableAutoManage(this, 0 /* clientId */, this)` Use ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` and it will work fine
29,619,208
I implement `GoogleApiClient` as bellow: ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` But in `onConnected` method I check mGoogleApiClient => value null. In this case I try to re-build googleApiClient but I get error: ``` java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0 ``` Please help me understand why mGoogleApiClient is sometimes NULL althought it's connected :|. (Notes. I checked all source code, I never set GoogleApiClient to NULL). Thanks! **Update** My problem now solved after I try use latest version of play-service. Thanks everybody for help.
2015/04/14
[ "https://Stackoverflow.com/questions/29619208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205503/" ]
I had the same problem. All I did to solve it is remove `.enableAutoManage(this, 0 /* clientId */, this)` because it just doesn't work properly from what I assumed. Then, override these methods in your activity: ``` @Override public void onStart() { super.onStart(); if (mGoogleApiClient != null) { mGoogleApiClient.connect(); } } @Override public void onStop() { if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } super.onStop(); } ``` Technically, that is what `.enableAutoManage(this, 0 /* clientId */, this)` was supposed to do, except that now, everything works as it should.
[Documentation](https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.Builder) says: At any given time, only one auto-managed client is allowed per id. To reuse an id you must first call `stopAutoManage(FragmentActivity)` on the previous client. What I personally do is making a call to bellow method before I leave the activity, in which I am using the Google Api Client. ``` private void stopAutoManage() { if (mGoogleApiClient != null) mGoogleApiClient.stopAutoManage(mActivity); } ```
29,619,208
I implement `GoogleApiClient` as bellow: ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` But in `onConnected` method I check mGoogleApiClient => value null. In this case I try to re-build googleApiClient but I get error: ``` java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0 ``` Please help me understand why mGoogleApiClient is sometimes NULL althought it's connected :|. (Notes. I checked all source code, I never set GoogleApiClient to NULL). Thanks! **Update** My problem now solved after I try use latest version of play-service. Thanks everybody for help.
2015/04/14
[ "https://Stackoverflow.com/questions/29619208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205503/" ]
I had the same problem. All I did to solve it is remove `.enableAutoManage(this, 0 /* clientId */, this)` because it just doesn't work properly from what I assumed. Then, override these methods in your activity: ``` @Override public void onStart() { super.onStart(); if (mGoogleApiClient != null) { mGoogleApiClient.connect(); } } @Override public void onStop() { if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } super.onStop(); } ``` Technically, that is what `.enableAutoManage(this, 0 /* clientId */, this)` was supposed to do, except that now, everything works as it should.
`build()` calls `onConnected` immediately if you are already connected. Therefore, your variable might be null. Better use ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this); mGoogleApiClient.build(); ```
29,619,208
I implement `GoogleApiClient` as bellow: ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this) .build(); ``` But in `onConnected` method I check mGoogleApiClient => value null. In this case I try to re-build googleApiClient but I get error: ``` java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0 ``` Please help me understand why mGoogleApiClient is sometimes NULL althought it's connected :|. (Notes. I checked all source code, I never set GoogleApiClient to NULL). Thanks! **Update** My problem now solved after I try use latest version of play-service. Thanks everybody for help.
2015/04/14
[ "https://Stackoverflow.com/questions/29619208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205503/" ]
I had the same problem (Already managing a GoogleApiClient with id 0) in a fragment, and finally I resolved it : * Override `onStart()` and `onStop()` normally * Add in `onStop()` call `yourApiGoogle.stopAutoManage(context);` Have a nice day...
`build()` calls `onConnected` immediately if you are already connected. Therefore, your variable might be null. Better use ``` mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, 0 /* clientId */, this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .addConnectionCallbacks(this); mGoogleApiClient.build(); ```
13,250,030
I'm using this CoverFlow : <http://www.inter-fuser.com/2010/02/android-coverflow-widget-v2.html> I want to be able to change View when I click on a button, the button being a back/forward icon which will take you to the previous/next item in the coverflow. I have modded the coverflow slightly so that I use an XML layout instead. Here is my onCreate() method: ``` setContentView(R.layout.main); CoverFlow coverFlow = (CoverFlow)findViewById(R.id.coverflow); coverFlow.setAdapter(new ImageAdapter(this)); ImageAdapter coverImageAdapter = new ImageAdapter(this); coverFlow.setAdapter(coverImageAdapter); coverFlow.setSpacing(-20); coverFlow.setSelection(0, true); coverFlow.setAnimationDuration(1000); tv = (TextView)findViewById(R.id.textView1); coverFlow.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Toast.makeText(getBaseContext(), String.valueOf(arg2), Toast.LENGTH_SHORT).show(); } }); coverFlow.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { tv.setText(String.valueOf(arg2)); } @Override public void onNothingSelected(AdapterView<?> arg0) { // Do something } }); ``` My XML: ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/home_background" android:orientation="vertical" > <com.demo.app.coverflow.CoverFlow android:id="@+id/coverflow" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_marginBottom="39dp" android:layout_marginLeft="35dp" android:background="@drawable/button_left" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_marginBottom="39dp" android:layout_marginRight="35dp" android:background="@drawable/button_right" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="55dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="hello" android:textColor="@color/White" android:textSize="16dp" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_marginRight="170dp" android:layout_marginTop="15dp" android:src="@drawable/unsa_logo" /> <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginRight="14dp" android:layout_marginTop="23dp" android:src="@drawable/pnc_logo" /> </RelativeLayout> ```
2012/11/06
[ "https://Stackoverflow.com/questions/13250030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067944/" ]
While I was trying to find out how to add the animation I came across this which does everything in just one line : go left `coverFlow.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(0, 0));` go right `coverFlow.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(0, 0));` (just add each line to their respective button onclick methods Hope this can help anyone else who finds them self in the same situation as I was :)
I hope i understand your question. if so, here's an idea: you need to store a private instance variable that tracks the current position of the image that is being displayed from the coverflow. then, you update it from the `setOnItemSelectedListener()` method, which is inherited from Gallery. On the "back" or "forward" button, you simply set your current selection +/- 1 depending on the button pressed. so in your Activity, add an instance variable int that will keep track of position like... ``` public class MyActivity { private int currentImagePosition = -1; //add the rest of your onCreate code here... } ``` Next, you need to be able to update the current position of the image that is currently being displayed in the coverflow. you can do so by overriding `setOnItemSelectedListener` like so (inside your onCreate method): ``` coverFlow.setOnItemSelectedListener(new OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { currentImagePosition = position; //this will update your current marker } }; ``` Lastly, all you have to do is set each button's onclick listeners to change to the previous or next image by using `setSelection( currentImagePosition+1 )` or `setSelection( currentImagePosition-1 )`. By the way, what's the true or false parameter of `setSelection()` do? i'm not sure what it does so i'm just going to use `true` like you did initially. your `onCreate()` method will now look something like: ``` @Override public void onCreate(Bundle savedInstanceState){ //insert your other code in onCreate here in this spot.... //add the following lines to your code: Button goLeft = (Button) findViewById(R.id.button1); goLeft.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { //go to previous image if( currentImagePosition > 0 ){ //i'm assuming you dont want to go left anymore once at the leftmost image coverFlow.setSelection(currentImagePosition - 1, true); } } } ) ; Button goRight = (Button) findViewById(R.id.button2); goRight.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { //go to previous image if( currentImagePosition < coverFlow.getCount()-1 ){ //i'm assuming you dont want to go left anymore once at the leftmost image coverFlow.setSelection(currentImagePosition + 1, true); } } } ) ; } ``` NOTE: the part about updating position is assumed to work from reading [Get the position of the current image displayed in Gallery](https://stackoverflow.com/questions/5994181/get-the-position-of-the-current-image-displayed-in-gallery) so i hope this works. if not, at least i tried :D Good luck!!!
13,250,030
I'm using this CoverFlow : <http://www.inter-fuser.com/2010/02/android-coverflow-widget-v2.html> I want to be able to change View when I click on a button, the button being a back/forward icon which will take you to the previous/next item in the coverflow. I have modded the coverflow slightly so that I use an XML layout instead. Here is my onCreate() method: ``` setContentView(R.layout.main); CoverFlow coverFlow = (CoverFlow)findViewById(R.id.coverflow); coverFlow.setAdapter(new ImageAdapter(this)); ImageAdapter coverImageAdapter = new ImageAdapter(this); coverFlow.setAdapter(coverImageAdapter); coverFlow.setSpacing(-20); coverFlow.setSelection(0, true); coverFlow.setAnimationDuration(1000); tv = (TextView)findViewById(R.id.textView1); coverFlow.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Toast.makeText(getBaseContext(), String.valueOf(arg2), Toast.LENGTH_SHORT).show(); } }); coverFlow.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { tv.setText(String.valueOf(arg2)); } @Override public void onNothingSelected(AdapterView<?> arg0) { // Do something } }); ``` My XML: ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/home_background" android:orientation="vertical" > <com.demo.app.coverflow.CoverFlow android:id="@+id/coverflow" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_marginBottom="39dp" android:layout_marginLeft="35dp" android:background="@drawable/button_left" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_marginBottom="39dp" android:layout_marginRight="35dp" android:background="@drawable/button_right" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="55dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="hello" android:textColor="@color/White" android:textSize="16dp" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_marginRight="170dp" android:layout_marginTop="15dp" android:src="@drawable/unsa_logo" /> <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginRight="14dp" android:layout_marginTop="23dp" android:src="@drawable/pnc_logo" /> </RelativeLayout> ```
2012/11/06
[ "https://Stackoverflow.com/questions/13250030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067944/" ]
While I was trying to find out how to add the animation I came across this which does everything in just one line : go left `coverFlow.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(0, 0));` go right `coverFlow.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(0, 0));` (just add each line to their respective button onclick methods Hope this can help anyone else who finds them self in the same situation as I was :)
Thanks David, I'm one of the Mike colleagues but I've never written a line of Java. I work in the iOS department of our company. I understood what you were talking about. Your answer was helpful and well written! I just had to add : ``` if ( currentimageposition < coverFlow.getcount()-1) { coverFlow.setSelection(currentImagePosition +1, true); currentImagePosition = currentImagePosition +1; } ``` Because your onItemSelected was not called (update the current marker), I don't know why. However, `coverFlow.selection( int , bool)` is not animated. It is just a set method when the view is loaded. For example, `coverFlow.selection(3,true)` will set the fourth image on the center of the coverflow.
32,537,729
I installed libsql-translator-perl on Ubuntu 15.04 and ran it with ``` sqlt -f SQLite -t MySql /tmp/test.sql /tmp/out.sql ``` test.sql contains only this: ``` CREATE TABLE X (id INTEGER); ``` It failed with ``` Use of uninitialized value $name in pattern match (m//) at /usr/share/perl5/SQL/Translator.pm line 610. ``` I looked at this file, it contains ``` sub load { my $name = shift; my @path; push @path, "" if $name =~ /::/; # error here ``` The call stack shows that it was called with ``` SQL::Translator::load(undef, 'SQL::Translator::Producer') ``` from here ``` sub _load_sub { my ($tool, @path) = @_; my (undef,$module,$func_name) = $tool =~ m/((.*)::)?(\w+)$/; if ( my $module = load($module => @path) ) { # <<<<<<< my $sub = "$module\::$func_name"; return wantarray ? ( \&{ $sub }, $sub ) : \&$sub; } return undef; } ``` I don't know enough Perl to unpick this any further. Does anyone know what might be going on? Thanks.
2015/09/12
[ "https://Stackoverflow.com/questions/32537729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/458742/" ]
The error message tells you that `$name` is undefined; it is set to the first argument, i.e. the value of `$module` in `_load_sub`, which is set to the second captured match in `m/((.*)::)?(\w+)$/`: everything in the value of `$tool` before the first occurrence of `::`, if `::` occurs, and undefined otherwise. So `$tool` does not contain the string `::`; the matching pattern accounts for this (by including the `?` metacharacter), but the code in `load` doesn't. Looks like a bug in the code. [The documentation](http://search.cpan.org/~ilmari/SQL-Translator-0.11021/lib/SQL/Translator.pm) lists several ways to report this or verify whether this has been reported or fixed before. You can debug Perl code by running it with `perl -d` - see [its manual](http://perldoc.perl.org/perldebug.html).
The SQL::Translator parser for MySQL is called "MySQL", not "MySql". ``` sqlt -f SQLite -t MySQL /tmp/test.sql /tmp/out.sql ``` Running `sqlt -l` will give you a complete list of the parsers available. But I certainly agree that the error message could be better. It's worth raising a bug against this.
32,506,415
I'm trying to load google font to my webapp (angular based but not relevant) and I'm getting this error: ``` Failed to decode downloaded font: https://fonts.googleapis.com/css?family=Open+Sans ``` The relevant part of my webpack.config.js is: ``` loaders: [ {test: /\.less$/, loader: "style!css!less", exclude: /node_modules|bower_components/}, {test: /\.woff(2)$/, loader: "url?limit=10000&minetype=application/font-woff"} ] ``` and my style.less is: ``` @font-face { font-family: "myFont"; font-style: normal; src: url(https://fonts.googleapis.com/css?family=Open+Sans); } body { font-family: "myFont"; } ``` My guess is that it is not really related to the webpack part but the font inclusion itself. Unfortunately I lack the knowledge to figure out where exactly is the problem.
2015/09/10
[ "https://Stackoverflow.com/questions/32506415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4470201/" ]
I'd suggest you have a look at this article by Paul Irish from 2009 named [Bulletproof @font-face syntax](http://www.paulirish.com/2009/bulletproof-font-face-implementation-syntax/) It explains very well and in all detail how to get webfonts up and running across all (or at least all capable) browsers.
Another way is to use `link` tag to load the CSS. Then define the font in custom CSS. Example: ``` <link href='http://fonts.googleapis.com/css?family=Abel' rel='stylesheet' type='text/css'> <style type="text/css"> body { font-family:'Abel',Sans; } </style> ```
15,746,542
I have a problem with sorting my sentence values ​​in descending order: I typed this command in unix: ``` sort fileInput -t"(" -k2r >fileSort ``` Here's the input file: ``` comité de conciliation de décision du parlement européen et du (0.00098379) les amendements CARD CARD CARD CARD CARD CARD et CARD (-0.00025165) la protection des consommateurs sur la proposition de directive du (0.00077120) ``` and here's the output file: ``` comité de conciliation de décision du parlement européen et du (0.00098379) les amendements CARD CARD CARD CARD CARD CARD et CARD (-0.00025165) la protection des consommateurs sur la proposition de directive du (0.00077120) ``` The file is not well sorted Any idea please?
2013/04/01
[ "https://Stackoverflow.com/questions/15746542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2215112/" ]
Add `-n` and `-g` options for numeric sort like this: ``` sort -t"(" -ngk2r ```
use -rk2 instead of -k2r, that is ``` sort fileInput -t"(" -k2r >fileSort ```
1,003,201
Is there a way to list runtime-only (i.e. no `--permanent`) changes in firewalld? I would like to see a diff in my configuration to make sure no change will get lost in case of a `--reload`.
2020/02/15
[ "https://serverfault.com/questions/1003201", "https://serverfault.com", "https://serverfault.com/users/364632/" ]
as far as I can see no tool that offers you that possibility, but you can create it yourself. I add a runtime acl to port 54/tcp: ``` # firewall-cmd --add-port=54/tcp ``` Then I can save the runtime rules to a file: ``` # firewall-cmd --list-all > /tmp/runtime_rules ``` And I save the permanent rules to another file: ``` # firewall-cmd --list-all --permanent > /tmp/permanent_rules ``` Finally I use diff to compare both ``` # diff /tmp/runtime_rules /tmp/permanent_rules 1c1 < FedoraWorkstation (active) --- > FedoraWorkstation 4c4 < interfaces: wlp2s0 --- > interfaces: 7c7 < ports: 1025-65535/udp 1025-65535/tcp 54/tcp --- > ports: 1025-65535/udp 1025-65535/tcp ``` And there you have the port I added on the runtime rules, not on the permanent one.
I'd like to propose a one-liner alternative usable in a bash shell: ```sh diff -u <(firewall-cmd --list-all --permanent) <(firewall-cmd --list-all) ``` ``` --- /dev/fd/63 2022-02-20 14:05:38.106385643 +0000 +++ /dev/fd/62 2022-02-20 14:05:38.110385485 +0000 @@ -3,7 +3,7 @@ icmp-block-inversion: no interfaces: eno0 sources: - services: dhcpv6-client ssh + services: dhcpv6-client http https ssh ports: protocols: forward: no ``` Lines prefixed with `-` are in the permanent config. Those with `+` are in the live configuration.