qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
10,563,177
I am trying to search if char from alpabet array is equal to the textCharArray's element. And if so do some math: char number from alphabet to add to arrayList value. But I getting an error: **java.lang.ArrayIndexOutOfBoundsException** The problem should be in for cicles. But I don't know how to fix it corectly. The Code: ``` outputText.setText(""); inputTextString = inputText.getText().toString().replace(" ", ""); //panaikinami tarpa char[] textCharArray = inputTextString.toCharArray(); //seka paverciama char masyvu int l = textCharArray.length; char[] alphabet = {'A','B','C','D','E','F','G','H','I','K','L','M','N','O','P','Q','R','S','T','V','X','Y','Z'}; int alpLenght = alphabet.length; System.out.println(alpLenght); stringKey = inputKey.getText().toString(); int k = Integer.parseInt(stringKey); List<Integer>keyList = new ArrayList<Integer>(); while(k > 0){ keyList.add(k%10); k = k /10; } Collections.reverse(keyList); int j = 0; int temp; for(int i = 0; i <= l; i++){ for(int ii = 0; ii < alpLenght; i++){ if(j < keyList.size()){ if(textCharArray[i] == alphabet[ii]){ temp = ii + keyList.get(j); System.out.println("Uzkoduotas: " + temp); } j++; } else { j = 0; if(textCharArray[i] == alphabet[ii]){ temp = ii + keyList.get(j); System.out.println("Uzkoduotas: " + temp); } } j++; } ```
2012/05/12
[ "https://Stackoverflow.com/questions/10563177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1319195/" ]
I would recommend reading the [PythonSoftwareFoundationFAQ](http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq#If_I_bundle_Python_with_my_application.2C_what_do_I_need_to_include_in_my_software_and.2BAC8-or_printed_documentation.3F). This is probably what you are looking for: > > You must retain all copyright notices found in the code you are redistributing and include a copy of the PSF License and all of the other licenses in the Python "license stack" with the software distribution. The "license stack" is a result of the history of Python's development as described here (this page also lists all licenses in the stack). > > >
I'm not a lawyer, but just on common sense I'm pretty sure that when you're distributing a big collection of copyrighted documents covered by numerous licenses that you would have to clearly communicate what licenses cover what documents in order for the licensees to know what license conditions they have to adhere to. i.e. It seems ridiculous to suppose you could distribute a big blob of code and say "some of this is covered by the GPL, some is public domain, and some is covered by a proprietary license" without saying which is which. If you did, someone could then use some of your proprietary code as if it were public domain, and make the argument that they believed in good faith that it was public domain based on your information.
3,992,187
An example of what I'm talking about is similar to Google Calendar. When a new recurring task is created. After creating the recurring task "template" - which all of the individual tasks are based on, do you create all of the individual tasks and store them in the database? or do you just store the "template" recurring events and their exceptions? If the user requests a "month" view, and you want to display all of the events/tasks, it seems like creating the output in real time from the template, and including all of the exceptions would be a lot more resource intensive then if each individual recurring tasks was created from the template and inserted into the database. This would make searching/sorting, etc, a lot more easier too. Anybody create something like this before? ideas?
2010/10/21
[ "https://Stackoverflow.com/questions/3992187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367657/" ]
I went through the same problem a while back and instead of reinventing the wheel, I used Google Calendar APIs. (http://code.google.com/apis/calendar/data/2.0/developers\_guide.html) You create a Google Account and access the calendar information. There are APIs to create/edit/delete a recurring entry. Also, you can specify a date/time information and query for matching events. When you create an event on Google Calendar, you will receive a token/id which you can store in your own database and reference it within the context of the application.
> > If the user requests a "month" view, and you want to display all of the events/tasks, it seems like creating the output in real time from the template, and including all of the exceptions would be a lot more resource intensive then if each individual recurring tasks was created from the template and inserted into the database. > > > I would disagree on that. What if a task repeats every saturday for the next 7 years... And what if there were a lot of these repeating tasks? That would cost you a lot of waste space. Therefor, I think it's better to save a recurring task as just one record + one record for every exception (since there are less exceptions than recurrences). Well, the only problem left is how to set up a query to select each task (still thinking abou that)
3,992,187
An example of what I'm talking about is similar to Google Calendar. When a new recurring task is created. After creating the recurring task "template" - which all of the individual tasks are based on, do you create all of the individual tasks and store them in the database? or do you just store the "template" recurring events and their exceptions? If the user requests a "month" view, and you want to display all of the events/tasks, it seems like creating the output in real time from the template, and including all of the exceptions would be a lot more resource intensive then if each individual recurring tasks was created from the template and inserted into the database. This would make searching/sorting, etc, a lot more easier too. Anybody create something like this before? ideas?
2010/10/21
[ "https://Stackoverflow.com/questions/3992187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367657/" ]
Store it all in the database. You want to have a "Task Template" table and a "Task" table where there is a one->many relationship. When the user indicates they want a task to reoccur, create a "Task Template" record and then create as many "Tasks" as the user has indicated (don't allow a user to create tasks too far into the future). Each Task is linked to the Task Template via a Foreign Key. The idea is that SQL is going to be more efficient at managing these records than trying to do this all in code based on one template. This way, you will have more option when your sorting and filtering your data. After all, writing a SQL query is easier than writing, testing, and maintaining a PHP function that manipulates the data. Some other tips I would give you is: * Try to get a lot of information in your "Task Template" record. Keep the number of tasks the Template covers, the date the last task ends, the time elapsed between the first task and the last, etc.. This "Meta Data" can help save you query time when you're looking to sort and filter tasks. * Put an index on the Date and FK field, this will help query time as well. * I just built two calendar apps at work that were pretty well received by the bosses. I used the "FullCalendar" JQuery plugin (http://arshaw.com/fullcalendar/). I used JQuery AJAX to handle most of my events, and it had built in support for Month, Day, and Week view.
> > If the user requests a "month" view, and you want to display all of the events/tasks, it seems like creating the output in real time from the template, and including all of the exceptions would be a lot more resource intensive then if each individual recurring tasks was created from the template and inserted into the database. > > > I would disagree on that. What if a task repeats every saturday for the next 7 years... And what if there were a lot of these repeating tasks? That would cost you a lot of waste space. Therefor, I think it's better to save a recurring task as just one record + one record for every exception (since there are less exceptions than recurrences). Well, the only problem left is how to set up a query to select each task (still thinking abou that)
3,992,187
An example of what I'm talking about is similar to Google Calendar. When a new recurring task is created. After creating the recurring task "template" - which all of the individual tasks are based on, do you create all of the individual tasks and store them in the database? or do you just store the "template" recurring events and their exceptions? If the user requests a "month" view, and you want to display all of the events/tasks, it seems like creating the output in real time from the template, and including all of the exceptions would be a lot more resource intensive then if each individual recurring tasks was created from the template and inserted into the database. This would make searching/sorting, etc, a lot more easier too. Anybody create something like this before? ideas?
2010/10/21
[ "https://Stackoverflow.com/questions/3992187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367657/" ]
For recurring events I did the following a while back: 1. When a user entered an event I stored the event's date pattern GNU date style - the keyword for PHP is [relative date formats](http://www.php.net/manual/de/datetime.formats.relative.php). 2. Then I started off by creating events for e.g. the next year. And created actual records where I converted the relative date to an actual -- e.g. "every first Monday" to a "mm-dd-YYYY". This allowed me to display them and also allow the user to e.g. move a single event or cancel one, etc.. 3. Then figure out how far to go into the future - my idea was to create events when the actual pages were browsed. E.g. if I had created events through June 2011 and someone skipped all the way to July 2011, I would iterate on my events and set them up transparently. 4. When the user changes the relative pattern, offer to update all following events -- unless they have a custom pattern already. Relative patterns make it super easy to calculate all that.
> > If the user requests a "month" view, and you want to display all of the events/tasks, it seems like creating the output in real time from the template, and including all of the exceptions would be a lot more resource intensive then if each individual recurring tasks was created from the template and inserted into the database. > > > I would disagree on that. What if a task repeats every saturday for the next 7 years... And what if there were a lot of these repeating tasks? That would cost you a lot of waste space. Therefor, I think it's better to save a recurring task as just one record + one record for every exception (since there are less exceptions than recurrences). Well, the only problem left is how to set up a query to select each task (still thinking abou that)
3,992,187
An example of what I'm talking about is similar to Google Calendar. When a new recurring task is created. After creating the recurring task "template" - which all of the individual tasks are based on, do you create all of the individual tasks and store them in the database? or do you just store the "template" recurring events and their exceptions? If the user requests a "month" view, and you want to display all of the events/tasks, it seems like creating the output in real time from the template, and including all of the exceptions would be a lot more resource intensive then if each individual recurring tasks was created from the template and inserted into the database. This would make searching/sorting, etc, a lot more easier too. Anybody create something like this before? ideas?
2010/10/21
[ "https://Stackoverflow.com/questions/3992187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367657/" ]
Store it all in the database. You want to have a "Task Template" table and a "Task" table where there is a one->many relationship. When the user indicates they want a task to reoccur, create a "Task Template" record and then create as many "Tasks" as the user has indicated (don't allow a user to create tasks too far into the future). Each Task is linked to the Task Template via a Foreign Key. The idea is that SQL is going to be more efficient at managing these records than trying to do this all in code based on one template. This way, you will have more option when your sorting and filtering your data. After all, writing a SQL query is easier than writing, testing, and maintaining a PHP function that manipulates the data. Some other tips I would give you is: * Try to get a lot of information in your "Task Template" record. Keep the number of tasks the Template covers, the date the last task ends, the time elapsed between the first task and the last, etc.. This "Meta Data" can help save you query time when you're looking to sort and filter tasks. * Put an index on the Date and FK field, this will help query time as well. * I just built two calendar apps at work that were pretty well received by the bosses. I used the "FullCalendar" JQuery plugin (http://arshaw.com/fullcalendar/). I used JQuery AJAX to handle most of my events, and it had built in support for Month, Day, and Week view.
I went through the same problem a while back and instead of reinventing the wheel, I used Google Calendar APIs. (http://code.google.com/apis/calendar/data/2.0/developers\_guide.html) You create a Google Account and access the calendar information. There are APIs to create/edit/delete a recurring entry. Also, you can specify a date/time information and query for matching events. When you create an event on Google Calendar, you will receive a token/id which you can store in your own database and reference it within the context of the application.
3,992,187
An example of what I'm talking about is similar to Google Calendar. When a new recurring task is created. After creating the recurring task "template" - which all of the individual tasks are based on, do you create all of the individual tasks and store them in the database? or do you just store the "template" recurring events and their exceptions? If the user requests a "month" view, and you want to display all of the events/tasks, it seems like creating the output in real time from the template, and including all of the exceptions would be a lot more resource intensive then if each individual recurring tasks was created from the template and inserted into the database. This would make searching/sorting, etc, a lot more easier too. Anybody create something like this before? ideas?
2010/10/21
[ "https://Stackoverflow.com/questions/3992187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367657/" ]
For recurring events I did the following a while back: 1. When a user entered an event I stored the event's date pattern GNU date style - the keyword for PHP is [relative date formats](http://www.php.net/manual/de/datetime.formats.relative.php). 2. Then I started off by creating events for e.g. the next year. And created actual records where I converted the relative date to an actual -- e.g. "every first Monday" to a "mm-dd-YYYY". This allowed me to display them and also allow the user to e.g. move a single event or cancel one, etc.. 3. Then figure out how far to go into the future - my idea was to create events when the actual pages were browsed. E.g. if I had created events through June 2011 and someone skipped all the way to July 2011, I would iterate on my events and set them up transparently. 4. When the user changes the relative pattern, offer to update all following events -- unless they have a custom pattern already. Relative patterns make it super easy to calculate all that.
I went through the same problem a while back and instead of reinventing the wheel, I used Google Calendar APIs. (http://code.google.com/apis/calendar/data/2.0/developers\_guide.html) You create a Google Account and access the calendar information. There are APIs to create/edit/delete a recurring entry. Also, you can specify a date/time information and query for matching events. When you create an event on Google Calendar, you will receive a token/id which you can store in your own database and reference it within the context of the application.
3,992,187
An example of what I'm talking about is similar to Google Calendar. When a new recurring task is created. After creating the recurring task "template" - which all of the individual tasks are based on, do you create all of the individual tasks and store them in the database? or do you just store the "template" recurring events and their exceptions? If the user requests a "month" view, and you want to display all of the events/tasks, it seems like creating the output in real time from the template, and including all of the exceptions would be a lot more resource intensive then if each individual recurring tasks was created from the template and inserted into the database. This would make searching/sorting, etc, a lot more easier too. Anybody create something like this before? ideas?
2010/10/21
[ "https://Stackoverflow.com/questions/3992187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367657/" ]
Store it all in the database. You want to have a "Task Template" table and a "Task" table where there is a one->many relationship. When the user indicates they want a task to reoccur, create a "Task Template" record and then create as many "Tasks" as the user has indicated (don't allow a user to create tasks too far into the future). Each Task is linked to the Task Template via a Foreign Key. The idea is that SQL is going to be more efficient at managing these records than trying to do this all in code based on one template. This way, you will have more option when your sorting and filtering your data. After all, writing a SQL query is easier than writing, testing, and maintaining a PHP function that manipulates the data. Some other tips I would give you is: * Try to get a lot of information in your "Task Template" record. Keep the number of tasks the Template covers, the date the last task ends, the time elapsed between the first task and the last, etc.. This "Meta Data" can help save you query time when you're looking to sort and filter tasks. * Put an index on the Date and FK field, this will help query time as well. * I just built two calendar apps at work that were pretty well received by the bosses. I used the "FullCalendar" JQuery plugin (http://arshaw.com/fullcalendar/). I used JQuery AJAX to handle most of my events, and it had built in support for Month, Day, and Week view.
For recurring events I did the following a while back: 1. When a user entered an event I stored the event's date pattern GNU date style - the keyword for PHP is [relative date formats](http://www.php.net/manual/de/datetime.formats.relative.php). 2. Then I started off by creating events for e.g. the next year. And created actual records where I converted the relative date to an actual -- e.g. "every first Monday" to a "mm-dd-YYYY". This allowed me to display them and also allow the user to e.g. move a single event or cancel one, etc.. 3. Then figure out how far to go into the future - my idea was to create events when the actual pages were browsed. E.g. if I had created events through June 2011 and someone skipped all the way to July 2011, I would iterate on my events and set them up transparently. 4. When the user changes the relative pattern, offer to update all following events -- unless they have a custom pattern already. Relative patterns make it super easy to calculate all that.
43,342,354
I want to connect to database from my c# windows forms application. I tried using ``` using(SqlConnection conn = new SqlConnection()) { conn.ConnectionString = "Data Source=localhost; User Id=root; Password=; Initial Catalog=dbName"; conn.Open(); } ``` and when I build my project I get an error that `server wasn't found or wasn't accessible`. I tried connecting through data source configuration wizard, but also database can't be found. I use `WAMP` server, and I can find my database through `phpMyAdmin`.
2017/04/11
[ "https://Stackoverflow.com/questions/43342354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4043273/" ]
You're trying to connect to Microsoft SQL Server. ``` using System; using System.Data; using MySql.Data; using MySql.Data.MySqlClient; public class Tutorial1 { public static void Main() { string connStr = "server=localhost;user=root;database=world;port=3306;password=******;"; MySqlConnection conn = new MySqlConnection(connStr); try { Console.WriteLine("Connecting to MySQL..."); conn.Open(); // Perform database operations } catch (Exception ex) { Console.WriteLine(ex.ToString()); } conn.Close(); Console.WriteLine("Done."); } } ``` Check this links,hope this will be helped to you * <https://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-open.html> * <http://net-informations.com/q/faq/mysql.html> you can install MySql.Data by ,open Package Manager Console **Tools > NuGet Package Manager > Package Manager Console** then type `Install-Package MySql.Data -Version 6.9.9` in there
You would need to use a `MySqlConnection` to connect to a MySQL database, see answer here [How to connect to MySQL Database?](https://stackoverflow.com/questions/21618015/how-to-connect-to-mysql-database)
26,715,112
I have a button which is added dynamically ``` <button id="btnSubmit">Button 1</button> $(document).ready(function(){ $('#btnSubmit').on('click', function(){ alert('Button 1'); var button2 = '<button id="btn2" >Button 2</button>'; $('#btnSubmit').after('<p></p>' + button2); }); $(document).on('#btn2', 'click', function(){ alert('Button2 clicked'); }); }); ``` Now, when I click on #btn2 the event is not detected. How can this be fixed?
2014/11/03
[ "https://Stackoverflow.com/questions/26715112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/544079/" ]
You are adding `btn2` for every click of `btnSubmit`, this will create multiple buttons with same `id` and it is not acceptible with jQuery. Use unique `id` or `class` for every dynamic button adde, and use `.on()` to bind click event to button, see below code HTML ``` <button id="btnSubmit">Button 1</button> ``` jQuery ``` $(document).ready(function(){ $('#btnSubmit').on('click', function(){ alert('Button 1'); var button2 = '<button class="btn2" >Button 2</button>'; $('#btnSubmit').after('<p></p>' + button2); }); $(document).on('click','.btn2', function(){ alert('Button2 clicked'); }); }); ```
``` $(document).ready(function(){ $('#btnSubmit').on('click', function(){ alert('Button 1'); var button2 = '<button id="btn2" >Button 2</button>'; $('#btnSubmit').after('<p></p>' + button2); $(document).bind('#btn2', 'click', function(){ alert('Button2 clicked'); }); }); }); ``` try this code It will work. or you can try this as well. ``` $(document).ready(function(){ $('#btnSubmit').on('click', function(){ alert('Button 1'); var button2 = '<button id="btn2" >Button 2</button>'; $('#btnSubmit').after('<p></p>' + button2); $('#btn2').live('click', function(){ alert('Button2 clicked'); }); }); }); ```
13,262,804
How to organize a file downloading from server database and open it on the client machine? my code works only when the page is opened on the server: ``` OracleCommand oracleCom = new OracleCommand(); oracleCom.Connection = oraConnect; oracleCom.CommandText = "Select m_content, f_extension From " + Session["tableNameIns"] + " where i_id = " + rowData; OracleDataAdapter adapter = new OracleDataAdapter(); DataTable tableD = new DataTable(); tableD.Locale = System.Globalization.CultureInfo.InvariantCulture; adapter.SelectCommand = oracleCom; adapter.Fill(tableD); string FileName = Path.GetTempPath(); FileName += "tempfile" + tableD.Rows[0][1]; byte[] file = new byte[0]; file = (byte[])tableD.Rows[0][0]; FileStream fs = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write); fs.Write(file, 0, file.GetUpperBound(0) + 1); fs.Close(); System.Diagnostics.Process.Start(FileName); ```
2012/11/07
[ "https://Stackoverflow.com/questions/13262804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1555931/" ]
I don't know if this is still an issue for you but I had a similar problem and found that I had not decorated one of my DTOs with `[DataContract]` and `[DataMember]` attributes, as described on the [SOAP Support wiki page](https://github.com/ServiceStack/ServiceStack/wiki/SOAP-support). Once you have added these to your DTO it will be declared in the type section of the WSDL.
Have a look at using `[DataContract (Namespace = "YOUR NAMESPACE")]` on top of your DTO's. This is how my objects are referenced. ``` [DataContract(Namespace = "My.WS.DTO")] public class Account{ } ``` I also use this in my service model. [System.ServiceModel.ServiceContract()] and [System.ServiceModel.OperationContract()] ``` [System.ServiceModel.ServiceContract()] public class SendGetAccountResponseService : IService<SendGetAccountNotification> { #region IService implementation [System.ServiceModel.OperationContract()] public object Execute (SendGetAccountNotification request) { Console.WriteLine ("Reached"); return null; } #endregion } ``` Hope this helps / solves your problem.
13,262,804
How to organize a file downloading from server database and open it on the client machine? my code works only when the page is opened on the server: ``` OracleCommand oracleCom = new OracleCommand(); oracleCom.Connection = oraConnect; oracleCom.CommandText = "Select m_content, f_extension From " + Session["tableNameIns"] + " where i_id = " + rowData; OracleDataAdapter adapter = new OracleDataAdapter(); DataTable tableD = new DataTable(); tableD.Locale = System.Globalization.CultureInfo.InvariantCulture; adapter.SelectCommand = oracleCom; adapter.Fill(tableD); string FileName = Path.GetTempPath(); FileName += "tempfile" + tableD.Rows[0][1]; byte[] file = new byte[0]; file = (byte[])tableD.Rows[0][0]; FileStream fs = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write); fs.Write(file, 0, file.GetUpperBound(0) + 1); fs.Close(); System.Diagnostics.Process.Start(FileName); ```
2012/11/07
[ "https://Stackoverflow.com/questions/13262804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1555931/" ]
I don't know if this is still an issue for you but I had a similar problem and found that I had not decorated one of my DTOs with `[DataContract]` and `[DataMember]` attributes, as described on the [SOAP Support wiki page](https://github.com/ServiceStack/ServiceStack/wiki/SOAP-support). Once you have added these to your DTO it will be declared in the type section of the WSDL.
I know this is an old question, but I had to add SOAP support for a 3rd party that refused to support REST very recently to my ServiceStack implementation so it could still be relevant to other people still having this issue. I had the same issue you were having: > > Unable to import binding 'BasicHttpBinding\_ISyncReply'... > > > And like mickfold previously answered I needed to add **[DataContract]** and **[DataMember]** to my class definitions and their properties. But I also had to add the following to my AssemblyInfo.cs file before the error went away for me: ``` [assembly: ContractNamespace("http://schemas.servicestack.net/types", ClrNamespace = "My Type Namespace")] ``` I assume that you will need one of these lines for every single namespace where you have a type declared, which based upon the original question above would be **My.WS.DTO**.
4,164,820
Suppose we need to embed a widget in third party page. This widget might use jquery for instance so widget carries a jquery library with itself. Suppose third party page also uses jquery but a different version. How to prevent clash between them when embedding widgets? jquery.noConflict is not an option because it's required to call this method for the first jquery library which is loaded in the page and this means that third party website should call it. The idea is that third party site should not amend or do anything aside putting tag with a src to the widget in order to use it. Also this is not the problem with jquery in particular - google closure library (even compiled) might be taken as an example. What solutions are exist to isolate different javascript libraries aside from obvious iframe? Maybe loading javascript as string and then eval (by using Function('code to eval'), not the eval('code to eval')) it in anonymous function might do the trick?
2010/11/12
[ "https://Stackoverflow.com/questions/4164820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82189/" ]
Actually, I think [jQuery.noConflict](http://api.jquery.com/jQuery.noConflict/) is precisely what you want to use. If I understand its [implementation](https://github.com/jquery/jquery/blob/master/src/core.js#L376) correctly, your code should look like this: ``` (function () { var my$; // your copy of the minified jQuery source my$ = jQuery.noConflict(true); // your widget code, which should use my$ instead of $ }()); ``` The call to `noConflict` will restore the global `jQuery` and `$` objects to their former values.
Instead of looking for methods like no conflict, you can very well call full URL of the Google API on jQuery so that it can work in the application.
4,164,820
Suppose we need to embed a widget in third party page. This widget might use jquery for instance so widget carries a jquery library with itself. Suppose third party page also uses jquery but a different version. How to prevent clash between them when embedding widgets? jquery.noConflict is not an option because it's required to call this method for the first jquery library which is loaded in the page and this means that third party website should call it. The idea is that third party site should not amend or do anything aside putting tag with a src to the widget in order to use it. Also this is not the problem with jquery in particular - google closure library (even compiled) might be taken as an example. What solutions are exist to isolate different javascript libraries aside from obvious iframe? Maybe loading javascript as string and then eval (by using Function('code to eval'), not the eval('code to eval')) it in anonymous function might do the trick?
2010/11/12
[ "https://Stackoverflow.com/questions/4164820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82189/" ]
`Function(...)` makes an eval inside your function, it isn't any better. Why not use the `iframe` they provide a default sandboxing for third party content. And for friendly ones you can share text data, between them and your page, using `parent.postMessage` for modern browser or the `window.name` hack for the olders.
Instead of looking for methods like no conflict, you can very well call full URL of the Google API on jQuery so that it can work in the application.
4,164,820
Suppose we need to embed a widget in third party page. This widget might use jquery for instance so widget carries a jquery library with itself. Suppose third party page also uses jquery but a different version. How to prevent clash between them when embedding widgets? jquery.noConflict is not an option because it's required to call this method for the first jquery library which is loaded in the page and this means that third party website should call it. The idea is that third party site should not amend or do anything aside putting tag with a src to the widget in order to use it. Also this is not the problem with jquery in particular - google closure library (even compiled) might be taken as an example. What solutions are exist to isolate different javascript libraries aside from obvious iframe? Maybe loading javascript as string and then eval (by using Function('code to eval'), not the eval('code to eval')) it in anonymous function might do the trick?
2010/11/12
[ "https://Stackoverflow.com/questions/4164820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82189/" ]
I built a library to solve this very problem. I am not sure if it will help you of course, because the code still has to be aware of the problem and use the library in the first place, so it will help only if you are able to change your code to use the library. The library in question is called [Packages JS](http://packagesinjavascript.wordpress.com) and can be downloaded and used for free as it is Open Source under a Creative Commons license. It basically works by packaging code inside functions. From those functions you export those objects you want to expose to other packages. In the consumer packages you import these objects into your local namespace. It doesn't matter if someone else or indeed even you yourself use the same name multiple times because you can resolve the ambiguity. Here is an example: *(file example/greeting.js)* ``` Package("example.greeting", function() { // Create a function hello... function hello() { return "Hello world!"; }; // ...then export it for use by other packages Export(hello); // You need to supply a name for anonymous functions... Export("goodbye", function() { return "Goodbye cruel world!"; }); }); ``` *(file example/ambiguity.js)* ``` Package("example.ambiguity", function() { // functions hello and goodbye are also in example.greeting, making it ambiguous which // one is intended when using the unqualified name. function hello() { return "Hello ambiguity!"; }; function goodbye() { return "Goodbye ambiguity!"; }; // export for use by other packages Export(hello); Export(goodbye); }); ``` *(file example/ambiguitytest.js)* ``` Package("example.ambiguitytest", ["example.ambiguity", "example.greeting"], function(hello, log) { // Which hello did we get? The one from example.ambiguity or from example.greeting? log().info(hello()); // We will get the first one found, so the one from example.ambiguity in this case. // Use fully qualified names to resolve any ambiguities. var goodbye1 = Import("example.greeting.goodbye"); var goodbye2 = Import("example.ambiguity.goodbye"); log().info(goodbye1()); log().info(goodbye2()); }); ``` example/ambiguitytest.js uses two libraries that both export a function goodbye, but it can explicitly import the correct ones and assign them to local aliases to disambiguate between them. To use jQuery in this way would mean 'packaging' jQuery by wrapping it's code in a call to Package and Exporting the objects that it now exposes to the global scope. It means changing the library a bit which may not be what you want but alas there is no way around that that I can see without resorting to iframes. I am planning on including 'packaged' versions of popular libraries along in the download and jQuery is definitely on the list, but at the moment I only have a packaged version of Sizzle, jQuery's selector engine.
Instead of looking for methods like no conflict, you can very well call full URL of the Google API on jQuery so that it can work in the application.
4,164,820
Suppose we need to embed a widget in third party page. This widget might use jquery for instance so widget carries a jquery library with itself. Suppose third party page also uses jquery but a different version. How to prevent clash between them when embedding widgets? jquery.noConflict is not an option because it's required to call this method for the first jquery library which is loaded in the page and this means that third party website should call it. The idea is that third party site should not amend or do anything aside putting tag with a src to the widget in order to use it. Also this is not the problem with jquery in particular - google closure library (even compiled) might be taken as an example. What solutions are exist to isolate different javascript libraries aside from obvious iframe? Maybe loading javascript as string and then eval (by using Function('code to eval'), not the eval('code to eval')) it in anonymous function might do the trick?
2010/11/12
[ "https://Stackoverflow.com/questions/4164820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82189/" ]
Actually, I think [jQuery.noConflict](http://api.jquery.com/jQuery.noConflict/) is precisely what you want to use. If I understand its [implementation](https://github.com/jquery/jquery/blob/master/src/core.js#L376) correctly, your code should look like this: ``` (function () { var my$; // your copy of the minified jQuery source my$ = jQuery.noConflict(true); // your widget code, which should use my$ instead of $ }()); ``` The call to `noConflict` will restore the global `jQuery` and `$` objects to their former values.
I built a library to solve this very problem. I am not sure if it will help you of course, because the code still has to be aware of the problem and use the library in the first place, so it will help only if you are able to change your code to use the library. The library in question is called [Packages JS](http://packagesinjavascript.wordpress.com) and can be downloaded and used for free as it is Open Source under a Creative Commons license. It basically works by packaging code inside functions. From those functions you export those objects you want to expose to other packages. In the consumer packages you import these objects into your local namespace. It doesn't matter if someone else or indeed even you yourself use the same name multiple times because you can resolve the ambiguity. Here is an example: *(file example/greeting.js)* ``` Package("example.greeting", function() { // Create a function hello... function hello() { return "Hello world!"; }; // ...then export it for use by other packages Export(hello); // You need to supply a name for anonymous functions... Export("goodbye", function() { return "Goodbye cruel world!"; }); }); ``` *(file example/ambiguity.js)* ``` Package("example.ambiguity", function() { // functions hello and goodbye are also in example.greeting, making it ambiguous which // one is intended when using the unqualified name. function hello() { return "Hello ambiguity!"; }; function goodbye() { return "Goodbye ambiguity!"; }; // export for use by other packages Export(hello); Export(goodbye); }); ``` *(file example/ambiguitytest.js)* ``` Package("example.ambiguitytest", ["example.ambiguity", "example.greeting"], function(hello, log) { // Which hello did we get? The one from example.ambiguity or from example.greeting? log().info(hello()); // We will get the first one found, so the one from example.ambiguity in this case. // Use fully qualified names to resolve any ambiguities. var goodbye1 = Import("example.greeting.goodbye"); var goodbye2 = Import("example.ambiguity.goodbye"); log().info(goodbye1()); log().info(goodbye2()); }); ``` example/ambiguitytest.js uses two libraries that both export a function goodbye, but it can explicitly import the correct ones and assign them to local aliases to disambiguate between them. To use jQuery in this way would mean 'packaging' jQuery by wrapping it's code in a call to Package and Exporting the objects that it now exposes to the global scope. It means changing the library a bit which may not be what you want but alas there is no way around that that I can see without resorting to iframes. I am planning on including 'packaged' versions of popular libraries along in the download and jQuery is definitely on the list, but at the moment I only have a packaged version of Sizzle, jQuery's selector engine.
4,164,820
Suppose we need to embed a widget in third party page. This widget might use jquery for instance so widget carries a jquery library with itself. Suppose third party page also uses jquery but a different version. How to prevent clash between them when embedding widgets? jquery.noConflict is not an option because it's required to call this method for the first jquery library which is loaded in the page and this means that third party website should call it. The idea is that third party site should not amend or do anything aside putting tag with a src to the widget in order to use it. Also this is not the problem with jquery in particular - google closure library (even compiled) might be taken as an example. What solutions are exist to isolate different javascript libraries aside from obvious iframe? Maybe loading javascript as string and then eval (by using Function('code to eval'), not the eval('code to eval')) it in anonymous function might do the trick?
2010/11/12
[ "https://Stackoverflow.com/questions/4164820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82189/" ]
Actually, I think [jQuery.noConflict](http://api.jquery.com/jQuery.noConflict/) is precisely what you want to use. If I understand its [implementation](https://github.com/jquery/jquery/blob/master/src/core.js#L376) correctly, your code should look like this: ``` (function () { var my$; // your copy of the minified jQuery source my$ = jQuery.noConflict(true); // your widget code, which should use my$ instead of $ }()); ``` The call to `noConflict` will restore the global `jQuery` and `$` objects to their former values.
``` <script src="myjquery.min.js"></script> <script>window.myjQuery = window.jQuery.noConflict();</script> ... <script src='...'></script> //another widget using an old versioned jquery <script> (function($){ //... //now you can access your own jquery here, without conflict })(window.myjQuery); delete window.myjQuery; </script> ``` Most important points: 1. call jQuery.noConflict() method IMMEDIATELY AFTER your own jquery and related plugins tags 2. store the result jquery to a global variable, with a name that has little chance to conflict or confuse 3. load your widget using the old versioned jquery; 4. followed up is your logic codes. using a closure to obtain a private $ for convience. The private $ will not conflict with other jquerys. 5. You'd better not forget to delete the global temp var.
4,164,820
Suppose we need to embed a widget in third party page. This widget might use jquery for instance so widget carries a jquery library with itself. Suppose third party page also uses jquery but a different version. How to prevent clash between them when embedding widgets? jquery.noConflict is not an option because it's required to call this method for the first jquery library which is loaded in the page and this means that third party website should call it. The idea is that third party site should not amend or do anything aside putting tag with a src to the widget in order to use it. Also this is not the problem with jquery in particular - google closure library (even compiled) might be taken as an example. What solutions are exist to isolate different javascript libraries aside from obvious iframe? Maybe loading javascript as string and then eval (by using Function('code to eval'), not the eval('code to eval')) it in anonymous function might do the trick?
2010/11/12
[ "https://Stackoverflow.com/questions/4164820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82189/" ]
`Function(...)` makes an eval inside your function, it isn't any better. Why not use the `iframe` they provide a default sandboxing for third party content. And for friendly ones you can share text data, between them and your page, using `parent.postMessage` for modern browser or the `window.name` hack for the olders.
I built a library to solve this very problem. I am not sure if it will help you of course, because the code still has to be aware of the problem and use the library in the first place, so it will help only if you are able to change your code to use the library. The library in question is called [Packages JS](http://packagesinjavascript.wordpress.com) and can be downloaded and used for free as it is Open Source under a Creative Commons license. It basically works by packaging code inside functions. From those functions you export those objects you want to expose to other packages. In the consumer packages you import these objects into your local namespace. It doesn't matter if someone else or indeed even you yourself use the same name multiple times because you can resolve the ambiguity. Here is an example: *(file example/greeting.js)* ``` Package("example.greeting", function() { // Create a function hello... function hello() { return "Hello world!"; }; // ...then export it for use by other packages Export(hello); // You need to supply a name for anonymous functions... Export("goodbye", function() { return "Goodbye cruel world!"; }); }); ``` *(file example/ambiguity.js)* ``` Package("example.ambiguity", function() { // functions hello and goodbye are also in example.greeting, making it ambiguous which // one is intended when using the unqualified name. function hello() { return "Hello ambiguity!"; }; function goodbye() { return "Goodbye ambiguity!"; }; // export for use by other packages Export(hello); Export(goodbye); }); ``` *(file example/ambiguitytest.js)* ``` Package("example.ambiguitytest", ["example.ambiguity", "example.greeting"], function(hello, log) { // Which hello did we get? The one from example.ambiguity or from example.greeting? log().info(hello()); // We will get the first one found, so the one from example.ambiguity in this case. // Use fully qualified names to resolve any ambiguities. var goodbye1 = Import("example.greeting.goodbye"); var goodbye2 = Import("example.ambiguity.goodbye"); log().info(goodbye1()); log().info(goodbye2()); }); ``` example/ambiguitytest.js uses two libraries that both export a function goodbye, but it can explicitly import the correct ones and assign them to local aliases to disambiguate between them. To use jQuery in this way would mean 'packaging' jQuery by wrapping it's code in a call to Package and Exporting the objects that it now exposes to the global scope. It means changing the library a bit which may not be what you want but alas there is no way around that that I can see without resorting to iframes. I am planning on including 'packaged' versions of popular libraries along in the download and jQuery is definitely on the list, but at the moment I only have a packaged version of Sizzle, jQuery's selector engine.
4,164,820
Suppose we need to embed a widget in third party page. This widget might use jquery for instance so widget carries a jquery library with itself. Suppose third party page also uses jquery but a different version. How to prevent clash between them when embedding widgets? jquery.noConflict is not an option because it's required to call this method for the first jquery library which is loaded in the page and this means that third party website should call it. The idea is that third party site should not amend or do anything aside putting tag with a src to the widget in order to use it. Also this is not the problem with jquery in particular - google closure library (even compiled) might be taken as an example. What solutions are exist to isolate different javascript libraries aside from obvious iframe? Maybe loading javascript as string and then eval (by using Function('code to eval'), not the eval('code to eval')) it in anonymous function might do the trick?
2010/11/12
[ "https://Stackoverflow.com/questions/4164820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82189/" ]
`Function(...)` makes an eval inside your function, it isn't any better. Why not use the `iframe` they provide a default sandboxing for third party content. And for friendly ones you can share text data, between them and your page, using `parent.postMessage` for modern browser or the `window.name` hack for the olders.
``` <script src="myjquery.min.js"></script> <script>window.myjQuery = window.jQuery.noConflict();</script> ... <script src='...'></script> //another widget using an old versioned jquery <script> (function($){ //... //now you can access your own jquery here, without conflict })(window.myjQuery); delete window.myjQuery; </script> ``` Most important points: 1. call jQuery.noConflict() method IMMEDIATELY AFTER your own jquery and related plugins tags 2. store the result jquery to a global variable, with a name that has little chance to conflict or confuse 3. load your widget using the old versioned jquery; 4. followed up is your logic codes. using a closure to obtain a private $ for convience. The private $ will not conflict with other jquerys. 5. You'd better not forget to delete the global temp var.
4,164,820
Suppose we need to embed a widget in third party page. This widget might use jquery for instance so widget carries a jquery library with itself. Suppose third party page also uses jquery but a different version. How to prevent clash between them when embedding widgets? jquery.noConflict is not an option because it's required to call this method for the first jquery library which is loaded in the page and this means that third party website should call it. The idea is that third party site should not amend or do anything aside putting tag with a src to the widget in order to use it. Also this is not the problem with jquery in particular - google closure library (even compiled) might be taken as an example. What solutions are exist to isolate different javascript libraries aside from obvious iframe? Maybe loading javascript as string and then eval (by using Function('code to eval'), not the eval('code to eval')) it in anonymous function might do the trick?
2010/11/12
[ "https://Stackoverflow.com/questions/4164820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82189/" ]
I built a library to solve this very problem. I am not sure if it will help you of course, because the code still has to be aware of the problem and use the library in the first place, so it will help only if you are able to change your code to use the library. The library in question is called [Packages JS](http://packagesinjavascript.wordpress.com) and can be downloaded and used for free as it is Open Source under a Creative Commons license. It basically works by packaging code inside functions. From those functions you export those objects you want to expose to other packages. In the consumer packages you import these objects into your local namespace. It doesn't matter if someone else or indeed even you yourself use the same name multiple times because you can resolve the ambiguity. Here is an example: *(file example/greeting.js)* ``` Package("example.greeting", function() { // Create a function hello... function hello() { return "Hello world!"; }; // ...then export it for use by other packages Export(hello); // You need to supply a name for anonymous functions... Export("goodbye", function() { return "Goodbye cruel world!"; }); }); ``` *(file example/ambiguity.js)* ``` Package("example.ambiguity", function() { // functions hello and goodbye are also in example.greeting, making it ambiguous which // one is intended when using the unqualified name. function hello() { return "Hello ambiguity!"; }; function goodbye() { return "Goodbye ambiguity!"; }; // export for use by other packages Export(hello); Export(goodbye); }); ``` *(file example/ambiguitytest.js)* ``` Package("example.ambiguitytest", ["example.ambiguity", "example.greeting"], function(hello, log) { // Which hello did we get? The one from example.ambiguity or from example.greeting? log().info(hello()); // We will get the first one found, so the one from example.ambiguity in this case. // Use fully qualified names to resolve any ambiguities. var goodbye1 = Import("example.greeting.goodbye"); var goodbye2 = Import("example.ambiguity.goodbye"); log().info(goodbye1()); log().info(goodbye2()); }); ``` example/ambiguitytest.js uses two libraries that both export a function goodbye, but it can explicitly import the correct ones and assign them to local aliases to disambiguate between them. To use jQuery in this way would mean 'packaging' jQuery by wrapping it's code in a call to Package and Exporting the objects that it now exposes to the global scope. It means changing the library a bit which may not be what you want but alas there is no way around that that I can see without resorting to iframes. I am planning on including 'packaged' versions of popular libraries along in the download and jQuery is definitely on the list, but at the moment I only have a packaged version of Sizzle, jQuery's selector engine.
``` <script src="myjquery.min.js"></script> <script>window.myjQuery = window.jQuery.noConflict();</script> ... <script src='...'></script> //another widget using an old versioned jquery <script> (function($){ //... //now you can access your own jquery here, without conflict })(window.myjQuery); delete window.myjQuery; </script> ``` Most important points: 1. call jQuery.noConflict() method IMMEDIATELY AFTER your own jquery and related plugins tags 2. store the result jquery to a global variable, with a name that has little chance to conflict or confuse 3. load your widget using the old versioned jquery; 4. followed up is your logic codes. using a closure to obtain a private $ for convience. The private $ will not conflict with other jquerys. 5. You'd better not forget to delete the global temp var.
372,771
I have a grid I would like to make some changes to it but have no idea. My minimal example: ``` \documentclass[border=2mm]{standalone} \usepackage{tikz} \usetikzlibrary{calc} \begin{document} \begin{tikzpicture} \draw[step=2cm,color=gray,rotate=45] (-1,-1) grid (9,9); \node at (-0.5,+0.5) {A}; \end{tikzpicture} \end{document} ``` But this won't give me the answer. What I actually want is (i) each adjacent line to have different color(two in total, may be one red and another blue). (ii) then where ever they cross blue and red lines a circle(hiding the cross with circle), inside the circle a text like **A**(misplaced by me), everywhere they cross. [![enter image description here](https://i.stack.imgur.com/ktcll.jpg)](https://i.stack.imgur.com/ktcll.jpg) (partially near to this) Don't consider the background color. But something like the this directed(with arrows) network. With dashed and complete circles, labelled differently. I am new to TikZ or making figures in LaTeX. My apologies.
2017/06/01
[ "https://tex.stackexchange.com/questions/372771", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/120078/" ]
The question is not very clear. I was preparing this solution, when I saw that marsupilam already aswered something very similar. The main difference in my solution is the inclusion of a `\path[clip]` to remove the unwanted parts: ``` \documentclass[border=3mm]{standalone} \usepackage{tikz} \begin{document} \begin{tikzpicture} \path[clip] (-3,-3) rectangle +(6,6); \begin{scope}[rotate=45] \foreach \x in {-4,...,4} { \draw[red] (\x, -4) -- +(0,8); } \foreach \y in {-4,...,4} { \draw[blue] (-4,\y) -- +(8,0); } \foreach \x in {-4,...,4} \foreach \y in {-4,...,4} \node[draw,circle,fill=white, inner sep=2pt] at (\x,\y) {A}; \end{scope} \end{tikzpicture} ``` \end{document} Result: [![Result](https://i.stack.imgur.com/occGY.png)](https://i.stack.imgur.com/occGY.png) Update ====== The OP asked for arrows between nodes. At first I thought of decorating the edges, but in the end the following approach, which draws arrows slightly offset is much simpler: ``` \documentclass[border=3mm]{standalone} \usepackage{tikz} \usetikzlibrary{decorations.markings} \begin{document} \begin{tikzpicture}[>=stealth] \path[clip] (-3,-3) rectangle +(6,6); \begin{scope}[rotate=45] \foreach \x in {-4,...,4} \foreach \y in {-4,...,4} { \draw[blue,->] (\x-0.4, \y) -- (\x+0.6, \y); \draw[red, ->] (\x, \y-0.5) -- (\x, \y+0.6); \node[draw,circle,fill=white, inner sep=2pt] at (\x,\y) {A}; } \end{scope} \end{tikzpicture} \end{document} ``` [![Result](https://i.stack.imgur.com/IQVy9.png)](https://i.stack.imgur.com/IQVy9.png) Update 2 ======== The OP asked later for different style/content for alternate nodes. The easiest way to do this is to compute the function `mod(abs(x+y), 2)+1` which has only two possible outcomes (1 and 2), and use this result to set the appropiate subindex in the node content, and to select a different tikz style. ``` \documentclass[border=3mm]{standalone} \usepackage{tikz} \usetikzlibrary{decorations.markings} \tikzset{ mynode/.style = {circle, draw, thick, fill=white, inner sep=0pt}, type1/.style = {mynode}, type2/.style = {mynode, dashed} } \begin{document} \begin{tikzpicture}[>=stealth] \path[clip] (-3,-3) rectangle +(6,6); \begin{scope}[rotate=45] \foreach \x in {-4,...,4} \foreach \y in {-4,...,4} { \pgfmathsetmacro{\type}{int(mod(abs(\x+\y),2)+1)}; \draw[blue,->] (\x-0.4, \y) -- (\x+0.6, \y); \draw[red, ->] (\x, \y-0.5) -- (\x, \y+0.6); \node[type\type] at (\x,\y) {$A_\type$}; } \end{scope} \end{tikzpicture} \end{document} ``` [![Result](https://i.stack.imgur.com/2tPIP.png)](https://i.stack.imgur.com/2tPIP.png)
Welcome to TeX.SX ! Edited version -------------- ### The output Closer to your pic. Is this better ? [![enter image description here](https://i.stack.imgur.com/pVjnA.png)](https://i.stack.imgur.com/pVjnA.png) ### The code ``` \documentclass[tikz,border=2mm]{standalone} \usetikzlibrary{calc} \begin{document} \begin{tikzpicture} \begin{scope}[rotate=45] \coordinate (SE) at (-1,-1) ; \coordinate (NW) at (9,9) ; \foreach \x in {0,2,...,8} { \coordinate (X) at (\x,\x); \draw [red] (X-|SE) -- (X-|NW) ; \draw [blue] (X|-SE) -- (X|-NW) ; } \foreach \x in {0,2,...,8} { \foreach \y in {0,2,...,8} { \node [circle, draw, fill=green, fill opacity=.8, text opacity=1] at (\x,\y) {A}; } } \end{scope} \end{tikzpicture} \end{document} ``` Original version ---------------- Is this what you need ? ### The output [![enter image description here](https://i.stack.imgur.com/pIQP5.png)](https://i.stack.imgur.com/pIQP5.png) ### The code ``` \documentclass[tikz,border=2mm]{standalone} \usetikzlibrary{calc} \begin{document} \begin{tikzpicture} \begin{scope}[rotate=45] \coordinate (SE) at (-1,-1) ; \coordinate (NW) at (9,9) ; \draw [step=2cm,color=gray] (SE) grid (NW); \coordinate (A) at (2,4) ; \draw [blue, thick,] (SE|-A) -- (NW|-A) ; \draw [red, thick,] (SE-|A) -- (NW-|A) ; \node [circle, draw, fill=green, fill opacity=.8, text opacity=1] at (A) {A}; \end{scope} \end{tikzpicture} \end{document} ```
372,771
I have a grid I would like to make some changes to it but have no idea. My minimal example: ``` \documentclass[border=2mm]{standalone} \usepackage{tikz} \usetikzlibrary{calc} \begin{document} \begin{tikzpicture} \draw[step=2cm,color=gray,rotate=45] (-1,-1) grid (9,9); \node at (-0.5,+0.5) {A}; \end{tikzpicture} \end{document} ``` But this won't give me the answer. What I actually want is (i) each adjacent line to have different color(two in total, may be one red and another blue). (ii) then where ever they cross blue and red lines a circle(hiding the cross with circle), inside the circle a text like **A**(misplaced by me), everywhere they cross. [![enter image description here](https://i.stack.imgur.com/ktcll.jpg)](https://i.stack.imgur.com/ktcll.jpg) (partially near to this) Don't consider the background color. But something like the this directed(with arrows) network. With dashed and complete circles, labelled differently. I am new to TikZ or making figures in LaTeX. My apologies.
2017/06/01
[ "https://tex.stackexchange.com/questions/372771", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/120078/" ]
The question is not very clear. I was preparing this solution, when I saw that marsupilam already aswered something very similar. The main difference in my solution is the inclusion of a `\path[clip]` to remove the unwanted parts: ``` \documentclass[border=3mm]{standalone} \usepackage{tikz} \begin{document} \begin{tikzpicture} \path[clip] (-3,-3) rectangle +(6,6); \begin{scope}[rotate=45] \foreach \x in {-4,...,4} { \draw[red] (\x, -4) -- +(0,8); } \foreach \y in {-4,...,4} { \draw[blue] (-4,\y) -- +(8,0); } \foreach \x in {-4,...,4} \foreach \y in {-4,...,4} \node[draw,circle,fill=white, inner sep=2pt] at (\x,\y) {A}; \end{scope} \end{tikzpicture} ``` \end{document} Result: [![Result](https://i.stack.imgur.com/occGY.png)](https://i.stack.imgur.com/occGY.png) Update ====== The OP asked for arrows between nodes. At first I thought of decorating the edges, but in the end the following approach, which draws arrows slightly offset is much simpler: ``` \documentclass[border=3mm]{standalone} \usepackage{tikz} \usetikzlibrary{decorations.markings} \begin{document} \begin{tikzpicture}[>=stealth] \path[clip] (-3,-3) rectangle +(6,6); \begin{scope}[rotate=45] \foreach \x in {-4,...,4} \foreach \y in {-4,...,4} { \draw[blue,->] (\x-0.4, \y) -- (\x+0.6, \y); \draw[red, ->] (\x, \y-0.5) -- (\x, \y+0.6); \node[draw,circle,fill=white, inner sep=2pt] at (\x,\y) {A}; } \end{scope} \end{tikzpicture} \end{document} ``` [![Result](https://i.stack.imgur.com/IQVy9.png)](https://i.stack.imgur.com/IQVy9.png) Update 2 ======== The OP asked later for different style/content for alternate nodes. The easiest way to do this is to compute the function `mod(abs(x+y), 2)+1` which has only two possible outcomes (1 and 2), and use this result to set the appropiate subindex in the node content, and to select a different tikz style. ``` \documentclass[border=3mm]{standalone} \usepackage{tikz} \usetikzlibrary{decorations.markings} \tikzset{ mynode/.style = {circle, draw, thick, fill=white, inner sep=0pt}, type1/.style = {mynode}, type2/.style = {mynode, dashed} } \begin{document} \begin{tikzpicture}[>=stealth] \path[clip] (-3,-3) rectangle +(6,6); \begin{scope}[rotate=45] \foreach \x in {-4,...,4} \foreach \y in {-4,...,4} { \pgfmathsetmacro{\type}{int(mod(abs(\x+\y),2)+1)}; \draw[blue,->] (\x-0.4, \y) -- (\x+0.6, \y); \draw[red, ->] (\x, \y-0.5) -- (\x, \y+0.6); \node[type\type] at (\x,\y) {$A_\type$}; } \end{scope} \end{tikzpicture} \end{document} ``` [![Result](https://i.stack.imgur.com/2tPIP.png)](https://i.stack.imgur.com/2tPIP.png)
Update ------ With clip, and no coordinate label ``` \documentclass[border=2mm]{standalone} \usepackage{tikz} \usetikzlibrary{calc} \begin{document} \begin{tikzpicture} \path[clip] (-10,-4) rectangle +(8,8); \begin{scope}[rotate=45] \draw[step=4cm,color=blue, thick] (-15,-15) grid (9,9); \draw[step=4cm,color=red,thick, shift={(-2cm,-2cm)}] (-13,-13) grid (11,11); \foreach \i in {-14,-12,...,8}{% \foreach \j in {-14,-12,...,8} \node[fill=black!30,circle,radius=2pt] at (\i,\j) {A}; } \end{scope} \end{tikzpicture} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/rrlnVm.png)](https://i.stack.imgur.com/rrlnVm.png) --- Like the others have mentioned, the question is not clear. My interpretation is as such: * Parallel grid lines (on both axes) should have alternate colours. * Circle with text inside Obviously the circles need not be on every intersection point, you can add nodes yourself on relevant coordinates. I've left the coordinates above the nodes, for your reference. You can omit those in your own code, if they are not required. Also, your image in the question had labels outside the node, so I was confused on what you wanted for a moment. [![enter image description here](https://i.stack.imgur.com/lmYt9.png)](https://i.stack.imgur.com/lmYt9.png) ``` \documentclass[border=2mm]{standalone} \usepackage{tikz} \usetikzlibrary{calc} \begin{document} \begin{tikzpicture}[rotate=45] \draw[step=4cm,color=blue, thick] (-3,-3) grid (9,9); \draw[step=4cm,color=red,thick, shift={(-2cm,-2cm)}] (-1,-1) grid (11,11); \foreach \i in {-2,0,...,8}{% \foreach \j in {-2,0,...,8} \node[fill=black!30,circle,radius=2pt,label={[above]:(\i,\j)}] at (\i,\j) {A}; } \end{tikzpicture} \end{document} ``` --- **Crux of my code:** Basically I doubled the grid size from `2cm` to `4cm`, and set up two grids superimposed on each other, with a shift. This way I was able to set up two colours for the grid.
52,305,417
I have succeeded in cobbling together pieces of code that achieve my goal. However, I would like some advice from more advanced vanilla JS programmers on how I can go about reaching my goal in a better way. To start, I want to introduce my problem. I have a piece of text on my website where a portion is designed to change every so often. For this, I am running through a loop of phrases. To run this loop continuously, I first call the loop, then I call it again with setInterval timed to start when the initial loop ends. Here is the code I've got, which works even if it isn't what could be considered quality code: ``` function loop(){ for (let i = 0; i < header_phrases.length; i++){ (function (i) { setTimeout(function(){ header_txt.textContent = header_phrases[i]; }, 3000 * i); })(i); }; } loop(); setInterval(loop, 21000); ``` Is there a better way to right this code for both performance and quality? Do I need to use async? If so, any material I can see to learn more? Thanks!
2018/09/13
[ "https://Stackoverflow.com/questions/52305417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5791718/" ]
You can implement the same logic using recursion. ``` function recursify(phrases, index = 0) { header_txt.textContent = phrases[index]; setTimeout(function () { recursify(phrases, index < phrases.length - 1 ? index + 1 : 0); }, 300) } recursify(header_phrases); ``` The function 'recursify' will call itself after 300 miliseconds, but everytime this function gets called, the value of index will be different.
If I understand your requirement correctly, you want top populate an element from an array of values. A simple way to do this is: ``` doLoop(); function doLoop() { var phraseNo=0; setTimeout(next,21000); next(); function next() { header_txt.textContent = header_phrases[phraseNo++]; if(phraseNo>=header_phrases.length) phraseNo=0; } } ``` This simply puts the `next()` function on the queue and waits. The call to `next()` before the function simply starts it off without waiting for the timeout.
52,305,417
I have succeeded in cobbling together pieces of code that achieve my goal. However, I would like some advice from more advanced vanilla JS programmers on how I can go about reaching my goal in a better way. To start, I want to introduce my problem. I have a piece of text on my website where a portion is designed to change every so often. For this, I am running through a loop of phrases. To run this loop continuously, I first call the loop, then I call it again with setInterval timed to start when the initial loop ends. Here is the code I've got, which works even if it isn't what could be considered quality code: ``` function loop(){ for (let i = 0; i < header_phrases.length; i++){ (function (i) { setTimeout(function(){ header_txt.textContent = header_phrases[i]; }, 3000 * i); })(i); }; } loop(); setInterval(loop, 21000); ``` Is there a better way to right this code for both performance and quality? Do I need to use async? If so, any material I can see to learn more? Thanks!
2018/09/13
[ "https://Stackoverflow.com/questions/52305417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5791718/" ]
You can implement the same logic using recursion. ``` function recursify(phrases, index = 0) { header_txt.textContent = phrases[index]; setTimeout(function () { recursify(phrases, index < phrases.length - 1 ? index + 1 : 0); }, 300) } recursify(header_phrases); ``` The function 'recursify' will call itself after 300 miliseconds, but everytime this function gets called, the value of index will be different.
this is assuming that `header_txt` and `header_phrases` are not global vars. using global vars isn't a good idea. ``` var repeatIn = 3000; phraseUpdater(); function phraseUpdater() { var updateCount = 0, phrasesCount = header_phrases.length; setHeader(); setTimeout(setHeader, repeatIn); function setHeader() { header_txt.textContent = header_phrases[updateCount++ % phrasesCount] || ''; } } ```
73,194,227
How can I get printed console object value to HTML? I have JavaScript fetch code like this: ``` const comments = fetch("https://api.github.com/repos/pieceofdiy/comments/issues/1") .then((response) => response.json()) .then((labels) => { return labels.comments; }); const printComments = () => { comments.then((number) => { console.log(number); }); }; printComments() ``` printComments() numeric object value shows correct in console, but how to show it in HTML to `<span id="comments">..</span>` ?
2022/08/01
[ "https://Stackoverflow.com/questions/73194227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19666472/" ]
You can put the class into a factory function: ```py def make_DDN(Base): class DDN(Base): def other_methods(self): ... return DDN ``` Now you can make new classes: `DDN1 = make_DDN(BN)` etc
The working field of your program is unclear to me, and it is unclear what objects and their methods should be able to do, so this is a suggestion, not an answer. But it's too big for a comment. ``` class BN: def method(self): return self.data*2 class QBN(BN): def method(self,classic=False): if classic: return super().method() return self.data*3 class DDN(QBN): def __init__(self,data): self.data=data ```
19,177,967
the format is: 19 digits followed by an underscore followed by 4 digits ,followed by an underscore ,followed by 1 digit, followed by an underscore, followed by 1 capital letter, followed by an underscore, followed by 4 digits, followed by a dash, followed by 2 digits, followed by a dash, followed by 2 digits, followed by an underscore, followed by 2 digits, followed by a dash, followed by 2 digits, followed by a dash, followed by 2 digits and ending with a `".db"`extension Here are a few filenames, as i thought the above information would be boring to read. :) thanx in advance to anyone who answers. `2408002705100010002_0002_0_V_2012-11-02_06-35-24.db` `2408002705100010001_0001_0_V_2012-11-05_05-32-06.db` `2408001000200000002_0002_0_E_2012-03-03_00-20-06.db`
2013/10/04
[ "https://Stackoverflow.com/questions/19177967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2845977/" ]
`\d{19}_\d{4}_\d_[A-Z]_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.db` <http://gskinner.com/RegExr/> - a website to test your RegEx but I noticed that for example, in the middle you have sth like `_0002_` Do you accept any 4 digits or those that start with "000"?
``` \d{19}_\d{4}_\d_[A-Z]_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.db ``` This one also does a **basic** check on the date/time part (assuming date YYYY-MM-DD): ``` \d{19}_\d{4}_\d_[A-Z]_\d{4}-(0(?!0)|1(?=[0-2]))\d-(0(?!0)|[1-2]|3(?=[0-1]))\d_([0-1]|2(?=[0-3]))\d(-[0-5]\d){2}\.db ``` **Basic** check means you can still insert dates like February 30th, but not January 32nd.
19,177,967
the format is: 19 digits followed by an underscore followed by 4 digits ,followed by an underscore ,followed by 1 digit, followed by an underscore, followed by 1 capital letter, followed by an underscore, followed by 4 digits, followed by a dash, followed by 2 digits, followed by a dash, followed by 2 digits, followed by an underscore, followed by 2 digits, followed by a dash, followed by 2 digits, followed by a dash, followed by 2 digits and ending with a `".db"`extension Here are a few filenames, as i thought the above information would be boring to read. :) thanx in advance to anyone who answers. `2408002705100010002_0002_0_V_2012-11-02_06-35-24.db` `2408002705100010001_0001_0_V_2012-11-05_05-32-06.db` `2408001000200000002_0002_0_E_2012-03-03_00-20-06.db`
2013/10/04
[ "https://Stackoverflow.com/questions/19177967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2845977/" ]
`\d{19}_\d{4}_\d_[A-Z]_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.db` <http://gskinner.com/RegExr/> - a website to test your RegEx but I noticed that for example, in the middle you have sth like `_0002_` Do you accept any 4 digits or those that start with "000"?
Based on your data: ``` \d{19}_0+\d_0_(V|E)?_(-?(\d{2}|\d{4}))+_(-?\d{2})+\.db ``` If seeking more generic: ``` \d{19}_\d+_\d_[A-Z]?_\d{4}(-\d{2}){2}_(-?\d{2})+\.db ``` HTH EDIT: On a side note, I would rather split this string with `_`, and then validate each section individually based on some pattern and/or property. That way you will have more control over how this string must look.
15,922
I need to change the content within a `[count]` number of braces for each line in my buffer. ``` 1 {Lorem} ipsum dolor {amet} blah blah {change this text} more blah blah 2 Hello. The {sun} rises in {the} east. blah {blah}. {also change this text}. final blah ``` In `line 1`, I need to substitute the content within the `3rd` set of braces to `random forest`. For `line 2`, I need to change the text within `4th` set of braces to `alchemy`. I know of a naive method for doing this, i.e. for each line, first move the cursor to the desired braces and perform a `ci}` For the reasons of efficiency (as I am editing/proof-reading a large text-file with such markup), I wish to do these per-line substitutions ***without*** moving the cursor from `column 1` for each linewise substitution. How can I achieve this? Does `ex` mode help?
2018/04/14
[ "https://vi.stackexchange.com/questions/15922", "https://vi.stackexchange.com", "https://vi.stackexchange.com/users/8408/" ]
The [answer from @RubenWesterberg](https://vi.stackexchange.com/posts/15923/edit) is a correct sequence of Normal mode commands to do what you want. But I read your request to not move the cursor a little more literally. Also, if you need to make substitutions like this frequently you probably want something a bit less manual. You can use standard substitution in a mapping like this: ``` :nnoremap <expr> <leader>{ ':<c-u>s/\({.\{-}\)\{' . v:count1 . '}\zs[^}]*/' ``` This is used in Normal mode by entering `N\{` where `N` is the numerical 1-based "index" of the bracket pair within which you want to replace text. (I'm assuming you are using default `<leader>` key `\`). This will take you to the command-line with a pre-populated `:substitute` command. The cursor will be placed so you merely enter the replacement text followed by `Enter` and the work is done. Keep in mind that the value of `N` is counted from the current cursor position. It will still work if the cursor is not in the first column but if any brackets appear before the cursor they will not be counted. And `N` can be omitted in which case a default of index 1 will be used. --- **Update:** For fun, if we want to take the no-cursor-movement requirement to the extreme this version will add Normal mode command `0` after the substitution so you always end up back in the first column: ``` :nnoremap <expr> <leader>{ ':<c-u>s/\({.\{-}\)\{' . v:count1 . '}\zs[^}]*// \| norm! 0<c-left><c-left><c-left><left><left>' ``` --- **Update 2:** Didn't have time to do this earlier so here's a breakdown of the pattern in the substitution. If we have `N=3` then substitution renders as the following (with the cursor at the very end): ``` s/\({.\{-}\)\{3}\zs[^}]*/ ``` * `{.\{-}` - Match a left bracket, `{`, followed by zero or more characters until a later segment of the pattern is matched or the pattern end is reached. `.\{-}` is like `.*` except that the latter matches as many characters as possible while the former matches as few as possible. * `\(...\)\{3}` - Match the previous pattern exactly three times. * `\zs` - Indicates that the substitution will replace characters starting at this position rather than replacing the whole pattern match. In this case, it is the position of the first character inside the target bracket pair. * `[^}]*` - Match zero or more characters that are not `}` or, in other words, match everything inside the target bracket pair.
Execute the following in normal mode on the first line: ``` 2f{ci{REPLACEMENT_TEXT<ESC>0 ``` This will find the target brace, change the content to REPLACEMENT\_TEXT and then return the cursor back to the beginning of the line. For the second line: ``` 4f{ci{REPLACEMENT_TEXT<ESC>0 ``` Note that the exact number of braces to search for depend on if the first character on the line is a brace.
31,914,083
I want to know is there any way to connect my android app with MS SQL Server 2012 and retrieve data from there instead of using `phpmyAdmin.` i know same type of question has been asked already but that was not clear and answers were not helpful as well. i'm searching for full tutorial as I'm pretty new to this thing. Thanks in advance.
2015/08/10
[ "https://Stackoverflow.com/questions/31914083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627060/" ]
You should use radiobuttons in this way. ```css body { font-family: sans-serif; font-weight: normal; margin: 10px; color: #999; background-color: #eee; } form { margin: 40px 0; } div { clear: both; margin: 0 50px; } label { width: 200px; border-radius: 3px; border: 1px solid #D1D3D4 } input.radio:empty { margin-left: -999px; } input.radio:empty ~ label { position: relative; float: left; line-height: 2.5em; text-indent: 3.25em; margin-top: 2em; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } input.radio:empty ~ label:before { position: absolute; display: block; top: 0; bottom: 0; left: 0; content: ''; width: 2.5em; background: #D1D3D4; border-radius: 3px 0 0 3px; } input.radio:hover:not(:checked) ~ label:before { content:'\2714'; text-indent: .9em; color: #C2C2C2; } input.radio:hover:not(:checked) ~ label { color: #888; } input.radio:checked ~ label:before { content:'\2714'; text-indent: .9em; color: #9CE2AE; background-color: #4DCB6D; } input.radio:checked ~ label { color: #777; } input.radio:focus ~ label:before { box-shadow: 0 0 0 3px #999; } ``` ```html <div> <input type="radio" name="radio" id="radio1" class="radio" checked/> <label for="radio1">Apple</label> </div> <div> <input type="radio" name="radio" id="radio2" class="radio"/> <label for="radio2">Samsung</label> </div> <div> <input type="radio" name="radio" id="radio3" class="radio"/> <label for="radio3">Sony</label> </div> ```
`Button` are used for buttons ``` <div class="btn-group btn-group-lg"> <input type="radio" class="btn btn-primary" value="Apple" name="radio"> Apple <input type="radio" class="btn btn-primary" value= "Samsung" name="radio"> Samsung <input type="radio" class="btn btn-primary" value "Sony" name="radio"> Sony </div> ``` Radios are `<input type="radio">`. If you want only one radio checked they have to get the same `name`.
31,914,083
I want to know is there any way to connect my android app with MS SQL Server 2012 and retrieve data from there instead of using `phpmyAdmin.` i know same type of question has been asked already but that was not clear and answers were not helpful as well. i'm searching for full tutorial as I'm pretty new to this thing. Thanks in advance.
2015/08/10
[ "https://Stackoverflow.com/questions/31914083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627060/" ]
This seems to be exactly what are you searching for. ``` <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> <input type="radio" name="options" id="option1" checked> Apple </label> <label class="btn btn-primary"> <input type="radio" name="options" id="option2"> Samsung </label> <label class="btn btn-primary"> <input type="radio" name="options" id="option3"> Sony </label> </div> ``` You can read more about this [under this link](http://getbootstrap.com/javascript/#buttons-checkbox-radio). This is how it looks like: [![enter image description here](https://i.stack.imgur.com/ot2b3.png)](https://i.stack.imgur.com/ot2b3.png)
You should use radiobuttons in this way. ```css body { font-family: sans-serif; font-weight: normal; margin: 10px; color: #999; background-color: #eee; } form { margin: 40px 0; } div { clear: both; margin: 0 50px; } label { width: 200px; border-radius: 3px; border: 1px solid #D1D3D4 } input.radio:empty { margin-left: -999px; } input.radio:empty ~ label { position: relative; float: left; line-height: 2.5em; text-indent: 3.25em; margin-top: 2em; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } input.radio:empty ~ label:before { position: absolute; display: block; top: 0; bottom: 0; left: 0; content: ''; width: 2.5em; background: #D1D3D4; border-radius: 3px 0 0 3px; } input.radio:hover:not(:checked) ~ label:before { content:'\2714'; text-indent: .9em; color: #C2C2C2; } input.radio:hover:not(:checked) ~ label { color: #888; } input.radio:checked ~ label:before { content:'\2714'; text-indent: .9em; color: #9CE2AE; background-color: #4DCB6D; } input.radio:checked ~ label { color: #777; } input.radio:focus ~ label:before { box-shadow: 0 0 0 3px #999; } ``` ```html <div> <input type="radio" name="radio" id="radio1" class="radio" checked/> <label for="radio1">Apple</label> </div> <div> <input type="radio" name="radio" id="radio2" class="radio"/> <label for="radio2">Samsung</label> </div> <div> <input type="radio" name="radio" id="radio3" class="radio"/> <label for="radio3">Sony</label> </div> ```
31,914,083
I want to know is there any way to connect my android app with MS SQL Server 2012 and retrieve data from there instead of using `phpmyAdmin.` i know same type of question has been asked already but that was not clear and answers were not helpful as well. i'm searching for full tutorial as I'm pretty new to this thing. Thanks in advance.
2015/08/10
[ "https://Stackoverflow.com/questions/31914083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627060/" ]
You should use radiobuttons in this way. ```css body { font-family: sans-serif; font-weight: normal; margin: 10px; color: #999; background-color: #eee; } form { margin: 40px 0; } div { clear: both; margin: 0 50px; } label { width: 200px; border-radius: 3px; border: 1px solid #D1D3D4 } input.radio:empty { margin-left: -999px; } input.radio:empty ~ label { position: relative; float: left; line-height: 2.5em; text-indent: 3.25em; margin-top: 2em; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } input.radio:empty ~ label:before { position: absolute; display: block; top: 0; bottom: 0; left: 0; content: ''; width: 2.5em; background: #D1D3D4; border-radius: 3px 0 0 3px; } input.radio:hover:not(:checked) ~ label:before { content:'\2714'; text-indent: .9em; color: #C2C2C2; } input.radio:hover:not(:checked) ~ label { color: #888; } input.radio:checked ~ label:before { content:'\2714'; text-indent: .9em; color: #9CE2AE; background-color: #4DCB6D; } input.radio:checked ~ label { color: #777; } input.radio:focus ~ label:before { box-shadow: 0 0 0 3px #999; } ``` ```html <div> <input type="radio" name="radio" id="radio1" class="radio" checked/> <label for="radio1">Apple</label> </div> <div> <input type="radio" name="radio" id="radio2" class="radio"/> <label for="radio2">Samsung</label> </div> <div> <input type="radio" name="radio" id="radio3" class="radio"/> <label for="radio3">Sony</label> </div> ```
For Bootstrap 4: ``` <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary active"> <input type="radio" name="options" id="option1" autocomplete="off" checked> Active </label> <label class="btn btn-secondary"> <input type="radio" name="options" id="option2" autocomplete="off"> Radio </label> <label class="btn btn-secondary"> <input type="radio" name="options" id="option3" autocomplete="off"> Radio </label> </div> ``` [See the docs](https://getbootstrap.com/docs/4.0/components/buttons/#checkbox-and-radio-buttons)
31,914,083
I want to know is there any way to connect my android app with MS SQL Server 2012 and retrieve data from there instead of using `phpmyAdmin.` i know same type of question has been asked already but that was not clear and answers were not helpful as well. i'm searching for full tutorial as I'm pretty new to this thing. Thanks in advance.
2015/08/10
[ "https://Stackoverflow.com/questions/31914083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627060/" ]
This seems to be exactly what are you searching for. ``` <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> <input type="radio" name="options" id="option1" checked> Apple </label> <label class="btn btn-primary"> <input type="radio" name="options" id="option2"> Samsung </label> <label class="btn btn-primary"> <input type="radio" name="options" id="option3"> Sony </label> </div> ``` You can read more about this [under this link](http://getbootstrap.com/javascript/#buttons-checkbox-radio). This is how it looks like: [![enter image description here](https://i.stack.imgur.com/ot2b3.png)](https://i.stack.imgur.com/ot2b3.png)
`Button` are used for buttons ``` <div class="btn-group btn-group-lg"> <input type="radio" class="btn btn-primary" value="Apple" name="radio"> Apple <input type="radio" class="btn btn-primary" value= "Samsung" name="radio"> Samsung <input type="radio" class="btn btn-primary" value "Sony" name="radio"> Sony </div> ``` Radios are `<input type="radio">`. If you want only one radio checked they have to get the same `name`.
31,914,083
I want to know is there any way to connect my android app with MS SQL Server 2012 and retrieve data from there instead of using `phpmyAdmin.` i know same type of question has been asked already but that was not clear and answers were not helpful as well. i'm searching for full tutorial as I'm pretty new to this thing. Thanks in advance.
2015/08/10
[ "https://Stackoverflow.com/questions/31914083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627060/" ]
For Bootstrap 4: ``` <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary active"> <input type="radio" name="options" id="option1" autocomplete="off" checked> Active </label> <label class="btn btn-secondary"> <input type="radio" name="options" id="option2" autocomplete="off"> Radio </label> <label class="btn btn-secondary"> <input type="radio" name="options" id="option3" autocomplete="off"> Radio </label> </div> ``` [See the docs](https://getbootstrap.com/docs/4.0/components/buttons/#checkbox-and-radio-buttons)
`Button` are used for buttons ``` <div class="btn-group btn-group-lg"> <input type="radio" class="btn btn-primary" value="Apple" name="radio"> Apple <input type="radio" class="btn btn-primary" value= "Samsung" name="radio"> Samsung <input type="radio" class="btn btn-primary" value "Sony" name="radio"> Sony </div> ``` Radios are `<input type="radio">`. If you want only one radio checked they have to get the same `name`.
31,914,083
I want to know is there any way to connect my android app with MS SQL Server 2012 and retrieve data from there instead of using `phpmyAdmin.` i know same type of question has been asked already but that was not clear and answers were not helpful as well. i'm searching for full tutorial as I'm pretty new to this thing. Thanks in advance.
2015/08/10
[ "https://Stackoverflow.com/questions/31914083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4627060/" ]
This seems to be exactly what are you searching for. ``` <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> <input type="radio" name="options" id="option1" checked> Apple </label> <label class="btn btn-primary"> <input type="radio" name="options" id="option2"> Samsung </label> <label class="btn btn-primary"> <input type="radio" name="options" id="option3"> Sony </label> </div> ``` You can read more about this [under this link](http://getbootstrap.com/javascript/#buttons-checkbox-radio). This is how it looks like: [![enter image description here](https://i.stack.imgur.com/ot2b3.png)](https://i.stack.imgur.com/ot2b3.png)
For Bootstrap 4: ``` <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary active"> <input type="radio" name="options" id="option1" autocomplete="off" checked> Active </label> <label class="btn btn-secondary"> <input type="radio" name="options" id="option2" autocomplete="off"> Radio </label> <label class="btn btn-secondary"> <input type="radio" name="options" id="option3" autocomplete="off"> Radio </label> </div> ``` [See the docs](https://getbootstrap.com/docs/4.0/components/buttons/#checkbox-and-radio-buttons)
2,941,351
1. Suppose that **$f: A→B$** and **$g:B→C$** are functions such that **$g◦f$** is *injective*. **Prove** that **$f$** must be *injective.* 2. Construct a *bijective* function $f:R→ (R\setminus \{0\})$. **Prove** that your function is actually a *bijective* function. Can someone help me on how do I prove it?
2018/10/03
[ "https://math.stackexchange.com/questions/2941351", "https://math.stackexchange.com", "https://math.stackexchange.com/users/584006/" ]
Set $x=-1+h\;$ ($h\to 0$) and use the binomial approximation: * $\sqrt[3]{1+2(-1+h)}+1=1-\sqrt[3]{1-2h}=1-\bigl(1-\frac23 h+o(h)\bigl)=\frac23 h+o(h)$, * $\sqrt{2+(-1+h)}-1+h=\sqrt{1+h}-1+h=1+\frac12h+o(h)-1+h=\frac32h+o(h),$ so $\;\dfrac{\sqrt[3]{1+2x}+1}{\sqrt{2+x} + x}=\dfrac{\frac23 h+o(h)}{\frac32h+o(h)})=\dfrac{\frac23+o(1)}{\frac32+o(1)}=\dfrac49+o(1).$
L'Hospital works: $$\lim\_{x\to{-1}} \frac{\sqrt[3]{1+2x}+1}{\sqrt{2+x} + x}=\lim\_{x\to{-1}} \frac{\dfrac2{3(\sqrt[3]{1+2x})^2}}{\dfrac1{2\sqrt{2+x}} + 1}=\frac49.$$
2,941,351
1. Suppose that **$f: A→B$** and **$g:B→C$** are functions such that **$g◦f$** is *injective*. **Prove** that **$f$** must be *injective.* 2. Construct a *bijective* function $f:R→ (R\setminus \{0\})$. **Prove** that your function is actually a *bijective* function. Can someone help me on how do I prove it?
2018/10/03
[ "https://math.stackexchange.com/questions/2941351", "https://math.stackexchange.com", "https://math.stackexchange.com/users/584006/" ]
Recall the formulas: $$ \begin{align} a^2 -b^2 &= (a - b)(a + b)\\ a^3 + b^3 &= (a + b)(a^2 - ab + b^2) \end{align} $$ Using them we can get the following: $$ \begin{align} \sqrt[3]{1+2x} + 1 &= \frac{1 + 2x + 1}{{\sqrt[3]{1+2x}}^2 - \sqrt[3]{1+2x} + 1} = \frac{2(x + 1)}{{\sqrt[3]{1+2x}}^2 - \sqrt[3]{1+2x} + 1} \\ \sqrt{2+x} + x &= \frac{2 + x - x^2}{\sqrt{2+x} - x} = -\frac{(x + 1)(x - 2)}{\sqrt{2+x} - x} \end{align} $$ Therefore, your limit is equal to $$ \lim\_{x\to{-1}} \frac{\sqrt[3]{1+2x}+1}{\sqrt{2+x} + x} = \lim\_{x\to{-1}} -\frac{2(\sqrt{2+x} - x)}{(x - 2)({\sqrt[3]{1+2x}}^2 - \sqrt[3]{1+2x} + 1)}, $$ which is pretty straightforward to compute.
L'Hospital works: $$\lim\_{x\to{-1}} \frac{\sqrt[3]{1+2x}+1}{\sqrt{2+x} + x}=\lim\_{x\to{-1}} \frac{\dfrac2{3(\sqrt[3]{1+2x})^2}}{\dfrac1{2\sqrt{2+x}} + 1}=\frac49.$$
67,106,912
I have a pandas dataframe where 'Column1' and 'Column2' contain lists of words in every row. I need to create a new column with the number of words repeated in Column1's list and Column2's list for every row. For example, in an especific row I could have ['apple', 'banana'] in Column1, ['banana', 'orange'] in Column2, and I need to add a third new column containing the number '1', since only one word (banana) is in both lists. I tried to do it like this: ``` for index, row in df.iterrows(): value = len(list(set(row['Column1']) & set(row['Column2']))) row['new_column'] = value ``` But the new column did not appear in the dataframe. I tried a second approach, creating the column first and setting it to 0 and then updating the values like this: ``` df['new_column'] = 0 for index, row in df.iterrows(): value = len(list(set(row['Column1']) & set(row['Column2']))) df.at[index,'new_column'] = value ``` But this didn't work either, the column is not updated. I tried a third approach using .apply like this: ``` df['new_column'] = df.apply(lambda x: len(list(set(x['Column1']) & set(x['Column2']))) ``` And then I got this error: ``` KeyError: 'Column1' ``` I don't know why any of this is working and neither I know any other way to try it. How can I make this work? Thank you!
2021/04/15
[ "https://Stackoverflow.com/questions/67106912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484895/" ]
In the end, the only way I could find to fix the issue is to use the choose element instead of validate-jwt, with custom code (which is what I was hoping to avoid any way). Basically I am saving the validated JWT Token to a variable and then using if / elseif to determine if the token is acceptable. Working relevant configuration below ``` <validate-jwt header-name="Authorization" failed-validation-httpcode="401" require-scheme="Bearer" output-token-variable-name="valid-jwt"> <openid-config url="https://login.microsoftonline.com/tenantid/v2.0/.well-known/openid-configuration" /> <issuers> <issuer>https://sts.windows.net/tenantid/</issuer> </issuers> </validate-jwt> <choose> <when condition="@{ var jwt = (Jwt)context.Variables["valid-jwt"]; if(jwt.Claims.ContainsKey("roles")){ var roles = jwt.Claims["roles"]; return !Array.Exists(roles, element => element == "MyRoleName"); } else if (jwt.Claims.ContainsKey("scp")){ var scp = jwt.Claims["scp"]; return !Array.Exists(scp, element => element == "user_impersonation"); } else { return true; } }"> <return-response> <set-status code="401" reason="Unauthorized" /> </return-response> </when> <otherwise /> </choose> ```
As you mentioned the token may contain either the `scp` cllaim or `roles` claim, it seems your token sometimes generated in "Delegated" type and sometimes generated in "Application" type. You just need to configure the `<validate-jwt>` policy like below screenshot, add both of the claims in it and choose "**Any claim**". [![enter image description here](https://i.stack.imgur.com/5qxnk.png)](https://i.stack.imgur.com/5qxnk.png) After that, the token can be validated if it just contain one claim. By the way, please check if your tokens in two situations have same "Audiences", otherwise your requirement may not be implemented by the configuration above.
112,580
I work in the USA and was recently placed on a 90-day performance improvement plan (PIP) with my company. Just shy of my 60-day PIP review, I was terminated. I was only with the company for 7 months, but they very graciously gave me a *3-and-a-half month* severance package with full salary and benefits. That's not a typo: after it's all said & done, they will have effectively paid time-and-a-half for my brief employment. Obviously, they felt I wasn't a good fit for the job but maybe "felt bad" about letting me go? Is there anything to be read into such a generous severance for such a short tenure? I do feel like I drew the short end of the stick from an *employment* standpoint, as the job ended up being very different than it was laid out to me in the original job description. Does it seem like the company agrees with this assessment and is trying to make ammends by giving me such a generous severance? Furthermore, is this appropriate to bring up in future interviews? Almost like saying, "the company felt that I wasn't a great fit for the job but thought so highly of me as an individual that they gave me an incredible severance package." Or something to that effect.
2018/05/20
[ "https://workplace.stackexchange.com/questions/112580", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/66509/" ]
> > Furthermore, is this appropriate to bring up in future interviews? > > > No. Future employers won't care about your severance package. And you don't really know why you got the severance that you did. It might be because you were an outstanding worker. Or it might just be standard procedure. Future employers won't care. Future employers will care that you were put on a PIP after only 5 months and then dismissed without even waiting for the 90-day period to expire. There's nothing good in that. Try to avoid the entire topic if you can.
> > Furthermore, is this appropriate to bring up in future interviews? > > > No. Nobody but your bank manager and your close family care about your severance package. You can ask why you got the severance package you did - and you should, because it will be educational for you. At a guess, you worked at Netflix, which has a standard procedure to give high severance packages. This is to encourage management to fire staff that are not performing, because now the managers don't feel so bad about it. It's a great trick, and helpful to management. It does not sell you to another employer though, so I would not bring it up. *Note* this is different to bringing up your last bonus, which you should do as that shows how valued you are and can be used as leverage for a sign-on bonus.
112,580
I work in the USA and was recently placed on a 90-day performance improvement plan (PIP) with my company. Just shy of my 60-day PIP review, I was terminated. I was only with the company for 7 months, but they very graciously gave me a *3-and-a-half month* severance package with full salary and benefits. That's not a typo: after it's all said & done, they will have effectively paid time-and-a-half for my brief employment. Obviously, they felt I wasn't a good fit for the job but maybe "felt bad" about letting me go? Is there anything to be read into such a generous severance for such a short tenure? I do feel like I drew the short end of the stick from an *employment* standpoint, as the job ended up being very different than it was laid out to me in the original job description. Does it seem like the company agrees with this assessment and is trying to make ammends by giving me such a generous severance? Furthermore, is this appropriate to bring up in future interviews? Almost like saying, "the company felt that I wasn't a great fit for the job but thought so highly of me as an individual that they gave me an incredible severance package." Or something to that effect.
2018/05/20
[ "https://workplace.stackexchange.com/questions/112580", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/66509/" ]
> > Furthermore, is this appropriate to bring up in future interviews? > > > No. Future employers won't care about your severance package. And you don't really know why you got the severance that you did. It might be because you were an outstanding worker. Or it might just be standard procedure. Future employers won't care. Future employers will care that you were put on a PIP after only 5 months and then dismissed without even waiting for the 90-day period to expire. There's nothing good in that. Try to avoid the entire topic if you can.
**No** I know it's been answered already, but just to throw in a new reason for the "No". If they thought highly of you, they'd keep you on! It's unlikely that they thought you were a bad employee, but such a nice guy that they'd give you a nice golden parachute unless you happened to be great friends with/have some dirt on the manager! If I were an interviewer, I'd entertain the possibility that they wanted to get rid of you *before* the remaining 2 months were up, and the extra money (which is actually just 1.5 months salary to them since they're saving the 2 months they would have paid you) is to stop you kicking up a fuss about early termination / not being allowed to complete your PIP...
112,580
I work in the USA and was recently placed on a 90-day performance improvement plan (PIP) with my company. Just shy of my 60-day PIP review, I was terminated. I was only with the company for 7 months, but they very graciously gave me a *3-and-a-half month* severance package with full salary and benefits. That's not a typo: after it's all said & done, they will have effectively paid time-and-a-half for my brief employment. Obviously, they felt I wasn't a good fit for the job but maybe "felt bad" about letting me go? Is there anything to be read into such a generous severance for such a short tenure? I do feel like I drew the short end of the stick from an *employment* standpoint, as the job ended up being very different than it was laid out to me in the original job description. Does it seem like the company agrees with this assessment and is trying to make ammends by giving me such a generous severance? Furthermore, is this appropriate to bring up in future interviews? Almost like saying, "the company felt that I wasn't a great fit for the job but thought so highly of me as an individual that they gave me an incredible severance package." Or something to that effect.
2018/05/20
[ "https://workplace.stackexchange.com/questions/112580", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/66509/" ]
> > Furthermore, is this appropriate to bring up in future interviews? > > > No. Future employers won't care about your severance package. And you don't really know why you got the severance that you did. It might be because you were an outstanding worker. Or it might just be standard procedure. Future employers won't care. Future employers will care that you were put on a PIP after only 5 months and then dismissed without even waiting for the 90-day period to expire. There's nothing good in that. Try to avoid the entire topic if you can.
Short answer, **NO** Longer answer This is becoming more and more common of a practice, as it's extending to paying people to quit. [Amazon](http://www.msn.com/en-us/money/companies/why-amazon-pays-employees-dollar5000-to-quit/ar-AAxAqrT?ocid=ientp), for example, sees this as beneficial to the company to get rid of people who don't want to be there. When it comes to employees who are underperforming or just a bad fit, it is better for all parties concerned to take this approach rather than the traditional one. It's less rough on the employee, management does not have to build a massive file, and an employee does not have a "fired for cause" on their record. It's not strange or odd, just very expedient for the company. If they pay you to go away, they're far less likely to get sued, have difficulties from past employees slamming them on sites like glass door, and managers are less likely to retain someone out of guilt. It's a very expedient way to handle the problem of terminating employees. To be a bit blunt, it's a way of telling you to go to Hell in such a way as to have you look forward to the trip. Nothing more. Do not volunteer this information. To those employers who do not practice this, they may view it as you being so bad as your previous employer thought it worth the money to be rid of you.
112,580
I work in the USA and was recently placed on a 90-day performance improvement plan (PIP) with my company. Just shy of my 60-day PIP review, I was terminated. I was only with the company for 7 months, but they very graciously gave me a *3-and-a-half month* severance package with full salary and benefits. That's not a typo: after it's all said & done, they will have effectively paid time-and-a-half for my brief employment. Obviously, they felt I wasn't a good fit for the job but maybe "felt bad" about letting me go? Is there anything to be read into such a generous severance for such a short tenure? I do feel like I drew the short end of the stick from an *employment* standpoint, as the job ended up being very different than it was laid out to me in the original job description. Does it seem like the company agrees with this assessment and is trying to make ammends by giving me such a generous severance? Furthermore, is this appropriate to bring up in future interviews? Almost like saying, "the company felt that I wasn't a great fit for the job but thought so highly of me as an individual that they gave me an incredible severance package." Or something to that effect.
2018/05/20
[ "https://workplace.stackexchange.com/questions/112580", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/66509/" ]
> > Furthermore, is this appropriate to bring up in future interviews? > > > No. Future employers won't care about your severance package. And you don't really know why you got the severance that you did. It might be because you were an outstanding worker. Or it might just be standard procedure. Future employers won't care. Future employers will care that you were put on a PIP after only 5 months and then dismissed without even waiting for the 90-day period to expire. There's nothing good in that. Try to avoid the entire topic if you can.
If I were a hiring manager and you told me that story, I'd probably assume you must've done something really bad if they're willing to dole out that kind of free money just to get you out the door. I'd say, don't mention the severance or the PIP. Instead just say something like, > > "There were some discrepancies between the description and the actual requirements and, after several months, we agreed the position wasn't a good fit for my skill set. I thought I would be spending the bulk of my time working on x but the job turned out to be mostly y." > > > Per @dwizum--you should also prepare for the interview by thinking of specific questions about the job to show that you're making a serious effort to prevent repeating the same mistake.
112,580
I work in the USA and was recently placed on a 90-day performance improvement plan (PIP) with my company. Just shy of my 60-day PIP review, I was terminated. I was only with the company for 7 months, but they very graciously gave me a *3-and-a-half month* severance package with full salary and benefits. That's not a typo: after it's all said & done, they will have effectively paid time-and-a-half for my brief employment. Obviously, they felt I wasn't a good fit for the job but maybe "felt bad" about letting me go? Is there anything to be read into such a generous severance for such a short tenure? I do feel like I drew the short end of the stick from an *employment* standpoint, as the job ended up being very different than it was laid out to me in the original job description. Does it seem like the company agrees with this assessment and is trying to make ammends by giving me such a generous severance? Furthermore, is this appropriate to bring up in future interviews? Almost like saying, "the company felt that I wasn't a great fit for the job but thought so highly of me as an individual that they gave me an incredible severance package." Or something to that effect.
2018/05/20
[ "https://workplace.stackexchange.com/questions/112580", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/66509/" ]
> > Furthermore, is this appropriate to bring up in future interviews? > > > No. Nobody but your bank manager and your close family care about your severance package. You can ask why you got the severance package you did - and you should, because it will be educational for you. At a guess, you worked at Netflix, which has a standard procedure to give high severance packages. This is to encourage management to fire staff that are not performing, because now the managers don't feel so bad about it. It's a great trick, and helpful to management. It does not sell you to another employer though, so I would not bring it up. *Note* this is different to bringing up your last bonus, which you should do as that shows how valued you are and can be used as leverage for a sign-on bonus.
**No** I know it's been answered already, but just to throw in a new reason for the "No". If they thought highly of you, they'd keep you on! It's unlikely that they thought you were a bad employee, but such a nice guy that they'd give you a nice golden parachute unless you happened to be great friends with/have some dirt on the manager! If I were an interviewer, I'd entertain the possibility that they wanted to get rid of you *before* the remaining 2 months were up, and the extra money (which is actually just 1.5 months salary to them since they're saving the 2 months they would have paid you) is to stop you kicking up a fuss about early termination / not being allowed to complete your PIP...
112,580
I work in the USA and was recently placed on a 90-day performance improvement plan (PIP) with my company. Just shy of my 60-day PIP review, I was terminated. I was only with the company for 7 months, but they very graciously gave me a *3-and-a-half month* severance package with full salary and benefits. That's not a typo: after it's all said & done, they will have effectively paid time-and-a-half for my brief employment. Obviously, they felt I wasn't a good fit for the job but maybe "felt bad" about letting me go? Is there anything to be read into such a generous severance for such a short tenure? I do feel like I drew the short end of the stick from an *employment* standpoint, as the job ended up being very different than it was laid out to me in the original job description. Does it seem like the company agrees with this assessment and is trying to make ammends by giving me such a generous severance? Furthermore, is this appropriate to bring up in future interviews? Almost like saying, "the company felt that I wasn't a great fit for the job but thought so highly of me as an individual that they gave me an incredible severance package." Or something to that effect.
2018/05/20
[ "https://workplace.stackexchange.com/questions/112580", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/66509/" ]
> > Furthermore, is this appropriate to bring up in future interviews? > > > No. Nobody but your bank manager and your close family care about your severance package. You can ask why you got the severance package you did - and you should, because it will be educational for you. At a guess, you worked at Netflix, which has a standard procedure to give high severance packages. This is to encourage management to fire staff that are not performing, because now the managers don't feel so bad about it. It's a great trick, and helpful to management. It does not sell you to another employer though, so I would not bring it up. *Note* this is different to bringing up your last bonus, which you should do as that shows how valued you are and can be used as leverage for a sign-on bonus.
Short answer, **NO** Longer answer This is becoming more and more common of a practice, as it's extending to paying people to quit. [Amazon](http://www.msn.com/en-us/money/companies/why-amazon-pays-employees-dollar5000-to-quit/ar-AAxAqrT?ocid=ientp), for example, sees this as beneficial to the company to get rid of people who don't want to be there. When it comes to employees who are underperforming or just a bad fit, it is better for all parties concerned to take this approach rather than the traditional one. It's less rough on the employee, management does not have to build a massive file, and an employee does not have a "fired for cause" on their record. It's not strange or odd, just very expedient for the company. If they pay you to go away, they're far less likely to get sued, have difficulties from past employees slamming them on sites like glass door, and managers are less likely to retain someone out of guilt. It's a very expedient way to handle the problem of terminating employees. To be a bit blunt, it's a way of telling you to go to Hell in such a way as to have you look forward to the trip. Nothing more. Do not volunteer this information. To those employers who do not practice this, they may view it as you being so bad as your previous employer thought it worth the money to be rid of you.
112,580
I work in the USA and was recently placed on a 90-day performance improvement plan (PIP) with my company. Just shy of my 60-day PIP review, I was terminated. I was only with the company for 7 months, but they very graciously gave me a *3-and-a-half month* severance package with full salary and benefits. That's not a typo: after it's all said & done, they will have effectively paid time-and-a-half for my brief employment. Obviously, they felt I wasn't a good fit for the job but maybe "felt bad" about letting me go? Is there anything to be read into such a generous severance for such a short tenure? I do feel like I drew the short end of the stick from an *employment* standpoint, as the job ended up being very different than it was laid out to me in the original job description. Does it seem like the company agrees with this assessment and is trying to make ammends by giving me such a generous severance? Furthermore, is this appropriate to bring up in future interviews? Almost like saying, "the company felt that I wasn't a great fit for the job but thought so highly of me as an individual that they gave me an incredible severance package." Or something to that effect.
2018/05/20
[ "https://workplace.stackexchange.com/questions/112580", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/66509/" ]
> > Furthermore, is this appropriate to bring up in future interviews? > > > No. Nobody but your bank manager and your close family care about your severance package. You can ask why you got the severance package you did - and you should, because it will be educational for you. At a guess, you worked at Netflix, which has a standard procedure to give high severance packages. This is to encourage management to fire staff that are not performing, because now the managers don't feel so bad about it. It's a great trick, and helpful to management. It does not sell you to another employer though, so I would not bring it up. *Note* this is different to bringing up your last bonus, which you should do as that shows how valued you are and can be used as leverage for a sign-on bonus.
If I were a hiring manager and you told me that story, I'd probably assume you must've done something really bad if they're willing to dole out that kind of free money just to get you out the door. I'd say, don't mention the severance or the PIP. Instead just say something like, > > "There were some discrepancies between the description and the actual requirements and, after several months, we agreed the position wasn't a good fit for my skill set. I thought I would be spending the bulk of my time working on x but the job turned out to be mostly y." > > > Per @dwizum--you should also prepare for the interview by thinking of specific questions about the job to show that you're making a serious effort to prevent repeating the same mistake.
112,580
I work in the USA and was recently placed on a 90-day performance improvement plan (PIP) with my company. Just shy of my 60-day PIP review, I was terminated. I was only with the company for 7 months, but they very graciously gave me a *3-and-a-half month* severance package with full salary and benefits. That's not a typo: after it's all said & done, they will have effectively paid time-and-a-half for my brief employment. Obviously, they felt I wasn't a good fit for the job but maybe "felt bad" about letting me go? Is there anything to be read into such a generous severance for such a short tenure? I do feel like I drew the short end of the stick from an *employment* standpoint, as the job ended up being very different than it was laid out to me in the original job description. Does it seem like the company agrees with this assessment and is trying to make ammends by giving me such a generous severance? Furthermore, is this appropriate to bring up in future interviews? Almost like saying, "the company felt that I wasn't a great fit for the job but thought so highly of me as an individual that they gave me an incredible severance package." Or something to that effect.
2018/05/20
[ "https://workplace.stackexchange.com/questions/112580", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/66509/" ]
Short answer, **NO** Longer answer This is becoming more and more common of a practice, as it's extending to paying people to quit. [Amazon](http://www.msn.com/en-us/money/companies/why-amazon-pays-employees-dollar5000-to-quit/ar-AAxAqrT?ocid=ientp), for example, sees this as beneficial to the company to get rid of people who don't want to be there. When it comes to employees who are underperforming or just a bad fit, it is better for all parties concerned to take this approach rather than the traditional one. It's less rough on the employee, management does not have to build a massive file, and an employee does not have a "fired for cause" on their record. It's not strange or odd, just very expedient for the company. If they pay you to go away, they're far less likely to get sued, have difficulties from past employees slamming them on sites like glass door, and managers are less likely to retain someone out of guilt. It's a very expedient way to handle the problem of terminating employees. To be a bit blunt, it's a way of telling you to go to Hell in such a way as to have you look forward to the trip. Nothing more. Do not volunteer this information. To those employers who do not practice this, they may view it as you being so bad as your previous employer thought it worth the money to be rid of you.
**No** I know it's been answered already, but just to throw in a new reason for the "No". If they thought highly of you, they'd keep you on! It's unlikely that they thought you were a bad employee, but such a nice guy that they'd give you a nice golden parachute unless you happened to be great friends with/have some dirt on the manager! If I were an interviewer, I'd entertain the possibility that they wanted to get rid of you *before* the remaining 2 months were up, and the extra money (which is actually just 1.5 months salary to them since they're saving the 2 months they would have paid you) is to stop you kicking up a fuss about early termination / not being allowed to complete your PIP...
112,580
I work in the USA and was recently placed on a 90-day performance improvement plan (PIP) with my company. Just shy of my 60-day PIP review, I was terminated. I was only with the company for 7 months, but they very graciously gave me a *3-and-a-half month* severance package with full salary and benefits. That's not a typo: after it's all said & done, they will have effectively paid time-and-a-half for my brief employment. Obviously, they felt I wasn't a good fit for the job but maybe "felt bad" about letting me go? Is there anything to be read into such a generous severance for such a short tenure? I do feel like I drew the short end of the stick from an *employment* standpoint, as the job ended up being very different than it was laid out to me in the original job description. Does it seem like the company agrees with this assessment and is trying to make ammends by giving me such a generous severance? Furthermore, is this appropriate to bring up in future interviews? Almost like saying, "the company felt that I wasn't a great fit for the job but thought so highly of me as an individual that they gave me an incredible severance package." Or something to that effect.
2018/05/20
[ "https://workplace.stackexchange.com/questions/112580", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/66509/" ]
If I were a hiring manager and you told me that story, I'd probably assume you must've done something really bad if they're willing to dole out that kind of free money just to get you out the door. I'd say, don't mention the severance or the PIP. Instead just say something like, > > "There were some discrepancies between the description and the actual requirements and, after several months, we agreed the position wasn't a good fit for my skill set. I thought I would be spending the bulk of my time working on x but the job turned out to be mostly y." > > > Per @dwizum--you should also prepare for the interview by thinking of specific questions about the job to show that you're making a serious effort to prevent repeating the same mistake.
**No** I know it's been answered already, but just to throw in a new reason for the "No". If they thought highly of you, they'd keep you on! It's unlikely that they thought you were a bad employee, but such a nice guy that they'd give you a nice golden parachute unless you happened to be great friends with/have some dirt on the manager! If I were an interviewer, I'd entertain the possibility that they wanted to get rid of you *before* the remaining 2 months were up, and the extra money (which is actually just 1.5 months salary to them since they're saving the 2 months they would have paid you) is to stop you kicking up a fuss about early termination / not being allowed to complete your PIP...
81,793
In 2012, Canon introduced remote radio control into its flashes with the introduction of the 600EX-RT speedlite. Canon master/slaves flashes in this system now include: * 600EX-RT * 600EX-RT II * 430EX III-RT And there's a headless transmitter (master) unit, the ST-E3-RT. 3rd-party speedlights and transmitter/receivers that can be used in conjunction with Canon's RT system include: * Yongnuo YN-600EX-RT (speedlight master/slave) * Yongnuo YN-E3-RT/RX (transmitter/receiver) * Phottix Laso TTL transmitter/receiver The only missing piece in the system seems to be built-in radio transmitters in the camera bodies. Does Nikon have an equivalent built-in radio triggering system for its flashes? If so, is there any 3rd-party support?
2016/08/09
[ "https://photo.stackexchange.com/questions/81793", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/27440/" ]
At the time of this writing, Nikon's radio flash system is only in the preliminary stages; it's more the groundwork for a system than an actual system, and is not a practical choice for most current Nikon shooters. * The only flash in the system is the SB-5000 (released 2016). It is RF slave only. * The SB-5000 can only be radio controlled from two Nikon bodies: the D5 and the D500. * Radio control from a D5/D500 also requires a WR-R10 transmitter (firmware version 3.0 or later). * Upgrading the WR-R10 firmware to 3.0 requires sending the WR-R10 to Nikon service, and apparently most units shipped with an earlier version. * There is no 3rd party support for the system yet. Needless to say, there's been a lot of online complaining about this, given the expectations that have arisen from the Canon RT system. Nikon also has a policy about not talking about future development prior to formal announcements. So whether or not it will simply require a firmware upgrade for older camera bodies that are compatible with the WR-R10 to use the new system; or newer camera bodies/speedlights will have the WR-R10 functionality built-in, is unknown at this time.
The Nikon SB-5000 flash and the D500 and D5 cameras support radio.
81,793
In 2012, Canon introduced remote radio control into its flashes with the introduction of the 600EX-RT speedlite. Canon master/slaves flashes in this system now include: * 600EX-RT * 600EX-RT II * 430EX III-RT And there's a headless transmitter (master) unit, the ST-E3-RT. 3rd-party speedlights and transmitter/receivers that can be used in conjunction with Canon's RT system include: * Yongnuo YN-600EX-RT (speedlight master/slave) * Yongnuo YN-E3-RT/RX (transmitter/receiver) * Phottix Laso TTL transmitter/receiver The only missing piece in the system seems to be built-in radio transmitters in the camera bodies. Does Nikon have an equivalent built-in radio triggering system for its flashes? If so, is there any 3rd-party support?
2016/08/09
[ "https://photo.stackexchange.com/questions/81793", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/27440/" ]
At the time of this writing, Nikon's radio flash system is only in the preliminary stages; it's more the groundwork for a system than an actual system, and is not a practical choice for most current Nikon shooters. * The only flash in the system is the SB-5000 (released 2016). It is RF slave only. * The SB-5000 can only be radio controlled from two Nikon bodies: the D5 and the D500. * Radio control from a D5/D500 also requires a WR-R10 transmitter (firmware version 3.0 or later). * Upgrading the WR-R10 firmware to 3.0 requires sending the WR-R10 to Nikon service, and apparently most units shipped with an earlier version. * There is no 3rd party support for the system yet. Needless to say, there's been a lot of online complaining about this, given the expectations that have arisen from the Canon RT system. Nikon also has a policy about not talking about future development prior to formal announcements. So whether or not it will simply require a firmware upgrade for older camera bodies that are compatible with the WR-R10 to use the new system; or newer camera bodies/speedlights will have the WR-R10 functionality built-in, is unknown at this time.
As of 1/2018 there is still no transmitter for the SB-5000 flashes. Even with firmware updates to include other cameras like the D810 that I own a pair of, they will not pair with the WR-R10 on the D810. Nikon said it is because the body does not have built in radio, but that is the reason why one would buy a WR-R10/A10/T10 setup in the first place. The customer service told me to use my DSLR's pop-up flash, or a SU-800 CLS commander to trigger the flashes. As both are optical solutions, they are not adequate replacement for RF.
2,481,804
Let $C\_p([0,1])$ denote the set of continuous functions $[0,1]\to\mathbb R$ with the subspace topology coming from the product $\mathbb R^{[0,1]}.$ The "p" stands for pointwise. Is this space a continuous image of $\mathbb R$? --- Some observations: * $C\_p([0,1])$ is not locally compact * To be an image of $\mathbb R$ a space must be $\sigma$-compact * $C\_p([0,1])$ is not Baire * It would be equivalent to consider maps $[0,1]\to [0,1].$ (In one direction we can "clip" a function to $[0,1],$ and in the other direction every real-valued continuous function is $N$ times a $[0,1]$ valued function, and we can use interleaving to encode all functions hitting each multiple of $N$ into a single surjection from $\mathbb R.$) * There is a nice diagonalization argument showing that $C\_p(\mathbb R)$ is not a continuous image of $\mathbb R.$ See [this answer](https://math.stackexchange.com/q/74779) and use the obvious continuous $C\_p(\mathbb R)\to C\_p(\mathbb N)$ coming from restriction to $\mathbb N$.
2017/10/20
[ "https://math.stackexchange.com/questions/2481804", "https://math.stackexchange.com", "https://math.stackexchange.com/users/467147/" ]
Hint: use this$x^TAx=(x^TAx)^T=x^TA^Tx=-x^TAx$. $x^TAx=(x^TAx)^T$ since $x^TAx$ is a scalar.
a classic exercise :$A$ real $n\times n$ antisymmetric if and only if $x^TAx=0$ for all $x\in {\mathbb{R}}^n$. One sense is easy the second (the question asked) follows from $x^T(A+A^T)x=0$ for all $x\in {\mathbb{R}}^n$ which means $A+A^T=0$ because it is real symmetric.
28,381,458
What is meant by application porting. when iam reading about log4net i came across this line "**Log4Net is an open source a .NET based set of assemblies, ported from the Apache Log4j java classes, to provide a configurable logging framework.**". what is meant by ported from apache log4J. can any one explain how a software can be ported in a simple language.
2015/02/07
[ "https://Stackoverflow.com/questions/28381458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4449555/" ]
Actually USB Host actually similar with OTG,since we can check the USB Host feature programically, here are my solution,hope this help you. ``` /** * Check the device whether has USB-HOST feature. */ public static boolean hasUsbHostFeature(Context context) { return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_USB_HOST); } ```
your **answer** is here : <https://stackoverflow.com/a/34691806/3818437> add a `<uses-feature>` element to your `manifest`, indicating that you are interested in the `android.hardware.usb.host` feature. **OR** use `PackageManager, hasSystemFeature(), and FEATURE_USB_HOST`. `FEATURE_USB_HOST` is defined as the same string as you would be using in `<uses-feature>`(android.hardware.usb.host).
35,977,064
I am having a weird problem with intellij. A handful of people in here, had similar issues in the past but none of the proposed solutions worked for me. So I am trying to view the javadoc for a builtin class(in my example java.io.FileReader) but I am only getting information about the signature, not details about the method as it is usually happening. I have also tried things around quick and external documentation, I have even added an external doc url in the project settings but nothing happened. In the screenshot you can see the output I am getting. Any help appreciated. [![My output](https://i.stack.imgur.com/UdEAr.png)](https://i.stack.imgur.com/UdEAr.png)
2016/03/13
[ "https://Stackoverflow.com/questions/35977064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/163085/" ]
Looks like Eclipse uses a different approach for the documentation. Also I had a non-fully document API and thats, combined, the reason it was not working. The solution is as follows: File -> Project structure -> SDKs -> Documentation paths -> Click the add button, with the earth on it -> Add an online documentation source. If you click the other one, you need to space a folder in your filesystem. Both work. Thank you for your help.
`Ctrl + Q` This assumes you have the JDK (with documentation) downloaded and configured with IntelliJ for the relevant object/class/method. Edit: Turned out it was a problem with the Users' JDK. The JDK source files didn't contain any comments (which IntelliJ uses to show JDK Documentation). This was resolved by installing the [JDK Documentation](http://www.oracle.com/technetwork/java/javase/documentation/jdk8-doc-downloads-2133158.html) and [configuring it with IntelliJ](https://stackoverflow.com/questions/8587522/how-to-view-jdk-external-documentation-in-intellij-idea).
80,273
Let $G\_d$ be the group with the following presentation $$\langle x,y \mid x^{2^{d+1}}=1, x^4=y^2, [x,y,x]=x^{2^{d}}, [x,y,y]=1\rangle,$$ where $d>2$ is an integer. It is clear that $G\_d$ is a finite $2$-group of nilpotency class at most $3$. It is easy to see that $[x,y]^2=1$ and since the quaternion group $Q\_8$ of order $8$ is a quotient of $G\_d$, $[x,y]$ has order $2$. So the nilpotency class of $G\_d$ is $2$ or $3$. The computation with GAP shows that $G\_d$ is nilpotent of class exactly $3$, whenever $d=3,4,5,6,7,8,9$. Question: Is the nilpotency class of $G$ $3$?
2011/11/07
[ "https://mathoverflow.net/questions/80273", "https://mathoverflow.net", "https://mathoverflow.net/users/19075/" ]
The nilpotency class of $G\_d$ is indeed always 3. One way to see this is to rewrite the presentation of $G\_d$ in such a way to exhibit that it is a polycyclic group. For this purpose, let $z:=[x,y]$ and $w:=y^{2^{d-1}}=x^{2^d}$. Clearly $w$ lies in the center of $G\_d$. With a little more effort we see that $$ G\_d \cong \langle x, y, z, w\mid x^4 = y^2, y^{2^{d-1}} = w, z^2 = w^2 = 1 ; y^x = yz, z^x = zw, z^y = z, w^x=w^y=w^z=w \rangle $$ This is indeed a polycyclic presentation, with relative order $4, 2^{d-1}, 2, 2$. (Thus the group has order $4\* 2^{d-1}\* 2\* 2=2^{d+3}$). But now it is easy to read off that $[G\_d,G\_d] = \langle z, w\rangle$, and thus $[[G\_d,G\_d],G\_d]=\langle w \rangle$, which is central. Hence the nilpotency class is 3.
If the nilpotency class is $2$, then we must have $[a,b,c]=1$ for all $a,b,c\in G\_d$. But we have $[x,y,x]=x^{2^d}\neq 1$ from the presentation.
80,273
Let $G\_d$ be the group with the following presentation $$\langle x,y \mid x^{2^{d+1}}=1, x^4=y^2, [x,y,x]=x^{2^{d}}, [x,y,y]=1\rangle,$$ where $d>2$ is an integer. It is clear that $G\_d$ is a finite $2$-group of nilpotency class at most $3$. It is easy to see that $[x,y]^2=1$ and since the quaternion group $Q\_8$ of order $8$ is a quotient of $G\_d$, $[x,y]$ has order $2$. So the nilpotency class of $G\_d$ is $2$ or $3$. The computation with GAP shows that $G\_d$ is nilpotent of class exactly $3$, whenever $d=3,4,5,6,7,8,9$. Question: Is the nilpotency class of $G$ $3$?
2011/11/07
[ "https://mathoverflow.net/questions/80273", "https://mathoverflow.net", "https://mathoverflow.net/users/19075/" ]
To show $w$ is nontrivial in Max's presentation, note first that the group $H\_d$ formed by the "subpresentation" $\langle y,z,w \mid y^{2^{d-1}} = w, w^2=z^2=1, z^y=z, w^z=w \rangle$ is equal to the abelian group $\langle y \rangle \times \langle z \rangle$ of order $2^{d+1}$, and $w$ is certainly a nontrivial element of $H\_d$. Now note that the map $y \to yz$, $z \to zw$ defines an automorphism of $H\_d$ of order 4. Let $X = \langle x \rangle$ be cyclic of order $2^{d+1}$. Then we can form the semidirect product $X \ltimes H\_d$ where conjugation by $x$ induces this automorphism. So $y^x=yz$, $z^x = zw$. In this semidirect product, $x^4$ and $y^2$ are both central elements of order $2^{d-1}$. So we can factor out the cyclic subgroup $\langle x^4y^{-2} \rangle$, which intersects $H\_d$ trivially, and hence gives the group with Max's presentation in which $w$ is nontrivial.
If the nilpotency class is $2$, then we must have $[a,b,c]=1$ for all $a,b,c\in G\_d$. But we have $[x,y,x]=x^{2^d}\neq 1$ from the presentation.
52,834,531
I have set up IIS on my Windows 7 PC and can access a basic HTML Web Page like so: ``` http://MY.LOCAL.IP.ADDRESS/home.html ``` Now I have created a folder: C:\inetpub\wwwroot\videos and copied in a small mp4 video file: ``` C:\inetpub\wwwroot\videos\test.mp4 ``` I want to access this video file like so: ``` <p><a href="http://localhost/videos/test.mp4">Sample MP4 Video File 1</a></p> <p><a href="http://127.0.0.1/videos/test.mp4">Sample MP4 Video File 2</a></p> <p><a href="http://my.Ip.Add.ress/videos/test.mp4">Sample MP4 Video File 3</a></p> ``` But when I click on the links I get the following error: [![enter image description here](https://i.stack.imgur.com/B0TWi.png)](https://i.stack.imgur.com/B0TWi.png) How can I get this video to stream?
2018/10/16
[ "https://Stackoverflow.com/questions/52834531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2339664/" ]
You may use ``` grep -Po 'Speed\s*\K\d+' ``` Or, to also get the fractional part if it is necessary ``` grep -Po 'Speed\s*\K\d+(\.\d+)?' ``` See the [online demo](https://ideone.com/qZzz5A) **Details** * `Speed` - a literal substring * `\s*` - 0+ whitespaces * `\K` - a match reset operator (discarding all text matched so far from the match value) * `\d+` - 1+ digits * `(\.\d+)?` - an optional sequence of a `.` and 1+ digits
``` awk 'match($0,"Speed [0-9]+.?[0-9]*"){print substr($0,RSTART+6,RLENGTH-6)}' sed '/Speed/s/.*Speed \([^ ]*\).*/\1/' ``` and if each line is always the same way formatted, you can do: ``` awk '{print $6}' file ``` This means, that every line always has the word speed in column 5 and you want to print column 6.
52,834,531
I have set up IIS on my Windows 7 PC and can access a basic HTML Web Page like so: ``` http://MY.LOCAL.IP.ADDRESS/home.html ``` Now I have created a folder: C:\inetpub\wwwroot\videos and copied in a small mp4 video file: ``` C:\inetpub\wwwroot\videos\test.mp4 ``` I want to access this video file like so: ``` <p><a href="http://localhost/videos/test.mp4">Sample MP4 Video File 1</a></p> <p><a href="http://127.0.0.1/videos/test.mp4">Sample MP4 Video File 2</a></p> <p><a href="http://my.Ip.Add.ress/videos/test.mp4">Sample MP4 Video File 3</a></p> ``` But when I click on the links I get the following error: [![enter image description here](https://i.stack.imgur.com/B0TWi.png)](https://i.stack.imgur.com/B0TWi.png) How can I get this video to stream?
2018/10/16
[ "https://Stackoverflow.com/questions/52834531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2339664/" ]
You may use ``` grep -Po 'Speed\s*\K\d+' ``` Or, to also get the fractional part if it is necessary ``` grep -Po 'Speed\s*\K\d+(\.\d+)?' ``` See the [online demo](https://ideone.com/qZzz5A) **Details** * `Speed` - a literal substring * `\s*` - 0+ whitespaces * `\K` - a match reset operator (discarding all text matched so far from the match value) * `\d+` - 1+ digits * `(\.\d+)?` - an optional sequence of a `.` and 1+ digits
If the output it *always* like that (i.e. not extra lines in between), a simple `cut -d' ' -f6` will do the job.
52,834,531
I have set up IIS on my Windows 7 PC and can access a basic HTML Web Page like so: ``` http://MY.LOCAL.IP.ADDRESS/home.html ``` Now I have created a folder: C:\inetpub\wwwroot\videos and copied in a small mp4 video file: ``` C:\inetpub\wwwroot\videos\test.mp4 ``` I want to access this video file like so: ``` <p><a href="http://localhost/videos/test.mp4">Sample MP4 Video File 1</a></p> <p><a href="http://127.0.0.1/videos/test.mp4">Sample MP4 Video File 2</a></p> <p><a href="http://my.Ip.Add.ress/videos/test.mp4">Sample MP4 Video File 3</a></p> ``` But when I click on the links I get the following error: [![enter image description here](https://i.stack.imgur.com/B0TWi.png)](https://i.stack.imgur.com/B0TWi.png) How can I get this video to stream?
2018/10/16
[ "https://Stackoverflow.com/questions/52834531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2339664/" ]
You may use ``` grep -Po 'Speed\s*\K\d+' ``` Or, to also get the fractional part if it is necessary ``` grep -Po 'Speed\s*\K\d+(\.\d+)?' ``` See the [online demo](https://ideone.com/qZzz5A) **Details** * `Speed` - a literal substring * `\s*` - 0+ whitespaces * `\K` - a match reset operator (discarding all text matched so far from the match value) * `\d+` - 1+ digits * `(\.\d+)?` - an optional sequence of a `.` and 1+ digits
Could you please try following. Considering that your Input\_file is same as shown samples. ``` awk '{sub(/.*Speed /,"");sub(/ .*/,"")} 1' Input_file ``` In case you want to save output into Input\_file itself then try following. ``` awk '{sub(/.*Speed /,"");sub(/ .*/,"")} 1' Input_file > temp_file && mv temp_file Input_file ``` Explanation: Adding explanation too here. ``` awk ' ##awk script starts from here. { sub(/.*Speed /,"") ##Using sub for substitution operation which will substitute from starting of line to till Speed string with NULL fir current line. sub(/ .*/,"") ##Using sub for substitution of everything starting from space to till end in current line with NULL. } 1 ##Mentioning 1 will print edited/non-edited lines in Input_file. ' Input_file ##Mentioning Input_file name here. ```
52,834,531
I have set up IIS on my Windows 7 PC and can access a basic HTML Web Page like so: ``` http://MY.LOCAL.IP.ADDRESS/home.html ``` Now I have created a folder: C:\inetpub\wwwroot\videos and copied in a small mp4 video file: ``` C:\inetpub\wwwroot\videos\test.mp4 ``` I want to access this video file like so: ``` <p><a href="http://localhost/videos/test.mp4">Sample MP4 Video File 1</a></p> <p><a href="http://127.0.0.1/videos/test.mp4">Sample MP4 Video File 2</a></p> <p><a href="http://my.Ip.Add.ress/videos/test.mp4">Sample MP4 Video File 3</a></p> ``` But when I click on the links I get the following error: [![enter image description here](https://i.stack.imgur.com/B0TWi.png)](https://i.stack.imgur.com/B0TWi.png) How can I get this video to stream?
2018/10/16
[ "https://Stackoverflow.com/questions/52834531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2339664/" ]
You may use ``` grep -Po 'Speed\s*\K\d+' ``` Or, to also get the fractional part if it is necessary ``` grep -Po 'Speed\s*\K\d+(\.\d+)?' ``` See the [online demo](https://ideone.com/qZzz5A) **Details** * `Speed` - a literal substring * `\s*` - 0+ whitespaces * `\K` - a match reset operator (discarding all text matched so far from the match value) * `\d+` - 1+ digits * `(\.\d+)?` - an optional sequence of a `.` and 1+ digits
sed works too. ``` $: echo $string | sed -En '/ Speed /{ s/.* Speed ([0-9]+).*/\1/; p; }' 377 ```
52,834,531
I have set up IIS on my Windows 7 PC and can access a basic HTML Web Page like so: ``` http://MY.LOCAL.IP.ADDRESS/home.html ``` Now I have created a folder: C:\inetpub\wwwroot\videos and copied in a small mp4 video file: ``` C:\inetpub\wwwroot\videos\test.mp4 ``` I want to access this video file like so: ``` <p><a href="http://localhost/videos/test.mp4">Sample MP4 Video File 1</a></p> <p><a href="http://127.0.0.1/videos/test.mp4">Sample MP4 Video File 2</a></p> <p><a href="http://my.Ip.Add.ress/videos/test.mp4">Sample MP4 Video File 3</a></p> ``` But when I click on the links I get the following error: [![enter image description here](https://i.stack.imgur.com/B0TWi.png)](https://i.stack.imgur.com/B0TWi.png) How can I get this video to stream?
2018/10/16
[ "https://Stackoverflow.com/questions/52834531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2339664/" ]
If the output it *always* like that (i.e. not extra lines in between), a simple `cut -d' ' -f6` will do the job.
``` awk 'match($0,"Speed [0-9]+.?[0-9]*"){print substr($0,RSTART+6,RLENGTH-6)}' sed '/Speed/s/.*Speed \([^ ]*\).*/\1/' ``` and if each line is always the same way formatted, you can do: ``` awk '{print $6}' file ``` This means, that every line always has the word speed in column 5 and you want to print column 6.
52,834,531
I have set up IIS on my Windows 7 PC and can access a basic HTML Web Page like so: ``` http://MY.LOCAL.IP.ADDRESS/home.html ``` Now I have created a folder: C:\inetpub\wwwroot\videos and copied in a small mp4 video file: ``` C:\inetpub\wwwroot\videos\test.mp4 ``` I want to access this video file like so: ``` <p><a href="http://localhost/videos/test.mp4">Sample MP4 Video File 1</a></p> <p><a href="http://127.0.0.1/videos/test.mp4">Sample MP4 Video File 2</a></p> <p><a href="http://my.Ip.Add.ress/videos/test.mp4">Sample MP4 Video File 3</a></p> ``` But when I click on the links I get the following error: [![enter image description here](https://i.stack.imgur.com/B0TWi.png)](https://i.stack.imgur.com/B0TWi.png) How can I get this video to stream?
2018/10/16
[ "https://Stackoverflow.com/questions/52834531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2339664/" ]
If the output it *always* like that (i.e. not extra lines in between), a simple `cut -d' ' -f6` will do the job.
Could you please try following. Considering that your Input\_file is same as shown samples. ``` awk '{sub(/.*Speed /,"");sub(/ .*/,"")} 1' Input_file ``` In case you want to save output into Input\_file itself then try following. ``` awk '{sub(/.*Speed /,"");sub(/ .*/,"")} 1' Input_file > temp_file && mv temp_file Input_file ``` Explanation: Adding explanation too here. ``` awk ' ##awk script starts from here. { sub(/.*Speed /,"") ##Using sub for substitution operation which will substitute from starting of line to till Speed string with NULL fir current line. sub(/ .*/,"") ##Using sub for substitution of everything starting from space to till end in current line with NULL. } 1 ##Mentioning 1 will print edited/non-edited lines in Input_file. ' Input_file ##Mentioning Input_file name here. ```
52,834,531
I have set up IIS on my Windows 7 PC and can access a basic HTML Web Page like so: ``` http://MY.LOCAL.IP.ADDRESS/home.html ``` Now I have created a folder: C:\inetpub\wwwroot\videos and copied in a small mp4 video file: ``` C:\inetpub\wwwroot\videos\test.mp4 ``` I want to access this video file like so: ``` <p><a href="http://localhost/videos/test.mp4">Sample MP4 Video File 1</a></p> <p><a href="http://127.0.0.1/videos/test.mp4">Sample MP4 Video File 2</a></p> <p><a href="http://my.Ip.Add.ress/videos/test.mp4">Sample MP4 Video File 3</a></p> ``` But when I click on the links I get the following error: [![enter image description here](https://i.stack.imgur.com/B0TWi.png)](https://i.stack.imgur.com/B0TWi.png) How can I get this video to stream?
2018/10/16
[ "https://Stackoverflow.com/questions/52834531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2339664/" ]
If the output it *always* like that (i.e. not extra lines in between), a simple `cut -d' ' -f6` will do the job.
sed works too. ``` $: echo $string | sed -En '/ Speed /{ s/.* Speed ([0-9]+).*/\1/; p; }' 377 ```
19,278,333
I have created a stored procedure ``` create or replace PROCEDURE "USP_USER_ADD" ( USERNAME IN VARCHAR2 , P_PASSWORD IN VARCHAR2 , SALT IN BLOB , EMAIL IN VARCHAR2 , FIRST_NAME IN VARCHAR2 , LAST_NAME IN VARCHAR2 , ip_address IN VARCHAR2 , EMAIL_VERIFIED IN NUMBER , ACTIVE IN NUMBER , CREATEDBY IN VARCHAR2 , CREATED IN DATE , MODIFIED IN DATE , MODIFIEDBY IN VARCHAR2 , USER_GROUP_ID IN NUMBER , LAST_PASSWORD_CHANGE_DATE IN DATE , P_failed_login_attempts IN NUMBER ) AS BEGIN declare user_id_tmp number(20); INSERT INTO users( "username" , "password" , "salt" , "email" , "first_name" , "last_name" , "email_verified" , "active" , "ip_address" , "created" , "createdby" , "modified" , "modifiedby" , "user_group_id" , "last_password_change_date" , "FAILED_LOGIN_ATTEMPTS" ) VALUES ( username , p_password , salt , email , first_name , last_name , email_verified , active , ip_address , created , createdby , modified , modifiedby , user_group_id , last_password_change_date , p_failed_login_attempts ); SELECT MAX(id) INTO user_id_tmp FROM users ; INSERT INTO user_passwords ( "user_id" , "password" , "created" ) VALUES ( user_id_tmp, p_password, created ); END USP_USER_ADD; ``` It's giving me two errors > > 1: Error(26,5): PLS-00103: Encountered the symbol "INSERT" when expecting one of the following: begin function package pragma procedure subtype type use form current cursor The symbol "begin" was substituted for "INSERT" to continue. > > > 2: Error(78,19): PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: begin case declare end exception exit for goto if loop mod null pragma raise return select update while with << close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe > > > These are my tables ``` -------------------------------------------------------- -- DDL for Table USER_PASSWORDS -------------------------------------------------------- CREATE TABLE "NEWS1.0"."USER_PASSWORDS" ( "ID" NUMBER(11,0), "USER_ID" NUMBER(11,0), "PASSWORD" VARCHAR2(255 BYTE), "SALT" VARCHAR2(255 BYTE), "IP" VARCHAR2(15 BYTE), "CREATEDBY" VARCHAR2(255 BYTE), "CREATED" DATE, "MODIFIED" DATE, "MODIFIEDBY" VARCHAR2(255 BYTE) ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ; -------------------------------------------------------- -- DDL for Index USERS_PK -------------------------------------------------------- CREATE UNIQUE INDEX "NEWS1.0"."USERS_PK" ON "NEWS1.0"."USER_PASSWORDS" ("ID") PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ; -------------------------------------------------------- -- Constraints for Table USER_PASSWORDS -------------------------------------------------------- ALTER TABLE "NEWS1.0"."USER_PASSWORDS" MODIFY ("ID" NOT NULL ENABLE); ALTER TABLE "NEWS1.0"."USER_PASSWORDS" MODIFY ("USER_ID" NOT NULL ENABLE); ALTER TABLE "NEWS1.0"."USER_PASSWORDS" MODIFY ("PASSWORD" NOT NULL ENABLE); ALTER TABLE "NEWS1.0"."USER_PASSWORDS" ADD CONSTRAINT "USERS_PK" PRIMARY KEY ("ID") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ENABLE; -------------------------------------------------------- -- DDL for Trigger BI_USER_PASSWORDS_ID -------------------------------------------------------- CREATE OR REPLACE TRIGGER "NEWS1.0"."BI_USER_PASSWORDS_ID" before insert on "USER_PASSWORDS" for each row begin if inserting then if :NEW."ID" is null then select USER_PASSWORDS_SEQ.nextval into :NEW."ID" from dual; end if; end if; end; / ALTER TRIGGER "NEWS1.0"."BI_USER_PASSWORDS_ID" ENABLE; -------------------------------------------------------- -- DDL for Table USERS -------------------------------------------------------- CREATE TABLE "NEWS1.0"."USERS" ( "ID" NUMBER(*,0), "USERNAME" VARCHAR2(100 BYTE), "PASSWORD" VARCHAR2(255 BYTE), "SALT" BLOB, "EMAIL" VARCHAR2(100 BYTE), "FIRST_NAME" VARCHAR2(100 BYTE), "LAST_NAME" VARCHAR2(100 BYTE), "EMAIL_VERIFIED" NUMBER(*,0) DEFAULT 1, "ACTIVE" NUMBER(*,0) DEFAULT 1, "IP_ADDRESS" VARCHAR2(50 BYTE), "USER_GROUP_ID" NUMBER(*,0), "LAST_PASSWORD_CHANGE_DATE" DATE, "FAILED_LOGIN_ATTEMPTS" NUMBER(*,0), "CREATED" DATE, "CREATEDBY" VARCHAR2(255 BYTE), "MODIFIED" DATE, "MODIFIEDBY" VARCHAR2(255 BYTE) ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" LOB ("SALT") STORE AS ( TABLESPACE "USERS" ENABLE STORAGE IN ROW CHUNK 8192 PCTVERSION 10 NOCACHE LOGGING STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)) ; -------------------------------------------------------- -- DDL for Index USERS_UK2 -------------------------------------------------------- CREATE UNIQUE INDEX "NEWS1.0"."USERS_UK2" ON "NEWS1.0"."USERS" ("EMAIL") PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ; -------------------------------------------------------- -- DDL for Index USERS_UK1 -------------------------------------------------------- CREATE UNIQUE INDEX "NEWS1.0"."USERS_UK1" ON "NEWS1.0"."USERS" ("USERNAME") PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ; -------------------------------------------------------- -- Constraints for Table USERS -------------------------------------------------------- ALTER TABLE "NEWS1.0"."USERS" MODIFY ("ID" NOT NULL ENABLE); ALTER TABLE "NEWS1.0"."USERS" MODIFY ("USERNAME" NOT NULL ENABLE); ALTER TABLE "NEWS1.0"."USERS" MODIFY ("PASSWORD" NOT NULL ENABLE); ALTER TABLE "NEWS1.0"."USERS" ADD CONSTRAINT "USERS_UK1" UNIQUE ("USERNAME") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ENABLE; ALTER TABLE "NEWS1.0"."USERS" ADD CONSTRAINT "USERS_UK2" UNIQUE ("EMAIL") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ENABLE; ```
2013/10/09
[ "https://Stackoverflow.com/questions/19278333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2863825/" ]
The problem is in this section of code: ``` P_failed_login_attempts IN NUMBER ) AS BEGIN declare user_id_tmp number(20); INSERT INTO users( "username" , -- rest omitted ``` Remove the `declare` and move the declaration of `user_id` between the `AS` and the `BEGIN`: ``` P_failed_login_attempts IN NUMBER ) AS user_id_tmp number(20); BEGIN INSERT INTO users( "username" , -- rest omitted ``` --- In Oracle PL/SQL, a *block* has the form ``` DECLARE -- some variable declarations BEGIN -- some code EXCEPTION -- some exception-handling END; ``` The variable declarations and exception-handling sections are optional. If there are no variable declarations, you can remove the keyword `DECLARE` (it's not an error if you leave it there). However, if the block has no exception handling, the `EXCEPTION` keyword must be removed. When declaring a procedure or function, the `CREATE OR REPLACE PROCEDURE ... AS` part takes the place of a `DECLARE`. The `-- some code` section of a PL/SQL block can contain further blocks inside it. In fact, this is what the PL/SQL compiler thought you wanted when it saw your `declare` keyword. It thought you were doing something like the following: ``` CREATE OR REPLACE PROCEDURE USP_USER_ADD ( -- parameters omitted ) AS BEGIN DECLARE -- some variable declarations BEGIN -- some code END; END USP_USER_ADD; ``` However, you had an `INSERT` after the `declare`. The compiler wasn't expecting that, and that's why you got an error. You also got an error about end-of-file, and that was because the PL/SQL compiler was expecting two `END`s but got to the end of your stored procedure before it found the second one.
I think that you should remove `DECLARE`. [Oracle 11g Create Procedure Documentation](http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/create_procedure.htm)
19,278,333
I have created a stored procedure ``` create or replace PROCEDURE "USP_USER_ADD" ( USERNAME IN VARCHAR2 , P_PASSWORD IN VARCHAR2 , SALT IN BLOB , EMAIL IN VARCHAR2 , FIRST_NAME IN VARCHAR2 , LAST_NAME IN VARCHAR2 , ip_address IN VARCHAR2 , EMAIL_VERIFIED IN NUMBER , ACTIVE IN NUMBER , CREATEDBY IN VARCHAR2 , CREATED IN DATE , MODIFIED IN DATE , MODIFIEDBY IN VARCHAR2 , USER_GROUP_ID IN NUMBER , LAST_PASSWORD_CHANGE_DATE IN DATE , P_failed_login_attempts IN NUMBER ) AS BEGIN declare user_id_tmp number(20); INSERT INTO users( "username" , "password" , "salt" , "email" , "first_name" , "last_name" , "email_verified" , "active" , "ip_address" , "created" , "createdby" , "modified" , "modifiedby" , "user_group_id" , "last_password_change_date" , "FAILED_LOGIN_ATTEMPTS" ) VALUES ( username , p_password , salt , email , first_name , last_name , email_verified , active , ip_address , created , createdby , modified , modifiedby , user_group_id , last_password_change_date , p_failed_login_attempts ); SELECT MAX(id) INTO user_id_tmp FROM users ; INSERT INTO user_passwords ( "user_id" , "password" , "created" ) VALUES ( user_id_tmp, p_password, created ); END USP_USER_ADD; ``` It's giving me two errors > > 1: Error(26,5): PLS-00103: Encountered the symbol "INSERT" when expecting one of the following: begin function package pragma procedure subtype type use form current cursor The symbol "begin" was substituted for "INSERT" to continue. > > > 2: Error(78,19): PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: begin case declare end exception exit for goto if loop mod null pragma raise return select update while with << close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe > > > These are my tables ``` -------------------------------------------------------- -- DDL for Table USER_PASSWORDS -------------------------------------------------------- CREATE TABLE "NEWS1.0"."USER_PASSWORDS" ( "ID" NUMBER(11,0), "USER_ID" NUMBER(11,0), "PASSWORD" VARCHAR2(255 BYTE), "SALT" VARCHAR2(255 BYTE), "IP" VARCHAR2(15 BYTE), "CREATEDBY" VARCHAR2(255 BYTE), "CREATED" DATE, "MODIFIED" DATE, "MODIFIEDBY" VARCHAR2(255 BYTE) ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ; -------------------------------------------------------- -- DDL for Index USERS_PK -------------------------------------------------------- CREATE UNIQUE INDEX "NEWS1.0"."USERS_PK" ON "NEWS1.0"."USER_PASSWORDS" ("ID") PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ; -------------------------------------------------------- -- Constraints for Table USER_PASSWORDS -------------------------------------------------------- ALTER TABLE "NEWS1.0"."USER_PASSWORDS" MODIFY ("ID" NOT NULL ENABLE); ALTER TABLE "NEWS1.0"."USER_PASSWORDS" MODIFY ("USER_ID" NOT NULL ENABLE); ALTER TABLE "NEWS1.0"."USER_PASSWORDS" MODIFY ("PASSWORD" NOT NULL ENABLE); ALTER TABLE "NEWS1.0"."USER_PASSWORDS" ADD CONSTRAINT "USERS_PK" PRIMARY KEY ("ID") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ENABLE; -------------------------------------------------------- -- DDL for Trigger BI_USER_PASSWORDS_ID -------------------------------------------------------- CREATE OR REPLACE TRIGGER "NEWS1.0"."BI_USER_PASSWORDS_ID" before insert on "USER_PASSWORDS" for each row begin if inserting then if :NEW."ID" is null then select USER_PASSWORDS_SEQ.nextval into :NEW."ID" from dual; end if; end if; end; / ALTER TRIGGER "NEWS1.0"."BI_USER_PASSWORDS_ID" ENABLE; -------------------------------------------------------- -- DDL for Table USERS -------------------------------------------------------- CREATE TABLE "NEWS1.0"."USERS" ( "ID" NUMBER(*,0), "USERNAME" VARCHAR2(100 BYTE), "PASSWORD" VARCHAR2(255 BYTE), "SALT" BLOB, "EMAIL" VARCHAR2(100 BYTE), "FIRST_NAME" VARCHAR2(100 BYTE), "LAST_NAME" VARCHAR2(100 BYTE), "EMAIL_VERIFIED" NUMBER(*,0) DEFAULT 1, "ACTIVE" NUMBER(*,0) DEFAULT 1, "IP_ADDRESS" VARCHAR2(50 BYTE), "USER_GROUP_ID" NUMBER(*,0), "LAST_PASSWORD_CHANGE_DATE" DATE, "FAILED_LOGIN_ATTEMPTS" NUMBER(*,0), "CREATED" DATE, "CREATEDBY" VARCHAR2(255 BYTE), "MODIFIED" DATE, "MODIFIEDBY" VARCHAR2(255 BYTE) ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" LOB ("SALT") STORE AS ( TABLESPACE "USERS" ENABLE STORAGE IN ROW CHUNK 8192 PCTVERSION 10 NOCACHE LOGGING STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)) ; -------------------------------------------------------- -- DDL for Index USERS_UK2 -------------------------------------------------------- CREATE UNIQUE INDEX "NEWS1.0"."USERS_UK2" ON "NEWS1.0"."USERS" ("EMAIL") PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ; -------------------------------------------------------- -- DDL for Index USERS_UK1 -------------------------------------------------------- CREATE UNIQUE INDEX "NEWS1.0"."USERS_UK1" ON "NEWS1.0"."USERS" ("USERNAME") PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ; -------------------------------------------------------- -- Constraints for Table USERS -------------------------------------------------------- ALTER TABLE "NEWS1.0"."USERS" MODIFY ("ID" NOT NULL ENABLE); ALTER TABLE "NEWS1.0"."USERS" MODIFY ("USERNAME" NOT NULL ENABLE); ALTER TABLE "NEWS1.0"."USERS" MODIFY ("PASSWORD" NOT NULL ENABLE); ALTER TABLE "NEWS1.0"."USERS" ADD CONSTRAINT "USERS_UK1" UNIQUE ("USERNAME") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ENABLE; ALTER TABLE "NEWS1.0"."USERS" ADD CONSTRAINT "USERS_UK2" UNIQUE ("EMAIL") USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT) TABLESPACE "USERS" ENABLE; ```
2013/10/09
[ "https://Stackoverflow.com/questions/19278333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2863825/" ]
The problem is in this section of code: ``` P_failed_login_attempts IN NUMBER ) AS BEGIN declare user_id_tmp number(20); INSERT INTO users( "username" , -- rest omitted ``` Remove the `declare` and move the declaration of `user_id` between the `AS` and the `BEGIN`: ``` P_failed_login_attempts IN NUMBER ) AS user_id_tmp number(20); BEGIN INSERT INTO users( "username" , -- rest omitted ``` --- In Oracle PL/SQL, a *block* has the form ``` DECLARE -- some variable declarations BEGIN -- some code EXCEPTION -- some exception-handling END; ``` The variable declarations and exception-handling sections are optional. If there are no variable declarations, you can remove the keyword `DECLARE` (it's not an error if you leave it there). However, if the block has no exception handling, the `EXCEPTION` keyword must be removed. When declaring a procedure or function, the `CREATE OR REPLACE PROCEDURE ... AS` part takes the place of a `DECLARE`. The `-- some code` section of a PL/SQL block can contain further blocks inside it. In fact, this is what the PL/SQL compiler thought you wanted when it saw your `declare` keyword. It thought you were doing something like the following: ``` CREATE OR REPLACE PROCEDURE USP_USER_ADD ( -- parameters omitted ) AS BEGIN DECLARE -- some variable declarations BEGIN -- some code END; END USP_USER_ADD; ``` However, you had an `INSERT` after the `declare`. The compiler wasn't expecting that, and that's why you got an error. You also got an error about end-of-file, and that was because the PL/SQL compiler was expecting two `END`s but got to the end of your stored procedure before it found the second one.
Previous answers have cleared up the compile errors, so I won't address those. But you have a potential bug in place; the id inserted into "user\_password" table may not be the same as in "user" table In a multi-user environment it is possible another user could insert and commit into after you insert into set but before you do the select max. That would hopefully raise dup-val-on-index, but would be extremely difficult to find. You can remove this possibility, and have slightly less/cleaner(?) code by getting the id assigned by a trigger?) by using the return option on the insert itself: insert into user ( ... ) values (...) returning id into user\_id\_tmp ; and delete the select max(id) ... statement.
7,245,967
Help! Can't figure this out! I'm getting a Integrity error on get\_or\_create even with a defaults parameter set. Here's how the model looks stripped down. ``` class Example(models.Model):model user = models.ForeignKey(User) text = models.TextField() def __unicode__(self): return "Example" ``` I run this in Django: ``` def create_example_model(user, textJson): defaults = {text: textJson.get("text", "undefined")} model, created = models.Example.objects.get_or_create( user=user, id=textJson.get("id", None), defaults=defaults) if not created: model.text = textJson.get("text", "undefined") model.save() return model ``` I'm getting an error on the get\_or\_create line: ``` IntegrityError: (1062, "Duplicate entry '3020' for key 'PRIMARY'") ``` It's live so I can't really tell what the input is. Help? There's actually a defaults set, so it's not like, this problem where they do not have a defaults. Plus it doesn't have together-unique. [Django : get\_or\_create Raises duplicate entry with together\_unique](https://stackoverflow.com/questions/6974463/django-get-or-create-raises-duplicate-entry-with-together-unique) I'm using python 2.6, and mysql.
2011/08/30
[ "https://Stackoverflow.com/questions/7245967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/421912/" ]
You shouldn't be setting the id for objects in general, you have to be careful when doing that. Have you checked to see the value for 'id' that you are putting into the database? If that doesn't fix your issue then it may be a database issue, for PostgreSQL there is a special sequence used to increment the ID's and sometimes this does not get incremented. Something like the following: > > SELECT setval('tablename\_id\_seq', (SELECT MAX(id) + 1 FROM > tablename\_id\_seq)); > > >
One common but little documented cause for `get_or_create()` fails is **corrupted database indexes.** Django depends on the assumption that there is only one record for given identifier, and this is in turn enforced using `UNIQUE` index on this particular field in the database. But indexes are constantly being rewritten and they may get corrupted e.g. when the [database crashes unexpectedly](https://webcookies.org/articles/51/django-get_or_create-integrity-or-duplicate-entry-errors). In such case the index may no longer return information about an existing record, another record with the same field is added, and as result you'll be hitting the `IntegrityError` each time you try to get or create this particular record. The solution is, at least in PostgreSQL, to [REINDEX](https://www.postgresql.org/docs/9.3/sql-reindex.html) this particular index, but you first need to get rid of the duplicate rows programmatically.
7,245,967
Help! Can't figure this out! I'm getting a Integrity error on get\_or\_create even with a defaults parameter set. Here's how the model looks stripped down. ``` class Example(models.Model):model user = models.ForeignKey(User) text = models.TextField() def __unicode__(self): return "Example" ``` I run this in Django: ``` def create_example_model(user, textJson): defaults = {text: textJson.get("text", "undefined")} model, created = models.Example.objects.get_or_create( user=user, id=textJson.get("id", None), defaults=defaults) if not created: model.text = textJson.get("text", "undefined") model.save() return model ``` I'm getting an error on the get\_or\_create line: ``` IntegrityError: (1062, "Duplicate entry '3020' for key 'PRIMARY'") ``` It's live so I can't really tell what the input is. Help? There's actually a defaults set, so it's not like, this problem where they do not have a defaults. Plus it doesn't have together-unique. [Django : get\_or\_create Raises duplicate entry with together\_unique](https://stackoverflow.com/questions/6974463/django-get-or-create-raises-duplicate-entry-with-together-unique) I'm using python 2.6, and mysql.
2011/08/30
[ "https://Stackoverflow.com/questions/7245967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/421912/" ]
`get_or_create()` will try to create a new object if it can't find one that is an **exact** match to the arguments you pass in. So is what I'm assuming is happening is that a different user has made an object with the id of 3020. Since there is no object with the user/id combo you're requesting, it tries to make a new object with that combo, but fails because a different user has already created an item with the id of 3020. Hopefully that makes sense. See what the following returns. Might give a little insight as to what has gone on. ``` models.Example.objects.get(id=3020) ``` You might need to make 3020 a string in the lookup. I'm assuming a string is coming back from your `textJson.get()` method.
One common but little documented cause for `get_or_create()` fails is **corrupted database indexes.** Django depends on the assumption that there is only one record for given identifier, and this is in turn enforced using `UNIQUE` index on this particular field in the database. But indexes are constantly being rewritten and they may get corrupted e.g. when the [database crashes unexpectedly](https://webcookies.org/articles/51/django-get_or_create-integrity-or-duplicate-entry-errors). In such case the index may no longer return information about an existing record, another record with the same field is added, and as result you'll be hitting the `IntegrityError` each time you try to get or create this particular record. The solution is, at least in PostgreSQL, to [REINDEX](https://www.postgresql.org/docs/9.3/sql-reindex.html) this particular index, but you first need to get rid of the duplicate rows programmatically.
29,692,050
I have a table and with in tds i had a text box ``` <table class="table ratemanagement customtabl-bordered " id="rate_table"> <tbody> <tr> <th><input type="checkbox" onclick="select_all()" class="check_all"></th> <th>From Days*</th> <th>To Days*</th> <th>Rent*</th> </tr> <tr> <td> <input class="case" type="checkbox"> </td> <td class="v"> <input id="rate_fromdays" class="form-control" name="fromdays" type="text"> </td> <td> <input id="rate_todays" class="form-control" name="todays" type="text"> </td> <td> <input id="rate_rent" class="form-control" name="rent" type="text"> </td> </tr> <tr> <td> <input class="case" type="checkbox"> </td> <td class="v"> <input id="rate_fromdays" class="form-control" name="fromdays" type="text"> </td> <td> <input id="rate_todays" class="form-control" name="todays" type="text"> </td> <td> <input id="rate_rent" class="form-control" name="rent" type="text"> </td> </tr> </tbody> </table> ``` i want to read the values from text box i tried ``` var values = {}; $('.v input').each(function () { values[$(this).attr('name')] = $(this).val(); }); ``` and ``` $('input[name="fromdays"],[name="todays"],[name="rent"]').each(function () { var fromdays = $(this).val(); alert(fromdays); }); ``` I want to store the values in independent variables how do i do that ex all fromdays to firstvariable, all todays to second variable how do i do that Thanks
2015/04/17
[ "https://Stackoverflow.com/questions/29692050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4000137/" ]
``` var values = []; $('.v input').each(function () { values.push($(this).attr('name') = $(this).val()); }); ```
On button click, iterate over the inputs and push their values in to the respective array: ```js $(document).on('click', '#getVar', function() { var fromVar = []; var toVar = []; $('input[name=fromdays]').each(function() { fromVar.push($(this).val()); }); $('input[name=todays]').each(function() { toVar.push($(this).val()); }); alert('from: ' + fromVar + ' - to: ' + toVar); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table class="table ratemanagement customtabl-bordered " id="rate_table"> <tbody> <tr> <th><input type="checkbox" onclick="select_all()" class="check_all"></th> <th>From Days*</th> <th>To Days*</th> <th>Rent*</th> </tr> <tr> <td> <input class="case" type="checkbox"> </td> <td class="v"> <input id="rate_fromdays" class="form-control" name="fromdays" type="text"> </td> <td> <input id="rate_todays" class="form-control" name="todays" type="text"> </td> <td> <input id="rate_rent" class="form-control" name="rent" type="text"> </td> </tr> <tr> <td> <input class="case" type="checkbox"> </td> <td class="v"> <input id="rate_fromdays" class="form-control" name="fromdays" type="text"> </td> <td> <input id="rate_todays" class="form-control" name="todays" type="text"> </td> <td> <input id="rate_rent" class="form-control" name="rent" type="text"> </td> </tr> </tbody> </table> <button id="getVar">get variables</button> ```
29,692,050
I have a table and with in tds i had a text box ``` <table class="table ratemanagement customtabl-bordered " id="rate_table"> <tbody> <tr> <th><input type="checkbox" onclick="select_all()" class="check_all"></th> <th>From Days*</th> <th>To Days*</th> <th>Rent*</th> </tr> <tr> <td> <input class="case" type="checkbox"> </td> <td class="v"> <input id="rate_fromdays" class="form-control" name="fromdays" type="text"> </td> <td> <input id="rate_todays" class="form-control" name="todays" type="text"> </td> <td> <input id="rate_rent" class="form-control" name="rent" type="text"> </td> </tr> <tr> <td> <input class="case" type="checkbox"> </td> <td class="v"> <input id="rate_fromdays" class="form-control" name="fromdays" type="text"> </td> <td> <input id="rate_todays" class="form-control" name="todays" type="text"> </td> <td> <input id="rate_rent" class="form-control" name="rent" type="text"> </td> </tr> </tbody> </table> ``` i want to read the values from text box i tried ``` var values = {}; $('.v input').each(function () { values[$(this).attr('name')] = $(this).val(); }); ``` and ``` $('input[name="fromdays"],[name="todays"],[name="rent"]').each(function () { var fromdays = $(this).val(); alert(fromdays); }); ``` I want to store the values in independent variables how do i do that ex all fromdays to firstvariable, all todays to second variable how do i do that Thanks
2015/04/17
[ "https://Stackoverflow.com/questions/29692050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4000137/" ]
You can store the values in three different `arrays` by checking the `name` attribute of the `input` fields ``` var fromdays=new Array(); var todays=new Array(); var rent=new Array(); $('#rate_table input[type="text"]').each(function () { if($(this).attr('name')=="fromdays") fromdays.push($(this).val()) if($(this).attr('name')=="todays") todays.push($(this).val()) if($(this).attr('name')=="rent") rent.push($(this).val()) }); ``` [JsFiddle](http://tps://jsfiddle.net/dbdm87k1/2/)
On button click, iterate over the inputs and push their values in to the respective array: ```js $(document).on('click', '#getVar', function() { var fromVar = []; var toVar = []; $('input[name=fromdays]').each(function() { fromVar.push($(this).val()); }); $('input[name=todays]').each(function() { toVar.push($(this).val()); }); alert('from: ' + fromVar + ' - to: ' + toVar); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table class="table ratemanagement customtabl-bordered " id="rate_table"> <tbody> <tr> <th><input type="checkbox" onclick="select_all()" class="check_all"></th> <th>From Days*</th> <th>To Days*</th> <th>Rent*</th> </tr> <tr> <td> <input class="case" type="checkbox"> </td> <td class="v"> <input id="rate_fromdays" class="form-control" name="fromdays" type="text"> </td> <td> <input id="rate_todays" class="form-control" name="todays" type="text"> </td> <td> <input id="rate_rent" class="form-control" name="rent" type="text"> </td> </tr> <tr> <td> <input class="case" type="checkbox"> </td> <td class="v"> <input id="rate_fromdays" class="form-control" name="fromdays" type="text"> </td> <td> <input id="rate_todays" class="form-control" name="todays" type="text"> </td> <td> <input id="rate_rent" class="form-control" name="rent" type="text"> </td> </tr> </tbody> </table> <button id="getVar">get variables</button> ```
28,280,685
Introduction ------------ This is more than a fact, using ClearCase (not UCM) as main SCM for large projects maintained by few people is a pretty not efficient solution. When it's Corporate Standard, we are stuck with it and we need to find an efficient workaround. The usual workflow with ClearCase consists of a `master` branch, a `develop` branch and several new feature branches. ``` o--------o (feature) / \ ----o--o---o-----o----o (develop) / \ \ *----------o---------o (main) ``` Example ------- Actually, what I call a feature could be also a simple refactoring, such as a massive renaming inside the project. In this example, and because ClearCase is file-centric, we always need a temporary branch (no atomic checkin in non-UCM CC). Creating a new branch is painful and having the right config-spec is a struggling task. From here, I see two solutions: 1. Be corporate and start the massive checkout of all the files. Because the SCM environment does not reside on the same site as the ClearCase servers, everything gets slower. I count 2s per file and 8min for 1k files. After the first coffee break, we do the work and we check in all the files (another 8min wasted). Some tests, a new massive checkout, a bugfix, a massive checkin, the merge to the `develop` branch and eventually we delete the `feature` branch, which is no longer useful. In this solution, everything's slow, a lot of caffeine gets consumed and the workflow is pretty inefficient. I don't think this is a good solution. 2. Because we would like to keep a trace of our changes, and we do not want to waste time checkin/out all the project's files, we init a Git repository from a snapshot view. Actually, the Git repository could be located anywhere else ouside ClearCase. The changes are made locally with the help of Git and, once everthing's done, the project is pushed back on ClearCase with `clearfsimport`. After this, we still need to merge the `feature` branch. This is done in CC. The feature branch can then be deleted. This solution requires lots of manipulations. Also, `clearfsimport` can be very dangerous if we misspell the target view or if we forget to remove all the temporary files. Last but not least, the final merge has to be done on CC. Snapshot Views -------------- In my examples, I did not mentioned the Snapshot Views because they are not compatible with Git. A hijacked file identified based on its timestamp. If I manually modify a file and restore its original modification date, ClearCase won't see any changes. This could be very dangerous as the following example proves it. If you don't believe me, you can try this: ``` stat -c 'touch --no-create -d "%y" "%n"' foo > restore_timestamp echo "ClearCase will not see this" >> foo source restore_timestamp rm restore_timestamp ``` With this mechanism, no Git repository can reside inside a ClearCase Snapshot View. Separated Git repository ------------------------ I doubt we can find any workaround to the requirement for a *temporary branch* creation. The merge has to be done on ClearCase even though Git is holding everything behind. I have tried to use the **Copy/Paste** extensively to synchronize a completely separated Git repository with ClearCase. Right before the final merge, I copy/paste the current state of the `develop` branch in a new Git branch and do the merge as quickly as possible. At the end, I used `clearfsimport` to push the modifications back to the `develop` branch. This operation could be very dangerous if someone wants to access the project during the merge process. For this reason, the development branch has to be locked or reserved during the operation. Unfortunately, this additional operation is very time consuming on ClearCase. The ClearCase "git checkout -b feature" equivalent -------------------------------------------------- In Git when I want to create a new branch I simply type: ``` git checkout -b feature ``` That's all, and I can work on my new feature right away. On ClearCase, things are a bit different. First, I need to place a label where I want to create my branch. From Windows with Cygwin, I can do this: ``` LABEL=my_temporary_label VOB=vob_name cleartool mklbtype -global -nc lbtype:${LABEL}@\\${VOB} cleartool mklabel -replace ${LABEL} `cleartool find . -cview -print -nxn | awk '{printf "%s ", $0}'` cleartool find . -cview -type l -exec 'cleartool ls %CLEARCASE_XPN%' | \ perl -p -e 's/\\/\//g' | \ perl -p -e 's/\r//g' | \ perl -e 'while(<>) {s@([.]/)(.*/)(.*-->\s*)@$2@;print;}' | \ xargs -n1 cleartool mklabel ${LABEL} ``` However, we need to be careful because symbolic links are not expanded. Then, a branch has to be created: ``` mkbrtype –c "Temporary Branch" my_temporary_branch ``` To work on this branch, a view need to be created: ``` cleartool mkview -tag my_temporary_view \\shared\path\to\viewStorage\my_temporary_view.vws ``` The config-spec has to be edited: ``` element * CHECKEDOUT element .../lost+found -none element * .../develop_branch/LATEST mkbranch develop_branch element * /main/A_LABEL_WHERE_THE_BRANCH_IS_BRANCHED_ON element * /main/LATEST end mkbranch develop_branch ``` Now, the branch is created. We can work on our feature. Easy, huh? In Git, I usually create 3-5 branches a day. I don't think I can do the same with ClearCase. Am I wrong? Discussion ---------- The two proposed solutions are far from good because they all require a lot of time consuming operations on ClearCase (create a branch, set a view, checkin, checkout, do the merge, delete the branch). I am looking for a solution that does not involve complex manipulations. And I still believe Git could be a good ally, but how can ClearCase and Git work together? I think we can use some scripting. I recently found [git-cc](https://github.com/charleso/git-cc) which could be a good start. Unfortunately, this project is not mature yet. I haven't investigated this approach, but I think there is one solution where we can use a ClearCase Snapshot View with Git. The timestamp of each file has to be saved before making any changes: ``` find . -type f -exec stat -c 'touch--no-create -d "%y" "%n"' {} \; > restore ``` From there, we can work on Git and once it is time to push the changes on ClearCase or just pull the changes from from the development branch, the original timestamp can be restored on all files but the modified files by since the last synchronization: ``` source ./restore git diff --name-only SHA1 SHA2 | xargs touch ``` The Question ------------ On StackOverflow, people like precise questions, not primary opinion-based questions. Thus, after this pretty long introduction I eventually can ask my question: I have tried many different approaches to improve my workflow with ClearCase but working on large projects with a *file-centric* **SCM** is not straightforward. I believe Git could help a lot, but I need to find a workflow that allows the synchronization of a local `git` repository with ClearCase and, if possible, without requiring a temporary branch. Can that be done?
2015/02/02
[ "https://Stackoverflow.com/questions/28280685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2612235/" ]
A possible solution from [VonC](https://stackoverflow.com/users/6309/vonc) -------------------------------------------------------------------------- In [VonC](https://stackoverflow.com/users/6309/vonc)'s [answer](https://stackoverflow.com/questions/28280685/toward-an-ideal-workflow-with-clearcase-and-git/28295769#comment44918646_28281599), he suggests to not use an intermediate branch and manage everything with Git. Through an example I would like to show his method. We start with this configuration on ClearCase: ``` o------o----o (develop) / \ *----------o (main) ``` The idea is to use Git to facilitate the development of a new feature that will eventually be merged to the `develop` branch. We first copy the ClearCase project into a local folder and init a Git repository (in the case the Git repository doesn't already exist). ``` WORKSPACE=~/foo cp `cleartool ls -r | grep '@@' | sed 's/@@.*$//'` $WORKSPACE cd $WORKSPACE git init git add . git commit -m "Initial commit" git checkout -b feature ``` We spend some time developing the feature on its own local Git branch: ``` x----x--x---x----x (feature on Git) / x---------- (master on Git) / o------o----o------o----o (develop) / \ *----------o (main) ``` At the end of the day it is time to sync-down the possible changes from ClearCase: ``` git checkout master git --ls-files | xargs rm cd $CCVIEW cleartool ls -r | grep '@@' | sed 's/@@.*$//' > $WORKSPACE/ccview cd $WORKSPACE cat ccview | xargs -n1 cp {} $WORKSPACE cat ccview | xargs git add git commit -m "Imported from CC" ``` So now we have made several commit on the `feature` branch and the `master` Git branch was synchronized with ClearCase. ``` x----x--x---x----x (feature on Git) / x-----------o (master on Git) / / o------o----o------o----o (develop) / \ *----------o (main) ``` We must not to forget to lock the ClearCase View during the entire merge process. This is required to prevent other developers to see their own changes erased by `clearfsimport`. To lock a ClearCase branch it is easy: ``` cleartool lock brtype:$BR_NAME ``` Then the merge can be done on Git: ``` git checkout master git merge feature ``` The `feature` Git branch was merged with the `master`. ``` x----x--x---x----x (feature on Git) / \ x-----------o--------o (master on Git) / / o------o----o------o----o (develop) / \ *----------o (main) ``` The modifications can be pushed back to ClearCase ``` OUT="$(mktemp -d)" cp -v --parents `git ls-files | sed 's/[^ ]*\.gitignore//g'` $OUT clearfsimport -comment 'clearfsimport' -rec -unco -nset $OUT $CVIEW rm -rf $OUT ``` And the lock can be removed to re-authorize the changes on the branch ``` cleartool unlock brtype:$BR_NAME ``` . ``` x----x--x---x----x (feature on Git) / \ x-----------o--------o (master on Git) / / \ o------o----o------o----o------------o (develop) / \ *----------o (main) ``` The Git repository and the local workspace may be removed unless we need to go on. ``` o------o----o------o----o------------o (develop) / \ *----------o (main) ``` In this solution, we did not use an intermediate branch on ClearCase and all the merge process occurred on Git. The ClearCase history is preserved. The only bad point is the need to lock the development branch for the final merge. [@VonC](https://stackoverflow.com/users/6309/vonc), feel free to modify my answer if I am wrong.
> > Actually, what I call a feature could be also a simple refactoring, such as a massive renaming inside the project. In this example, and because ClearCase is file-centric, **we always need a temporary branch** (no atomic checkin in non-UCM CC). > > Creating a new branch is painful and having the right config-spec is a struggling task > > > So... don't create a temporary branch? If this is to be used in collaboration with Git, only create that feature branch in the Git repo, do the final merge in the Git Repo, and *then* clearfsimport the result in the main ClearCase view.
23,630,943
Here I am using search TextField and search button in my program ``` searchTxt = new TextField(); searchTxt.setWidth("400px"); search = new Button("Search"); search.setImmediate(true); search.addListener((Button.ClickListener) this); public void buttonClick(ClickEvent event) { final Button button = event.getButton(); if (button == search) { String searchText = (String) searchTxt.getValue(); searchText = searchText.trim(); if (!searchText.equals(GlobalConstants.EMPTY_STRING) && searchText != null) { // logic } } ``` } which logic should I use here by performance point of view?
2014/05/13
[ "https://Stackoverflow.com/questions/23630943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3632315/" ]
First and foremost, you should not so much care about performance in GUI event handling code. If you'll encounter performance problems they will most probably not emerge in user input validation code. So, when writing an application your focus should be on maintainability and readability. You'll best achieve that when you use built-in framework functionality. So, assuming that with 'check that entered text only contains alphanumeric characters' you mean 'validate that...' you can use Vaadin's validators, and more specifically the RegexpValidator. Your code would then look like ``` searchTxt = new TextField(); // match at least one or more alphanumeric characters searchTxt.addValidator(new RegexpValidator("\\w+", true, "Error msg: not valid...")); public void buttonClick(ClickEvent event) { final Button button = event.getButton(); if (button == search) { if (searchTxt.isValid()) { // logic } } } ``` With that, the logic will only be executed if the user has entered at least one alphanumeric character.
You can do it as follows: 1. Check that the length of the String is 1. 2. If so, get the character at position zero by using `charAt()` method of `String`. 3. Then use `Character.isAlphabetic()` or `Character.isDigit()` to do your validation. Another option would be to use `RegEx` which would greatly reduce your lines of code but increase your learning curve.
58,259,514
I am currently developing a CQRS application that has a login page. In the `LoginCommand`, one user is fetched from the database, and if it can login (enrypted password matches given encrypted password), a token is assigned to the user. In CQRS, the command usually receives the ID of the element the command is aimed to, in order to fetch the Domain Aggregate it identifies and execute logic on it. However, in that case what I have from the user is the email. Despite that being an unique field, I am not sure if it is wrong to use that field to fetch the aggregate, despite being an unique field. I can also think of other situations with the same problem, like trying to identify a `Post` by a given semantic URL that does not contain the ID of the post. As executing queries inside the Command is forbiden, and attaching the user ID from the login form is unlikely, what options do I have to fetch the user given that situation? Should I query the read model outside the command (e.g. the controller)?
2019/10/06
[ "https://Stackoverflow.com/questions/58259514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821280/" ]
Speaking from a domain point of view, an `ID` associated with a `User` record is simply a [surrogate key](https://en.wikipedia.org/wiki/Surrogate_key). It does not have a corresponding representation in the real world and is only meant to help you persist and retrieve data. So if `email` is the unique field for your `User` records, by all means, use it as you would use an identifier in your command. That doesn't necessarily mean that you can get rid of your `id` field. You would still want to have a surrogate key like an `id` field in your `User` record, because you may want to give your users the option to change their email address. Even with a changed email address, you need to be able to identify the user uniquely throughout the system, and that's where a surrogate key comes handy. You would also want a surrogate key for performance reasons; it is almost always better to use an `Integer` or `UUID` field instead of a `String` email address as a primary key, or in reference fields. You should also differentiate between a `Command` and its corresponding `Command Handler`. A `Command` is just a DTO that encapsulates the change that happened in the external world, or a change that needs to committed to the database. In that sense, they are immutable and should not perform queries or update themselves in any way. A `Command Handler` (which is similar to an Application Service in nature but backgrounded) consumes the data in the command. In there, you can query your repository and retrieve records. In fact, this will be a necessity to do any kind of duplicate or reference key validations.
I would strongly suggest that this isn't a 'command' but rather a read from the read model. Here's why: You are simply checking that the supplied credentials match what's in the read model. This action doesn't change the state of the domain and is not therefore consistent with the use of a command. But there are more serious potential problems here. I'm not sure if you are using event sourcing or not but if you are I would be very nervous about putting passwords into it. Even if encrypted. A data breach of an event store with current and historical passwords could be a real issue. And there's more... I would want to limit the transit of passwords over the wire as much as is possible. Adding it to a command, depending on your infrastructure, adds additional transit time compared with a traditional credential check on a membership database. I do recognise however you may want to record the fact someone has logged in or failed to login. For this consider issuing commands like 'RecordSuccessfullLoggin' or 'RecordFailedLoginAttempt' if that is something your domain needs.
58,259,514
I am currently developing a CQRS application that has a login page. In the `LoginCommand`, one user is fetched from the database, and if it can login (enrypted password matches given encrypted password), a token is assigned to the user. In CQRS, the command usually receives the ID of the element the command is aimed to, in order to fetch the Domain Aggregate it identifies and execute logic on it. However, in that case what I have from the user is the email. Despite that being an unique field, I am not sure if it is wrong to use that field to fetch the aggregate, despite being an unique field. I can also think of other situations with the same problem, like trying to identify a `Post` by a given semantic URL that does not contain the ID of the post. As executing queries inside the Command is forbiden, and attaching the user ID from the login form is unlikely, what options do I have to fetch the user given that situation? Should I query the read model outside the command (e.g. the controller)?
2019/10/06
[ "https://Stackoverflow.com/questions/58259514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821280/" ]
Speaking from a domain point of view, an `ID` associated with a `User` record is simply a [surrogate key](https://en.wikipedia.org/wiki/Surrogate_key). It does not have a corresponding representation in the real world and is only meant to help you persist and retrieve data. So if `email` is the unique field for your `User` records, by all means, use it as you would use an identifier in your command. That doesn't necessarily mean that you can get rid of your `id` field. You would still want to have a surrogate key like an `id` field in your `User` record, because you may want to give your users the option to change their email address. Even with a changed email address, you need to be able to identify the user uniquely throughout the system, and that's where a surrogate key comes handy. You would also want a surrogate key for performance reasons; it is almost always better to use an `Integer` or `UUID` field instead of a `String` email address as a primary key, or in reference fields. You should also differentiate between a `Command` and its corresponding `Command Handler`. A `Command` is just a DTO that encapsulates the change that happened in the external world, or a change that needs to committed to the database. In that sense, they are immutable and should not perform queries or update themselves in any way. A `Command Handler` (which is similar to an Application Service in nature but backgrounded) consumes the data in the command. In there, you can query your repository and retrieve records. In fact, this will be a necessity to do any kind of duplicate or reference key validations.
First of all, I assume that when you say you assign a token to the user, it means you write in the database that assignment. Otherwise your login command wouldn't be a command. That being said, I see no problem having a method in your user repository that retrieves a user knowing the email.
58,259,514
I am currently developing a CQRS application that has a login page. In the `LoginCommand`, one user is fetched from the database, and if it can login (enrypted password matches given encrypted password), a token is assigned to the user. In CQRS, the command usually receives the ID of the element the command is aimed to, in order to fetch the Domain Aggregate it identifies and execute logic on it. However, in that case what I have from the user is the email. Despite that being an unique field, I am not sure if it is wrong to use that field to fetch the aggregate, despite being an unique field. I can also think of other situations with the same problem, like trying to identify a `Post` by a given semantic URL that does not contain the ID of the post. As executing queries inside the Command is forbiden, and attaching the user ID from the login form is unlikely, what options do I have to fetch the user given that situation? Should I query the read model outside the command (e.g. the controller)?
2019/10/06
[ "https://Stackoverflow.com/questions/58259514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821280/" ]
Speaking from a domain point of view, an `ID` associated with a `User` record is simply a [surrogate key](https://en.wikipedia.org/wiki/Surrogate_key). It does not have a corresponding representation in the real world and is only meant to help you persist and retrieve data. So if `email` is the unique field for your `User` records, by all means, use it as you would use an identifier in your command. That doesn't necessarily mean that you can get rid of your `id` field. You would still want to have a surrogate key like an `id` field in your `User` record, because you may want to give your users the option to change their email address. Even with a changed email address, you need to be able to identify the user uniquely throughout the system, and that's where a surrogate key comes handy. You would also want a surrogate key for performance reasons; it is almost always better to use an `Integer` or `UUID` field instead of a `String` email address as a primary key, or in reference fields. You should also differentiate between a `Command` and its corresponding `Command Handler`. A `Command` is just a DTO that encapsulates the change that happened in the external world, or a change that needs to committed to the database. In that sense, they are immutable and should not perform queries or update themselves in any way. A `Command Handler` (which is similar to an Application Service in nature but backgrounded) consumes the data in the command. In there, you can query your repository and retrieve records. In fact, this will be a necessity to do any kind of duplicate or reference key validations.
This is a very interesting question and I have had this dilemma also in CQRS/DDD/Event Sourcing context. Here's some additional answers on the top of others already mentioned. **Option A:** If you consider that you're modifying the state of a user by setting it to logged or similar, you need an ID. 1. **Use the email as your ID**. You could treat the email as the aggregate/user ID. Although like someone has mentioned that has a restriction as the email could never be modified. You could always create a clon user with the desired email (i.e: ID) though, so that's more a technical problem, achievable if business requires so without hassle. 2. **Have a two UI step login and retrieve the ID on the first one**. Or you could use an int/guid/uuid for your user in a standard way, and query, beforehand, the read side by an email in order to retrieve this ID. **There are some login systems (Google or Yahoo) that also work in two steps**. See <https://ux.stackexchange.com/questions/91763/google-and-yahoo-require-you-to-enter-your-username-first-then-password-why-is> *Although debatable, it has some advantages like allowing different login mechanisms depending on the user's preferences, showing customize login on UI, annoying automated bots as it would reduce phishing attachs as the second screen would look "different" for different users. In addition, it allows the read side to return different things if you are accessing from a registered device (e.g: your logo, etc.) than if you are accessing from a new device.* **Option B:** The other option is not to consider this as a command, but as a query. Basically you are querying a system, by passing an email and password, to obtain a token that matches that request. And you can use that token later on for actually changing the system, for example attached to a command as part of the payload, or command metadata or http header or similar. If you want, that system in charge of issuing tokens could raise events so that your domain would be able to react to those "external" events (e.g: userLoggedIn, userLoggedOut, loginAttemptFailed) and do whatever it needs to do on that specific user's aggregate. I personally like the *Option A.2* option of having a 2 steps, so that the flow goes like this: 1. End user sends a query to read side, searching by a specific email 2. The query side returns more or less info depending on whether the device was registered. But in any case it returns an ID 3. If the email exists (or even if not, the end user does not need to know that just yet if you want to avoid sharing info on which emails exist..) the second UI step is shown, where the user enters the password and/or any additional security credential (PIN? phone number? code that was sent by email?). *Also, notice how easily a user could have multiple emails, alias, etc. with this mechanism.* 4. The end user submits a command to the write side with the login attempt, providing the credentials and using the right ID. 5. The write side (command handler/domain) verifies the credentials and does whatever it needs to do, raises event userLoggedIn, or failedLoginAttempted or anything you consider relevant for your system to capture or mutate to. As a summary, my suggestion is, if you want to treat your User as an aggregate that changes state (loggeddIn, loggedOut, locked), you can still use "standard" CQRS flow, but you need a mechanism for the front end to know the ID beforehand in order to send a command. This is not too bad, as this ID can be cached in the browser and retrieved automatically even without hitting the query side of your system, and the user does not need to care about it.
58,259,514
I am currently developing a CQRS application that has a login page. In the `LoginCommand`, one user is fetched from the database, and if it can login (enrypted password matches given encrypted password), a token is assigned to the user. In CQRS, the command usually receives the ID of the element the command is aimed to, in order to fetch the Domain Aggregate it identifies and execute logic on it. However, in that case what I have from the user is the email. Despite that being an unique field, I am not sure if it is wrong to use that field to fetch the aggregate, despite being an unique field. I can also think of other situations with the same problem, like trying to identify a `Post` by a given semantic URL that does not contain the ID of the post. As executing queries inside the Command is forbiden, and attaching the user ID from the login form is unlikely, what options do I have to fetch the user given that situation? Should I query the read model outside the command (e.g. the controller)?
2019/10/06
[ "https://Stackoverflow.com/questions/58259514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821280/" ]
I don't think that CQRS would have any bearing on your design in this particular case. Perhaps event-sourcing might though. If you have some *natural key* then you have a couple of options. For one thing it is going to have to be unique. Your `UserRepository` may have a method using the e-mail address to fetch the user in addition to the id: ``` public interface IUserRepository { User Get(Guid id); User Find(string email); } ``` I tend to to use `Find` methods when I may return `null` as a `Get` indicates that the entity should exist and will throw an exception when not found. If you only want to find by `id` then you would need to look up the `id` using the `email` from some store. Depending on your consistency requirements an eventually consistent query/read store may suffice but there is nothing preventing you from accessing a 100% consistent store that has the e-mail to id mapping.
I would strongly suggest that this isn't a 'command' but rather a read from the read model. Here's why: You are simply checking that the supplied credentials match what's in the read model. This action doesn't change the state of the domain and is not therefore consistent with the use of a command. But there are more serious potential problems here. I'm not sure if you are using event sourcing or not but if you are I would be very nervous about putting passwords into it. Even if encrypted. A data breach of an event store with current and historical passwords could be a real issue. And there's more... I would want to limit the transit of passwords over the wire as much as is possible. Adding it to a command, depending on your infrastructure, adds additional transit time compared with a traditional credential check on a membership database. I do recognise however you may want to record the fact someone has logged in or failed to login. For this consider issuing commands like 'RecordSuccessfullLoggin' or 'RecordFailedLoginAttempt' if that is something your domain needs.
58,259,514
I am currently developing a CQRS application that has a login page. In the `LoginCommand`, one user is fetched from the database, and if it can login (enrypted password matches given encrypted password), a token is assigned to the user. In CQRS, the command usually receives the ID of the element the command is aimed to, in order to fetch the Domain Aggregate it identifies and execute logic on it. However, in that case what I have from the user is the email. Despite that being an unique field, I am not sure if it is wrong to use that field to fetch the aggregate, despite being an unique field. I can also think of other situations with the same problem, like trying to identify a `Post` by a given semantic URL that does not contain the ID of the post. As executing queries inside the Command is forbiden, and attaching the user ID from the login form is unlikely, what options do I have to fetch the user given that situation? Should I query the read model outside the command (e.g. the controller)?
2019/10/06
[ "https://Stackoverflow.com/questions/58259514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821280/" ]
I don't think that CQRS would have any bearing on your design in this particular case. Perhaps event-sourcing might though. If you have some *natural key* then you have a couple of options. For one thing it is going to have to be unique. Your `UserRepository` may have a method using the e-mail address to fetch the user in addition to the id: ``` public interface IUserRepository { User Get(Guid id); User Find(string email); } ``` I tend to to use `Find` methods when I may return `null` as a `Get` indicates that the entity should exist and will throw an exception when not found. If you only want to find by `id` then you would need to look up the `id` using the `email` from some store. Depending on your consistency requirements an eventually consistent query/read store may suffice but there is nothing preventing you from accessing a 100% consistent store that has the e-mail to id mapping.
First of all, I assume that when you say you assign a token to the user, it means you write in the database that assignment. Otherwise your login command wouldn't be a command. That being said, I see no problem having a method in your user repository that retrieves a user knowing the email.
58,259,514
I am currently developing a CQRS application that has a login page. In the `LoginCommand`, one user is fetched from the database, and if it can login (enrypted password matches given encrypted password), a token is assigned to the user. In CQRS, the command usually receives the ID of the element the command is aimed to, in order to fetch the Domain Aggregate it identifies and execute logic on it. However, in that case what I have from the user is the email. Despite that being an unique field, I am not sure if it is wrong to use that field to fetch the aggregate, despite being an unique field. I can also think of other situations with the same problem, like trying to identify a `Post` by a given semantic URL that does not contain the ID of the post. As executing queries inside the Command is forbiden, and attaching the user ID from the login form is unlikely, what options do I have to fetch the user given that situation? Should I query the read model outside the command (e.g. the controller)?
2019/10/06
[ "https://Stackoverflow.com/questions/58259514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821280/" ]
I don't think that CQRS would have any bearing on your design in this particular case. Perhaps event-sourcing might though. If you have some *natural key* then you have a couple of options. For one thing it is going to have to be unique. Your `UserRepository` may have a method using the e-mail address to fetch the user in addition to the id: ``` public interface IUserRepository { User Get(Guid id); User Find(string email); } ``` I tend to to use `Find` methods when I may return `null` as a `Get` indicates that the entity should exist and will throw an exception when not found. If you only want to find by `id` then you would need to look up the `id` using the `email` from some store. Depending on your consistency requirements an eventually consistent query/read store may suffice but there is nothing preventing you from accessing a 100% consistent store that has the e-mail to id mapping.
This is a very interesting question and I have had this dilemma also in CQRS/DDD/Event Sourcing context. Here's some additional answers on the top of others already mentioned. **Option A:** If you consider that you're modifying the state of a user by setting it to logged or similar, you need an ID. 1. **Use the email as your ID**. You could treat the email as the aggregate/user ID. Although like someone has mentioned that has a restriction as the email could never be modified. You could always create a clon user with the desired email (i.e: ID) though, so that's more a technical problem, achievable if business requires so without hassle. 2. **Have a two UI step login and retrieve the ID on the first one**. Or you could use an int/guid/uuid for your user in a standard way, and query, beforehand, the read side by an email in order to retrieve this ID. **There are some login systems (Google or Yahoo) that also work in two steps**. See <https://ux.stackexchange.com/questions/91763/google-and-yahoo-require-you-to-enter-your-username-first-then-password-why-is> *Although debatable, it has some advantages like allowing different login mechanisms depending on the user's preferences, showing customize login on UI, annoying automated bots as it would reduce phishing attachs as the second screen would look "different" for different users. In addition, it allows the read side to return different things if you are accessing from a registered device (e.g: your logo, etc.) than if you are accessing from a new device.* **Option B:** The other option is not to consider this as a command, but as a query. Basically you are querying a system, by passing an email and password, to obtain a token that matches that request. And you can use that token later on for actually changing the system, for example attached to a command as part of the payload, or command metadata or http header or similar. If you want, that system in charge of issuing tokens could raise events so that your domain would be able to react to those "external" events (e.g: userLoggedIn, userLoggedOut, loginAttemptFailed) and do whatever it needs to do on that specific user's aggregate. I personally like the *Option A.2* option of having a 2 steps, so that the flow goes like this: 1. End user sends a query to read side, searching by a specific email 2. The query side returns more or less info depending on whether the device was registered. But in any case it returns an ID 3. If the email exists (or even if not, the end user does not need to know that just yet if you want to avoid sharing info on which emails exist..) the second UI step is shown, where the user enters the password and/or any additional security credential (PIN? phone number? code that was sent by email?). *Also, notice how easily a user could have multiple emails, alias, etc. with this mechanism.* 4. The end user submits a command to the write side with the login attempt, providing the credentials and using the right ID. 5. The write side (command handler/domain) verifies the credentials and does whatever it needs to do, raises event userLoggedIn, or failedLoginAttempted or anything you consider relevant for your system to capture or mutate to. As a summary, my suggestion is, if you want to treat your User as an aggregate that changes state (loggeddIn, loggedOut, locked), you can still use "standard" CQRS flow, but you need a mechanism for the front end to know the ID beforehand in order to send a command. This is not too bad, as this ID can be cached in the browser and retrieved automatically even without hitting the query side of your system, and the user does not need to care about it.
58,259,514
I am currently developing a CQRS application that has a login page. In the `LoginCommand`, one user is fetched from the database, and if it can login (enrypted password matches given encrypted password), a token is assigned to the user. In CQRS, the command usually receives the ID of the element the command is aimed to, in order to fetch the Domain Aggregate it identifies and execute logic on it. However, in that case what I have from the user is the email. Despite that being an unique field, I am not sure if it is wrong to use that field to fetch the aggregate, despite being an unique field. I can also think of other situations with the same problem, like trying to identify a `Post` by a given semantic URL that does not contain the ID of the post. As executing queries inside the Command is forbiden, and attaching the user ID from the login form is unlikely, what options do I have to fetch the user given that situation? Should I query the read model outside the command (e.g. the controller)?
2019/10/06
[ "https://Stackoverflow.com/questions/58259514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821280/" ]
I would strongly suggest that this isn't a 'command' but rather a read from the read model. Here's why: You are simply checking that the supplied credentials match what's in the read model. This action doesn't change the state of the domain and is not therefore consistent with the use of a command. But there are more serious potential problems here. I'm not sure if you are using event sourcing or not but if you are I would be very nervous about putting passwords into it. Even if encrypted. A data breach of an event store with current and historical passwords could be a real issue. And there's more... I would want to limit the transit of passwords over the wire as much as is possible. Adding it to a command, depending on your infrastructure, adds additional transit time compared with a traditional credential check on a membership database. I do recognise however you may want to record the fact someone has logged in or failed to login. For this consider issuing commands like 'RecordSuccessfullLoggin' or 'RecordFailedLoginAttempt' if that is something your domain needs.
This is a very interesting question and I have had this dilemma also in CQRS/DDD/Event Sourcing context. Here's some additional answers on the top of others already mentioned. **Option A:** If you consider that you're modifying the state of a user by setting it to logged or similar, you need an ID. 1. **Use the email as your ID**. You could treat the email as the aggregate/user ID. Although like someone has mentioned that has a restriction as the email could never be modified. You could always create a clon user with the desired email (i.e: ID) though, so that's more a technical problem, achievable if business requires so without hassle. 2. **Have a two UI step login and retrieve the ID on the first one**. Or you could use an int/guid/uuid for your user in a standard way, and query, beforehand, the read side by an email in order to retrieve this ID. **There are some login systems (Google or Yahoo) that also work in two steps**. See <https://ux.stackexchange.com/questions/91763/google-and-yahoo-require-you-to-enter-your-username-first-then-password-why-is> *Although debatable, it has some advantages like allowing different login mechanisms depending on the user's preferences, showing customize login on UI, annoying automated bots as it would reduce phishing attachs as the second screen would look "different" for different users. In addition, it allows the read side to return different things if you are accessing from a registered device (e.g: your logo, etc.) than if you are accessing from a new device.* **Option B:** The other option is not to consider this as a command, but as a query. Basically you are querying a system, by passing an email and password, to obtain a token that matches that request. And you can use that token later on for actually changing the system, for example attached to a command as part of the payload, or command metadata or http header or similar. If you want, that system in charge of issuing tokens could raise events so that your domain would be able to react to those "external" events (e.g: userLoggedIn, userLoggedOut, loginAttemptFailed) and do whatever it needs to do on that specific user's aggregate. I personally like the *Option A.2* option of having a 2 steps, so that the flow goes like this: 1. End user sends a query to read side, searching by a specific email 2. The query side returns more or less info depending on whether the device was registered. But in any case it returns an ID 3. If the email exists (or even if not, the end user does not need to know that just yet if you want to avoid sharing info on which emails exist..) the second UI step is shown, where the user enters the password and/or any additional security credential (PIN? phone number? code that was sent by email?). *Also, notice how easily a user could have multiple emails, alias, etc. with this mechanism.* 4. The end user submits a command to the write side with the login attempt, providing the credentials and using the right ID. 5. The write side (command handler/domain) verifies the credentials and does whatever it needs to do, raises event userLoggedIn, or failedLoginAttempted or anything you consider relevant for your system to capture or mutate to. As a summary, my suggestion is, if you want to treat your User as an aggregate that changes state (loggeddIn, loggedOut, locked), you can still use "standard" CQRS flow, but you need a mechanism for the front end to know the ID beforehand in order to send a command. This is not too bad, as this ID can be cached in the browser and retrieved automatically even without hitting the query side of your system, and the user does not need to care about it.
58,259,514
I am currently developing a CQRS application that has a login page. In the `LoginCommand`, one user is fetched from the database, and if it can login (enrypted password matches given encrypted password), a token is assigned to the user. In CQRS, the command usually receives the ID of the element the command is aimed to, in order to fetch the Domain Aggregate it identifies and execute logic on it. However, in that case what I have from the user is the email. Despite that being an unique field, I am not sure if it is wrong to use that field to fetch the aggregate, despite being an unique field. I can also think of other situations with the same problem, like trying to identify a `Post` by a given semantic URL that does not contain the ID of the post. As executing queries inside the Command is forbiden, and attaching the user ID from the login form is unlikely, what options do I have to fetch the user given that situation? Should I query the read model outside the command (e.g. the controller)?
2019/10/06
[ "https://Stackoverflow.com/questions/58259514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821280/" ]
First of all, I assume that when you say you assign a token to the user, it means you write in the database that assignment. Otherwise your login command wouldn't be a command. That being said, I see no problem having a method in your user repository that retrieves a user knowing the email.
This is a very interesting question and I have had this dilemma also in CQRS/DDD/Event Sourcing context. Here's some additional answers on the top of others already mentioned. **Option A:** If you consider that you're modifying the state of a user by setting it to logged or similar, you need an ID. 1. **Use the email as your ID**. You could treat the email as the aggregate/user ID. Although like someone has mentioned that has a restriction as the email could never be modified. You could always create a clon user with the desired email (i.e: ID) though, so that's more a technical problem, achievable if business requires so without hassle. 2. **Have a two UI step login and retrieve the ID on the first one**. Or you could use an int/guid/uuid for your user in a standard way, and query, beforehand, the read side by an email in order to retrieve this ID. **There are some login systems (Google or Yahoo) that also work in two steps**. See <https://ux.stackexchange.com/questions/91763/google-and-yahoo-require-you-to-enter-your-username-first-then-password-why-is> *Although debatable, it has some advantages like allowing different login mechanisms depending on the user's preferences, showing customize login on UI, annoying automated bots as it would reduce phishing attachs as the second screen would look "different" for different users. In addition, it allows the read side to return different things if you are accessing from a registered device (e.g: your logo, etc.) than if you are accessing from a new device.* **Option B:** The other option is not to consider this as a command, but as a query. Basically you are querying a system, by passing an email and password, to obtain a token that matches that request. And you can use that token later on for actually changing the system, for example attached to a command as part of the payload, or command metadata or http header or similar. If you want, that system in charge of issuing tokens could raise events so that your domain would be able to react to those "external" events (e.g: userLoggedIn, userLoggedOut, loginAttemptFailed) and do whatever it needs to do on that specific user's aggregate. I personally like the *Option A.2* option of having a 2 steps, so that the flow goes like this: 1. End user sends a query to read side, searching by a specific email 2. The query side returns more or less info depending on whether the device was registered. But in any case it returns an ID 3. If the email exists (or even if not, the end user does not need to know that just yet if you want to avoid sharing info on which emails exist..) the second UI step is shown, where the user enters the password and/or any additional security credential (PIN? phone number? code that was sent by email?). *Also, notice how easily a user could have multiple emails, alias, etc. with this mechanism.* 4. The end user submits a command to the write side with the login attempt, providing the credentials and using the right ID. 5. The write side (command handler/domain) verifies the credentials and does whatever it needs to do, raises event userLoggedIn, or failedLoginAttempted or anything you consider relevant for your system to capture or mutate to. As a summary, my suggestion is, if you want to treat your User as an aggregate that changes state (loggeddIn, loggedOut, locked), you can still use "standard" CQRS flow, but you need a mechanism for the front end to know the ID beforehand in order to send a command. This is not too bad, as this ID can be cached in the browser and retrieved automatically even without hitting the query side of your system, and the user does not need to care about it.
32,282,814
Trying to create a generic function to do custom dialog box, running into an issue with dismissing the dialog box from itself, here is my code in the activity. I am trying to finish the dialog but not the activity. I also can't reference the alertDialog to do .dismiss() from the calling class. Any ideas? Yes I can technically have a showPopupMessage for every time I want to show this popup and do the onclick inside of it easily. I am trying to make a generic app wide one where I just set the onclicklistener outside the method and pass it in. ``` case R.id.deleteText: final Context context = this; View.OnClickListener rightEvent = new View.OnClickListener() { @Override public void onClick(View v) { deleteCard(btCardToken); finish(); } }; showPopupMessage(context,"Company", "Are you sure you wish to delete this card?", "CANCEL", "YES", rightEvent); break; ``` Then my code in my generic class, ``` public void showPopupMessage(Context context, String header, String message, String leftButtonText, String rightButtonText, View.OnClickListener rightEvent) { LayoutInflater inflator = LayoutInflater.from(context); View promptsView = inflator.inflate(R.layout.edit_text_prompt, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set prompts.xml to alertdialog builder alertDialogBuilder.setView(promptsView); final StyledTextView alertHeader = (StyledTextView)promptsView.findViewById(R.id.alertHeader); final StyledTextView alertText = (StyledTextView)promptsView.findViewById(R.id.alertText); final StyledTextView rightButton = (StyledTextView)promptsView.findViewById(R.id.rightButton); final StyledTextView leftButton = (StyledTextView)promptsView.findViewById(R.id.leftButton); final EditText inputEditTextBox = (EditText)promptsView.findViewById(R.id.inputEditTextBox); alertHeader.setText(header); alertText.setText(message); inputEditTextBox.setVisibility(View.GONE); leftButton.setText(leftButtonText); rightButton.setText(rightButtonText); // set dialog message alertDialogBuilder.setCancelable(true); // create alert dialog final AlertDialog alertDialog = alertDialogBuilder.create(); leftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); rightButton.setOnClickListener(rightEvent); alertDialog.show(); } ```
2015/08/29
[ "https://Stackoverflow.com/questions/32282814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279221/" ]
You should create a dialog by extending `DialogFragment` and creating a `AlertDialog` in the `onCreateDialog()` callback method. To deliver the dialog clicks, define an interface with a method for each type of click event. Then implement that interface in the host component that will receive the action events from the dialog. Your dialog could look something like this: ``` public class MyDialog extends DialogFragment { // Use this instance of the interface to deliver action events MyDialogListener mListener; // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener @Override public void onAttach(Activity activity) { super.onAttach(activity); // Verify that the host activity implements the callback interface try { // Instantiate the MyDialogListener so we can send events to the host mListener = (MyDialogListener) activity; } catch (ClassCastException e) { // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement MyDialogListener"); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Build the dialog and set up the button click handlers AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); builder.setView(inflater.inflate(R.layout.edit_text_prompt, null)) // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout final StyledTextView alertHeader = (StyledTextView) promptsView.findViewById(R.id.alertHeader); final StyledTextView alertText = (StyledTextView) promptsView.findViewById(R.id.alertText); final StyledTextView rightButton = (StyledTextView) promptsView.findViewById(R.id.rightButton); final StyledTextView leftButton = (StyledTextView) promptsView.findViewById(R.id.leftButton); final EditText inputEditTextBox = (EditText) promptsView.findViewById(R.id.inputEditTextBox); alertHeader.setText(header); alertText.setText(message); inputEditTextBox.setVisibility(View.GONE); leftButton.setText(leftButtonText); rightButton.setText(rightButtonText); // set dialog message builder.setCancelable(true); leftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.onLeftClicked(MyDialog.this); } }); rightButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.onRightClicked(MyDialog.this); } }); return builder.create(); } /* The activity that creates an instance of this dialog fragment must * implement this interface in order to receive event callbacks. * Each method passes the DialogFragment in case the host needs to query it. */ public interface MyDialogListener { public void onLeftClicked(DialogFragment dialog); public void onRightClicked(DialogFragment dialog); } } ``` In your activity, call the dialog and respond to the button clicks like so, ``` public class MainActivity extends FragmentActivity implements MyDialog.MyDialogListener{ ... public void showMyDialog() { // Create an instance of the dialog fragment and show it DialogFragment dialog = new MyDialog(); dialog.show(getSupportFragmentManager(), "MyDialog"); } // The dialog fragment receives a reference to this Activity through the // Fragment.onAttach() callback, which it uses to call the following methods // defined by the MyDialog.MyDialogListener interface @Override public void OnLeftClicked(DialogFragment dialog) { // User touched the dialog's left button ... } @Override public void onRightClicked(DialogFragment dialog) { // User touched the dialog's right button ... } } ``` For more info you can check the official docs: <http://developer.android.com/guide/topics/ui/dialogs.html>
<http://developer.android.com/guide/topics/ui/dialogs.html> You need to rework many things, `Dialog.show()` is not meant to be called by your program manually. You should use DialogFragment, and FragmentManager to manage the dialog show, hide etc. If you do not follow the DialogFragment route, you would face lots and lots of trouble later, until you realize you HAVE to use it.
32,282,814
Trying to create a generic function to do custom dialog box, running into an issue with dismissing the dialog box from itself, here is my code in the activity. I am trying to finish the dialog but not the activity. I also can't reference the alertDialog to do .dismiss() from the calling class. Any ideas? Yes I can technically have a showPopupMessage for every time I want to show this popup and do the onclick inside of it easily. I am trying to make a generic app wide one where I just set the onclicklistener outside the method and pass it in. ``` case R.id.deleteText: final Context context = this; View.OnClickListener rightEvent = new View.OnClickListener() { @Override public void onClick(View v) { deleteCard(btCardToken); finish(); } }; showPopupMessage(context,"Company", "Are you sure you wish to delete this card?", "CANCEL", "YES", rightEvent); break; ``` Then my code in my generic class, ``` public void showPopupMessage(Context context, String header, String message, String leftButtonText, String rightButtonText, View.OnClickListener rightEvent) { LayoutInflater inflator = LayoutInflater.from(context); View promptsView = inflator.inflate(R.layout.edit_text_prompt, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set prompts.xml to alertdialog builder alertDialogBuilder.setView(promptsView); final StyledTextView alertHeader = (StyledTextView)promptsView.findViewById(R.id.alertHeader); final StyledTextView alertText = (StyledTextView)promptsView.findViewById(R.id.alertText); final StyledTextView rightButton = (StyledTextView)promptsView.findViewById(R.id.rightButton); final StyledTextView leftButton = (StyledTextView)promptsView.findViewById(R.id.leftButton); final EditText inputEditTextBox = (EditText)promptsView.findViewById(R.id.inputEditTextBox); alertHeader.setText(header); alertText.setText(message); inputEditTextBox.setVisibility(View.GONE); leftButton.setText(leftButtonText); rightButton.setText(rightButtonText); // set dialog message alertDialogBuilder.setCancelable(true); // create alert dialog final AlertDialog alertDialog = alertDialogBuilder.create(); leftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); rightButton.setOnClickListener(rightEvent); alertDialog.show(); } ```
2015/08/29
[ "https://Stackoverflow.com/questions/32282814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279221/" ]
You should create a dialog by extending `DialogFragment` and creating a `AlertDialog` in the `onCreateDialog()` callback method. To deliver the dialog clicks, define an interface with a method for each type of click event. Then implement that interface in the host component that will receive the action events from the dialog. Your dialog could look something like this: ``` public class MyDialog extends DialogFragment { // Use this instance of the interface to deliver action events MyDialogListener mListener; // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener @Override public void onAttach(Activity activity) { super.onAttach(activity); // Verify that the host activity implements the callback interface try { // Instantiate the MyDialogListener so we can send events to the host mListener = (MyDialogListener) activity; } catch (ClassCastException e) { // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement MyDialogListener"); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Build the dialog and set up the button click handlers AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); builder.setView(inflater.inflate(R.layout.edit_text_prompt, null)) // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout final StyledTextView alertHeader = (StyledTextView) promptsView.findViewById(R.id.alertHeader); final StyledTextView alertText = (StyledTextView) promptsView.findViewById(R.id.alertText); final StyledTextView rightButton = (StyledTextView) promptsView.findViewById(R.id.rightButton); final StyledTextView leftButton = (StyledTextView) promptsView.findViewById(R.id.leftButton); final EditText inputEditTextBox = (EditText) promptsView.findViewById(R.id.inputEditTextBox); alertHeader.setText(header); alertText.setText(message); inputEditTextBox.setVisibility(View.GONE); leftButton.setText(leftButtonText); rightButton.setText(rightButtonText); // set dialog message builder.setCancelable(true); leftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.onLeftClicked(MyDialog.this); } }); rightButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.onRightClicked(MyDialog.this); } }); return builder.create(); } /* The activity that creates an instance of this dialog fragment must * implement this interface in order to receive event callbacks. * Each method passes the DialogFragment in case the host needs to query it. */ public interface MyDialogListener { public void onLeftClicked(DialogFragment dialog); public void onRightClicked(DialogFragment dialog); } } ``` In your activity, call the dialog and respond to the button clicks like so, ``` public class MainActivity extends FragmentActivity implements MyDialog.MyDialogListener{ ... public void showMyDialog() { // Create an instance of the dialog fragment and show it DialogFragment dialog = new MyDialog(); dialog.show(getSupportFragmentManager(), "MyDialog"); } // The dialog fragment receives a reference to this Activity through the // Fragment.onAttach() callback, which it uses to call the following methods // defined by the MyDialog.MyDialogListener interface @Override public void OnLeftClicked(DialogFragment dialog) { // User touched the dialog's left button ... } @Override public void onRightClicked(DialogFragment dialog) { // User touched the dialog's right button ... } } ``` For more info you can check the official docs: <http://developer.android.com/guide/topics/ui/dialogs.html>
Use the AlertDialog `setPositiveButton()` method for YES and `setNegativeButton()` method for NO and handle their clicks
32,282,814
Trying to create a generic function to do custom dialog box, running into an issue with dismissing the dialog box from itself, here is my code in the activity. I am trying to finish the dialog but not the activity. I also can't reference the alertDialog to do .dismiss() from the calling class. Any ideas? Yes I can technically have a showPopupMessage for every time I want to show this popup and do the onclick inside of it easily. I am trying to make a generic app wide one where I just set the onclicklistener outside the method and pass it in. ``` case R.id.deleteText: final Context context = this; View.OnClickListener rightEvent = new View.OnClickListener() { @Override public void onClick(View v) { deleteCard(btCardToken); finish(); } }; showPopupMessage(context,"Company", "Are you sure you wish to delete this card?", "CANCEL", "YES", rightEvent); break; ``` Then my code in my generic class, ``` public void showPopupMessage(Context context, String header, String message, String leftButtonText, String rightButtonText, View.OnClickListener rightEvent) { LayoutInflater inflator = LayoutInflater.from(context); View promptsView = inflator.inflate(R.layout.edit_text_prompt, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set prompts.xml to alertdialog builder alertDialogBuilder.setView(promptsView); final StyledTextView alertHeader = (StyledTextView)promptsView.findViewById(R.id.alertHeader); final StyledTextView alertText = (StyledTextView)promptsView.findViewById(R.id.alertText); final StyledTextView rightButton = (StyledTextView)promptsView.findViewById(R.id.rightButton); final StyledTextView leftButton = (StyledTextView)promptsView.findViewById(R.id.leftButton); final EditText inputEditTextBox = (EditText)promptsView.findViewById(R.id.inputEditTextBox); alertHeader.setText(header); alertText.setText(message); inputEditTextBox.setVisibility(View.GONE); leftButton.setText(leftButtonText); rightButton.setText(rightButtonText); // set dialog message alertDialogBuilder.setCancelable(true); // create alert dialog final AlertDialog alertDialog = alertDialogBuilder.create(); leftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); rightButton.setOnClickListener(rightEvent); alertDialog.show(); } ```
2015/08/29
[ "https://Stackoverflow.com/questions/32282814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279221/" ]
You should create a dialog by extending `DialogFragment` and creating a `AlertDialog` in the `onCreateDialog()` callback method. To deliver the dialog clicks, define an interface with a method for each type of click event. Then implement that interface in the host component that will receive the action events from the dialog. Your dialog could look something like this: ``` public class MyDialog extends DialogFragment { // Use this instance of the interface to deliver action events MyDialogListener mListener; // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener @Override public void onAttach(Activity activity) { super.onAttach(activity); // Verify that the host activity implements the callback interface try { // Instantiate the MyDialogListener so we can send events to the host mListener = (MyDialogListener) activity; } catch (ClassCastException e) { // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement MyDialogListener"); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Build the dialog and set up the button click handlers AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); builder.setView(inflater.inflate(R.layout.edit_text_prompt, null)) // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout final StyledTextView alertHeader = (StyledTextView) promptsView.findViewById(R.id.alertHeader); final StyledTextView alertText = (StyledTextView) promptsView.findViewById(R.id.alertText); final StyledTextView rightButton = (StyledTextView) promptsView.findViewById(R.id.rightButton); final StyledTextView leftButton = (StyledTextView) promptsView.findViewById(R.id.leftButton); final EditText inputEditTextBox = (EditText) promptsView.findViewById(R.id.inputEditTextBox); alertHeader.setText(header); alertText.setText(message); inputEditTextBox.setVisibility(View.GONE); leftButton.setText(leftButtonText); rightButton.setText(rightButtonText); // set dialog message builder.setCancelable(true); leftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.onLeftClicked(MyDialog.this); } }); rightButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.onRightClicked(MyDialog.this); } }); return builder.create(); } /* The activity that creates an instance of this dialog fragment must * implement this interface in order to receive event callbacks. * Each method passes the DialogFragment in case the host needs to query it. */ public interface MyDialogListener { public void onLeftClicked(DialogFragment dialog); public void onRightClicked(DialogFragment dialog); } } ``` In your activity, call the dialog and respond to the button clicks like so, ``` public class MainActivity extends FragmentActivity implements MyDialog.MyDialogListener{ ... public void showMyDialog() { // Create an instance of the dialog fragment and show it DialogFragment dialog = new MyDialog(); dialog.show(getSupportFragmentManager(), "MyDialog"); } // The dialog fragment receives a reference to this Activity through the // Fragment.onAttach() callback, which it uses to call the following methods // defined by the MyDialog.MyDialogListener interface @Override public void OnLeftClicked(DialogFragment dialog) { // User touched the dialog's left button ... } @Override public void onRightClicked(DialogFragment dialog) { // User touched the dialog's right button ... } } ``` For more info you can check the official docs: <http://developer.android.com/guide/topics/ui/dialogs.html>
Is setting onClickListener after showing dialog not working? ``` alertDialog.show(); leftButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); rightButton.setOnClickListener(rightEvent); ```
58,730,908
I want to build an M by M matrix where each cell\_{ij} is a function of the Kronecker delta &\_{ij} Here is the code for doing this using a for loop: ``` # Note: X is an M by M numpy array def build_matrix(X): def kd(i, j): if i==j: return 1 else : return 0 m = np.zeros((len(X), len(X))) for row in range(len(X)): for column in range(len(X)): m[row][column] = kd(X[row], X[column]) return m ``` Is there a better - more pythonic - way of achieving this?
2019/11/06
[ "https://Stackoverflow.com/questions/58730908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12222685/" ]
I was faced with the same problem, and found the following way to clean up before schema generation: use BeanFactoryPostProcessor. BeanFactoryPostProcessor is called when all bean definitions are loaded, but no beans are instantiated yet. ``` /** * Remove auto-generated schema files before JPA generates them. * Otherwise new content will be appended to the files. */ @Configuration public class SchemaSupport { @Bean public static BeanFactoryPostProcessor schemaFilesCleanupPostProcessor() { return bf -> { try { Files.deleteIfExists(Path.of("schema-drop-auto.sql")); Files.deleteIfExists(Path.of("schema-create-auto.sql")); } catch (IOException e) { throw new IllegalStateException(e); } }; } ```
Short example using Gradle and Springboot. Assuming you have a project property defining your environment, and "dev" is the one creating DDL files for Postgres. Excerpt from application.yml: ``` spring: jpa: database-platform: org.hibernate.dialect.PostgreSQLDialect database: POSTGRESQL properties: javax.persistence.schema-generation.database.action: drop-and-create javax.persistence.schema-generation.scripts.action: drop-and-create javax.persistence.schema-generation.scripts.create-target: ./sql/create-postgres.sql javax.persistence.schema-generation.scripts.create-source: metadata javax.persistence.schema-generation.scripts.drop-target: ./sql/drop-postgres.sql javax.persistence.schema-generation.scripts.drop-source: metadata ``` Add some code in bootRun task to delete the files: ``` bootRun { def defaultProfile = 'devtest' def profile = project.hasProperty("env") ? project.getProperty("env") : defaultProfile if (profile == 'dev') {delete 'sql/create-postgres.sql'; delete 'sql/drop-postgres.sql';} ``` ...}
58,730,908
I want to build an M by M matrix where each cell\_{ij} is a function of the Kronecker delta &\_{ij} Here is the code for doing this using a for loop: ``` # Note: X is an M by M numpy array def build_matrix(X): def kd(i, j): if i==j: return 1 else : return 0 m = np.zeros((len(X), len(X))) for row in range(len(X)): for column in range(len(X)): m[row][column] = kd(X[row], X[column]) return m ``` Is there a better - more pythonic - way of achieving this?
2019/11/06
[ "https://Stackoverflow.com/questions/58730908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12222685/" ]
I was faced with the same problem, and found the following way to clean up before schema generation: use BeanFactoryPostProcessor. BeanFactoryPostProcessor is called when all bean definitions are loaded, but no beans are instantiated yet. ``` /** * Remove auto-generated schema files before JPA generates them. * Otherwise new content will be appended to the files. */ @Configuration public class SchemaSupport { @Bean public static BeanFactoryPostProcessor schemaFilesCleanupPostProcessor() { return bf -> { try { Files.deleteIfExists(Path.of("schema-drop-auto.sql")); Files.deleteIfExists(Path.of("schema-create-auto.sql")); } catch (IOException e) { throw new IllegalStateException(e); } }; } ```
I only ever use the schema file for testing and solved the problem by specifying the location of the output file as follows: `spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=target/test-classes/schema.sql` This works well for Maven but the target directory could be modified for a Gradle build.
22,589,731
i don't know what's wrong, I tried to add "create" method to my application, and what i get is : "ActiveRecord::RecordNotFound in UsersController#show" "Couldn't find User with id=create" And then code ``` # Use callbacks to share a common setup def set_user @user = User.find(params[:id]) end # Permit only specific parameters ``` here's my User controller ``` class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] def index @users = User.all end def show end def create @user = User.new(user_params) respond_to do |user| if @user.save(user_params) user.html { redirect_to users_path, :notice => "User has been created!" } else user.html { redirect_to create_user_path(@user), :notice => "Sorry, couldn't create user. Try again!" } end end end def edit end def update respond_to do |format| if @user.update(user_params) format.html { redirect_to users_path, :notice => "User has been updated!" } else format.html { redirect_to edit_user_path(@user), :notice => "Sorry, couldn't update user. Try again!" } end end end def destroy @user.destroy respond_to do |d| d.html { redirect_to users_path, :notice => "User has been successfully destroyed :C !" } end end private # Use callbacks to share a common setup def set_user @user = User.find(params[:id]) end # Permit only specific parameters def user_params params.require(:user).permit(:name, :email) end end ``` The thing is, the index page works perfectly fine, but if i try to go somewhere else, like /users/create i get that error.. I tried changing routes, rewriting the code, nothing helps.My routes are like this: ``` # Root '/' root "users#index" # Show Users get "users/:id" => "users#show" ``` Can you guys help me ? I am literally stuck, as to how fix that problem :c
2014/03/23
[ "https://Stackoverflow.com/questions/22589731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3329577/" ]
You don't go to the `create` action via a URL. It's there to create a new user coming back from the `new.html.erb` file. If you want to create a new user you could use `/users/new` and add a `new` method to your controller along the lines of: ``` def new @user = User.new end ``` You will also need to change your `routes.rb` file to add all the default actions like: ``` resources :users ``` I suggest you work through <http://guides.rubyonrails.org/getting_started.html>.
In your controller: ``` class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] def index @users = User.all end def show end def new @user = User.new end def create @user = User.new(user_params) if @user.save redirect_to users_path, :notice => "User has been created!" else render :new end end def edit end def update if @user.update(user_params) redirect_to users_path, :notice => "User has been updated!" else render :edit end end def destroy @user.destroy redirect_to users_path, :notice => "User has been successfully destroyed :C !" } end private def set_user @user = User.find(params[:id]) end def user_params params.require(:user).permit(:name, :email) end end ``` You are using all RESTful actions, so you can add to `routes.rb`: ``` resources :users ``` And remove this: ``` get "users/:id" => "users#show" ```
22,589,731
i don't know what's wrong, I tried to add "create" method to my application, and what i get is : "ActiveRecord::RecordNotFound in UsersController#show" "Couldn't find User with id=create" And then code ``` # Use callbacks to share a common setup def set_user @user = User.find(params[:id]) end # Permit only specific parameters ``` here's my User controller ``` class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] def index @users = User.all end def show end def create @user = User.new(user_params) respond_to do |user| if @user.save(user_params) user.html { redirect_to users_path, :notice => "User has been created!" } else user.html { redirect_to create_user_path(@user), :notice => "Sorry, couldn't create user. Try again!" } end end end def edit end def update respond_to do |format| if @user.update(user_params) format.html { redirect_to users_path, :notice => "User has been updated!" } else format.html { redirect_to edit_user_path(@user), :notice => "Sorry, couldn't update user. Try again!" } end end end def destroy @user.destroy respond_to do |d| d.html { redirect_to users_path, :notice => "User has been successfully destroyed :C !" } end end private # Use callbacks to share a common setup def set_user @user = User.find(params[:id]) end # Permit only specific parameters def user_params params.require(:user).permit(:name, :email) end end ``` The thing is, the index page works perfectly fine, but if i try to go somewhere else, like /users/create i get that error.. I tried changing routes, rewriting the code, nothing helps.My routes are like this: ``` # Root '/' root "users#index" # Show Users get "users/:id" => "users#show" ``` Can you guys help me ? I am literally stuck, as to how fix that problem :c
2014/03/23
[ "https://Stackoverflow.com/questions/22589731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3329577/" ]
![enter image description here](https://i.stack.imgur.com/tkiYD.png) [This](http://guides.rubyonrails.org/routing.html) should help you - you're missing `resources :users`, which creates a set of RESTful routes for your controller. This, combined with the other answers should help
In your controller: ``` class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] def index @users = User.all end def show end def new @user = User.new end def create @user = User.new(user_params) if @user.save redirect_to users_path, :notice => "User has been created!" else render :new end end def edit end def update if @user.update(user_params) redirect_to users_path, :notice => "User has been updated!" else render :edit end end def destroy @user.destroy redirect_to users_path, :notice => "User has been successfully destroyed :C !" } end private def set_user @user = User.find(params[:id]) end def user_params params.require(:user).permit(:name, :email) end end ``` You are using all RESTful actions, so you can add to `routes.rb`: ``` resources :users ``` And remove this: ``` get "users/:id" => "users#show" ```
47,082,617
I have XML generating different namespaces, so how can I avoid using name space in xsl and get below result by using one single xsl. Or can I use any wild characters like `http://namesapce//example/*/format` Input 1: ``` <dynamic> <rpc xmlns="http://namespace/example/123/format" > <route> <table> <tablename>employee</tablename> <count>20</count> </table> <table> <tablename>employee</tablename> <count> 21</count> <rt> 1</rt> <rt> 2</rt> <rt> 3</rt> <rt> 4</rt> </table> <table> <tablename>dept</tablename> <count>20</count> <rt> a</rt> <rt> b</rt> <rt> c</rt> </table> <table> <tablename>employee</tablename> <count> 21</count> <rt> 5</rt> <rt> 6</rt> <rt> 7</rt> <rt> 8</rt> </table> <table> <tablename>dept</tablename> <count>44</count> <rt> d</rt> <rt> e</rt> <rt> g</rt> </table> </route> </rpc> </dynamic> ``` Input 2: ``` <dynamic> <rpc xmlns="http://namespace/example/567/format" > <route> <table> ``` Expected output 1: ``` <?xml version="1.0" encoding="UTF-8"?> <dynamic> <rpc xmlns="http://namespace/example"> <route> <table> <tablename>employee</tablename> <count>20</count> <rt> 1</rt> <rt> 2</rt> <rt> 3</rt> <rt> 4</rt> <rt> 5</rt> <rt> 6</rt> <rt> 7</rt> <rt> 8</rt> </table> <table> <tablename>dept</tablename> <count>20</count> <rt> a</rt> <rt> b</rt> <rt> c</rt> <rt> d</rt> <rt> e</rt> <rt> g</rt> </table> </route> </rpc> </dynamic> ``` Output 2 for xml 2 also contains namespace, and this xsl should be capable of handling any type of such XML. ``` <?xml version="1.0" encoding="UTF-8"?><dynamic> <rpc xmlns="http://namespace/example/567/format"> <route> ```
2017/11/02
[ "https://Stackoverflow.com/questions/47082617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6534786/" ]
Do a 2-phase transformation. Phase 1: standardize the namespaces. Phase 2: do the real transformation work. That way you minimize the amount of code that has to deal with variant namespaces. You can normalize namespaces using code such as ``` <xsl:template match="old:*" xmlns:old="(old-namespace)" xmlns:new="(new namespace)"> <xsl:element name="new:{local-name()"> <xsl:apply-templates select="@*, node()"/> </xsl:element> </xsl:template> ```
You can't use any wildcards in the namespace URI and with XSLT 1.0 you can't use `*` for a prefix. Maybe `starts-with()` would be enough of a check? Example... **XML Input** ``` <dynamic> <rpc xmlns="http://namespace/example/123/format" > <route> <table> <tablename>employee</tablename> <count>20</count> </table> <table> <tablename>employee</tablename> <count> 21</count> <rt> 1</rt> <rt> 2</rt> <rt> 3</rt> <rt> 4</rt> </table> <table> <tablename>dept</tablename> <count>20</count> <rt> a</rt> <rt> b</rt> <rt> c</rt> </table> <table> <tablename>employee</tablename> <count> 21</count> <rt> 5</rt> <rt> 6</rt> <rt> 7</rt> <rt> 8</rt> </table> <table> <tablename>dept</tablename> <count>44</count> <rt> d</rt> <rt> e</rt> <rt> g</rt> </table> </route> </rpc> </dynamic> ``` **XSLT 1.0** ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="*[starts-with(namespace-uri(),'http://namespace/example')]"> <xsl:element name="{local-name()}" namespace="http://namespace/example"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> </xsl:stylesheet> ``` **XML Output** ``` <dynamic> <rpc xmlns="http://namespace/example"> <route> <table> <tablename>employee</tablename> <count>20</count> </table> <table> <tablename>employee</tablename> <count> 21</count> <rt> 1</rt> <rt> 2</rt> <rt> 3</rt> <rt> 4</rt> </table> <table> <tablename>dept</tablename> <count>20</count> <rt> a</rt> <rt> b</rt> <rt> c</rt> </table> <table> <tablename>employee</tablename> <count> 21</count> <rt> 5</rt> <rt> 6</rt> <rt> 7</rt> <rt> 8</rt> </table> <table> <tablename>dept</tablename> <count>44</count> <rt> d</rt> <rt> e</rt> <rt> g</rt> </table> </route> </rpc> </dynamic> ``` Like Michael Kay suggested in his answer, I'd do this transform in two phases. The first phase would be this transform to normalize the namespace. The second transform would be from [my other answer](https://stackoverflow.com/a/47040756/317052) to do the grouping. You *could* use `local-name()` to make my original transform more generic, but it gets ugly in a hurry and I wouldn't recommend it. Here's an example though so you can make your own decision. ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <xsl:key name="table-by-name" match="*[local-name()='table']" use="*[local-name()='tablename']"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="*[starts-with(namespace-uri(),'http://namespace/example')]"> <xsl:element name="{local-name()}" namespace="http://namespace/example"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> <xsl:template match="*[local-name()='route'][starts-with(namespace-uri(),'http://namespace/example')]" priority="1"> <xsl:element name="{local-name()}" namespace="http://namespace/example"> <xsl:for-each select="*[local-name()='table'][count(.|key('table-by-name',*[local-name()='tablename'])[1])=1]"> <xsl:element name="{local-name()}" namespace="http://namespace/example"> <xsl:apply-templates select="*[local-name()='tablename']| *[local-name()='count']| key('table-by-name',*[local-name()='tablename'])/*[local-name()='rt']"/> </xsl:element> </xsl:for-each> </xsl:element> </xsl:template> </xsl:stylesheet> ```
51,726,486
I've try to make my Timer but , have got one problem I couldn't understand how to reset(refresh) my timer. ``` startTimer() { Observable.timer(this.countDownDuration, 1000) .map(i => this.countDownDuration - i) .take(this.countDownDuration + 1) .subscribe(i => { this.countDown = i; console.log(this.countDown); }); } resetTimer() { must stop previous timer and start new } ``` Any suggestions
2018/08/07
[ "https://Stackoverflow.com/questions/51726486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9881672/" ]
``` const s = new BehaviorSubject(null); s.switchMap(() => Observable.timer(this.countDownDuration, 1000)) .map(...) ... .subscribe(...); resetTimer() { s.next(); } ```
I found some another way for this. And in my example I must use take. I know how to reset throw switchMap. But it's not good for me. May be it'is not good decision. ``` status; startTimer() { this.status = Observable.timer(this.countDownDuration, 1000) .map(i => this.countDownDuration - i) .take(this.countDownDuration + 1) .subscribe(i => { this.countDown = i; console.log(this.countDown); }); } resetTimer() { this.status.unsubscribe(); this.startTimer(); } ```
51,726,486
I've try to make my Timer but , have got one problem I couldn't understand how to reset(refresh) my timer. ``` startTimer() { Observable.timer(this.countDownDuration, 1000) .map(i => this.countDownDuration - i) .take(this.countDownDuration + 1) .subscribe(i => { this.countDown = i; console.log(this.countDown); }); } resetTimer() { must stop previous timer and start new } ``` Any suggestions
2018/08/07
[ "https://Stackoverflow.com/questions/51726486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9881672/" ]
``` const s = new BehaviorSubject(null); s.switchMap(() => Observable.timer(this.countDownDuration, 1000)) .map(...) ... .subscribe(...); resetTimer() { s.next(); } ```
The martin's answer (<https://stackoverflow.com/a/51726532/3024975>) is correct, but I don't like subscribing the BehaviorSubject. So this is an alternative: We need a way to sinal the Observable to restart itself. This is a good use case for `Subject` ``` const signal = new Subject(); Observable.defer(() => Observable.timer(this.countDownDuration, 1000)) .takeUntil(signal) .repeat() .map(....) .subscribe(...); resetTimer() { signal.next(); } ``` I use [takeUntil](http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-takeUntil) to stop the Observable and immediately repeat it using [repeat](http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-repeat). [defer](http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-defer) is used to create timer with new `this.countDownDuration` value (I expect it's going to change).
51,726,486
I've try to make my Timer but , have got one problem I couldn't understand how to reset(refresh) my timer. ``` startTimer() { Observable.timer(this.countDownDuration, 1000) .map(i => this.countDownDuration - i) .take(this.countDownDuration + 1) .subscribe(i => { this.countDown = i; console.log(this.countDown); }); } resetTimer() { must stop previous timer and start new } ``` Any suggestions
2018/08/07
[ "https://Stackoverflow.com/questions/51726486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9881672/" ]
``` const s = new BehaviorSubject(null); s.switchMap(() => Observable.timer(this.countDownDuration, 1000)) .map(...) ... .subscribe(...); resetTimer() { s.next(); } ```
Here's another solution: ``` recording$ = new BehaviorSubject(false); stopWatch$: Observable<number>; ngOnInit() { this.stopWatch$ = this.recording$.pipe( switchMap(r => r ? timer(0, 10) : never()), share() ); } start() { this.recording$.next(true); } stop() { this.recording$.next(false); } ```
36,175
Is there a way to use the Galaxy Tab 2 with my Galaxy S3 (SPRINT) to get an internet connection?
2012/12/26
[ "https://android.stackexchange.com/questions/36175", "https://android.stackexchange.com", "https://android.stackexchange.com/users/25584/" ]
Yes, very easily actually. **To Make your S3 emit a WiFi network** 1. Enable 'WiFi Tethering' in `System Settings->More->Tethering and Portable Hotspot->Portable WiFi Hotspot`. 2. Configure the hotspot (name, password etc), in the `Setup WiFi Hotspot` menu. **To Connect your Tablet to the WiFi network** 1. Enter the tablets WiFi settings, and turn WiFi on. 2. Select the WiFi network you configured on your S3). 3. Select connect. If you setup a password, you need to enter it. **Other Info** If you do not see the WiFi Hotspot option, then your network has disabled it. If you're rooted you could use an app such as [WiFi Tethering](https://play.google.com/store/apps/details?id=og.android.tether) - just be aware that this will produce an Ad-Hoc hotspot, and Stock Android cannot connect to these types of hostspots. There is currently no way, AFAIK, to create a standard WiFi hotspot without using the stock android tethering system.
I assume that you have `3G/LTE` connection on your `Galaxy S3` and want to use that connection on your `Galaxy tab2`, so you would have internet on it. OK! here is the solution: **On Galaxy S3:** * Enable Internet (3G/LTE mobile data) * Go to Settings -> Wireless & Networks -> Tethering & portable hotspot (the path and names may be different on your phone) * Enable **Portable Wifi hotspot** * Click on "`Configure Wifi hotspot`" and define a desired SSID and password for your network. **Now, on your Galaxy Tab 2:** * Go to settings and enable Wi-fi * In the list of available wireless networks, find your wireless network created on Galaxy S3, and tap on it to connect * Enter password of the network you created on S3 and then it should connect to your Galaxy S3 and use its internet connection. more info: <http://support.google.com/android/bin/answer.py?hl=en&answer=168932> * If your network (Sprint) has disabled Tethering on the phone, you may want to use 3rd party apps to enable tethering (Liam has pointed to one of them in his answer)
36,175
Is there a way to use the Galaxy Tab 2 with my Galaxy S3 (SPRINT) to get an internet connection?
2012/12/26
[ "https://android.stackexchange.com/questions/36175", "https://android.stackexchange.com", "https://android.stackexchange.com/users/25584/" ]
Yes, very easily actually. **To Make your S3 emit a WiFi network** 1. Enable 'WiFi Tethering' in `System Settings->More->Tethering and Portable Hotspot->Portable WiFi Hotspot`. 2. Configure the hotspot (name, password etc), in the `Setup WiFi Hotspot` menu. **To Connect your Tablet to the WiFi network** 1. Enter the tablets WiFi settings, and turn WiFi on. 2. Select the WiFi network you configured on your S3). 3. Select connect. If you setup a password, you need to enter it. **Other Info** If you do not see the WiFi Hotspot option, then your network has disabled it. If you're rooted you could use an app such as [WiFi Tethering](https://play.google.com/store/apps/details?id=og.android.tether) - just be aware that this will produce an Ad-Hoc hotspot, and Stock Android cannot connect to these types of hostspots. There is currently no way, AFAIK, to create a standard WiFi hotspot without using the stock android tethering system.
What I did is to root my Samsung S3 and install a WiFi Tether apk file so I can get free internet on my Samsung Tab 2.
36,175
Is there a way to use the Galaxy Tab 2 with my Galaxy S3 (SPRINT) to get an internet connection?
2012/12/26
[ "https://android.stackexchange.com/questions/36175", "https://android.stackexchange.com", "https://android.stackexchange.com/users/25584/" ]
Yes, very easily actually. **To Make your S3 emit a WiFi network** 1. Enable 'WiFi Tethering' in `System Settings->More->Tethering and Portable Hotspot->Portable WiFi Hotspot`. 2. Configure the hotspot (name, password etc), in the `Setup WiFi Hotspot` menu. **To Connect your Tablet to the WiFi network** 1. Enter the tablets WiFi settings, and turn WiFi on. 2. Select the WiFi network you configured on your S3). 3. Select connect. If you setup a password, you need to enter it. **Other Info** If you do not see the WiFi Hotspot option, then your network has disabled it. If you're rooted you could use an app such as [WiFi Tethering](https://play.google.com/store/apps/details?id=og.android.tether) - just be aware that this will produce an Ad-Hoc hotspot, and Stock Android cannot connect to these types of hostspots. There is currently no way, AFAIK, to create a standard WiFi hotspot without using the stock android tethering system.
Samsung galaxy tab 2 and Motorola photon you can get internet thru Bluetooth
36,175
Is there a way to use the Galaxy Tab 2 with my Galaxy S3 (SPRINT) to get an internet connection?
2012/12/26
[ "https://android.stackexchange.com/questions/36175", "https://android.stackexchange.com", "https://android.stackexchange.com/users/25584/" ]
Yes, very easily actually. **To Make your S3 emit a WiFi network** 1. Enable 'WiFi Tethering' in `System Settings->More->Tethering and Portable Hotspot->Portable WiFi Hotspot`. 2. Configure the hotspot (name, password etc), in the `Setup WiFi Hotspot` menu. **To Connect your Tablet to the WiFi network** 1. Enter the tablets WiFi settings, and turn WiFi on. 2. Select the WiFi network you configured on your S3). 3. Select connect. If you setup a password, you need to enter it. **Other Info** If you do not see the WiFi Hotspot option, then your network has disabled it. If you're rooted you could use an app such as [WiFi Tethering](https://play.google.com/store/apps/details?id=og.android.tether) - just be aware that this will produce an Ad-Hoc hotspot, and Stock Android cannot connect to these types of hostspots. There is currently no way, AFAIK, to create a standard WiFi hotspot without using the stock android tethering system.
Best way is to enable WiFi Tethering. Bluetooth also works.
36,175
Is there a way to use the Galaxy Tab 2 with my Galaxy S3 (SPRINT) to get an internet connection?
2012/12/26
[ "https://android.stackexchange.com/questions/36175", "https://android.stackexchange.com", "https://android.stackexchange.com/users/25584/" ]
I assume that you have `3G/LTE` connection on your `Galaxy S3` and want to use that connection on your `Galaxy tab2`, so you would have internet on it. OK! here is the solution: **On Galaxy S3:** * Enable Internet (3G/LTE mobile data) * Go to Settings -> Wireless & Networks -> Tethering & portable hotspot (the path and names may be different on your phone) * Enable **Portable Wifi hotspot** * Click on "`Configure Wifi hotspot`" and define a desired SSID and password for your network. **Now, on your Galaxy Tab 2:** * Go to settings and enable Wi-fi * In the list of available wireless networks, find your wireless network created on Galaxy S3, and tap on it to connect * Enter password of the network you created on S3 and then it should connect to your Galaxy S3 and use its internet connection. more info: <http://support.google.com/android/bin/answer.py?hl=en&answer=168932> * If your network (Sprint) has disabled Tethering on the phone, you may want to use 3rd party apps to enable tethering (Liam has pointed to one of them in his answer)
What I did is to root my Samsung S3 and install a WiFi Tether apk file so I can get free internet on my Samsung Tab 2.
36,175
Is there a way to use the Galaxy Tab 2 with my Galaxy S3 (SPRINT) to get an internet connection?
2012/12/26
[ "https://android.stackexchange.com/questions/36175", "https://android.stackexchange.com", "https://android.stackexchange.com/users/25584/" ]
I assume that you have `3G/LTE` connection on your `Galaxy S3` and want to use that connection on your `Galaxy tab2`, so you would have internet on it. OK! here is the solution: **On Galaxy S3:** * Enable Internet (3G/LTE mobile data) * Go to Settings -> Wireless & Networks -> Tethering & portable hotspot (the path and names may be different on your phone) * Enable **Portable Wifi hotspot** * Click on "`Configure Wifi hotspot`" and define a desired SSID and password for your network. **Now, on your Galaxy Tab 2:** * Go to settings and enable Wi-fi * In the list of available wireless networks, find your wireless network created on Galaxy S3, and tap on it to connect * Enter password of the network you created on S3 and then it should connect to your Galaxy S3 and use its internet connection. more info: <http://support.google.com/android/bin/answer.py?hl=en&answer=168932> * If your network (Sprint) has disabled Tethering on the phone, you may want to use 3rd party apps to enable tethering (Liam has pointed to one of them in his answer)
Samsung galaxy tab 2 and Motorola photon you can get internet thru Bluetooth
36,175
Is there a way to use the Galaxy Tab 2 with my Galaxy S3 (SPRINT) to get an internet connection?
2012/12/26
[ "https://android.stackexchange.com/questions/36175", "https://android.stackexchange.com", "https://android.stackexchange.com/users/25584/" ]
I assume that you have `3G/LTE` connection on your `Galaxy S3` and want to use that connection on your `Galaxy tab2`, so you would have internet on it. OK! here is the solution: **On Galaxy S3:** * Enable Internet (3G/LTE mobile data) * Go to Settings -> Wireless & Networks -> Tethering & portable hotspot (the path and names may be different on your phone) * Enable **Portable Wifi hotspot** * Click on "`Configure Wifi hotspot`" and define a desired SSID and password for your network. **Now, on your Galaxy Tab 2:** * Go to settings and enable Wi-fi * In the list of available wireless networks, find your wireless network created on Galaxy S3, and tap on it to connect * Enter password of the network you created on S3 and then it should connect to your Galaxy S3 and use its internet connection. more info: <http://support.google.com/android/bin/answer.py?hl=en&answer=168932> * If your network (Sprint) has disabled Tethering on the phone, you may want to use 3rd party apps to enable tethering (Liam has pointed to one of them in his answer)
Best way is to enable WiFi Tethering. Bluetooth also works.
108,154
How do I rename a font style in an OTF font? I have this bug here: ![alt text](https://i.stack.imgur.com/3pjmX.png) I now can't select any other style except "Regular".
2010/02/12
[ "https://superuser.com/questions/108154", "https://superuser.com", "https://superuser.com/users/28077/" ]
After some more trials I found that when the second window that opened was dragged off of my third monitor the speed test would improve dramatically. This monitor is run off a second video card in a PCI slot. Both video cards are nvidia 8400 gs. Disabling this monitor completely solves problem. I guess it is a problem with the video card or more likely the driver.
Which version of Firefox are you using? Maybe you should disable a few extensions of Firefox and check again.
50,303,246
I can't think of a straightforward title for this problem. I can explain it better with code: ```js function Bar() { this.string = "something"; this.event = function(e) { console.log("This should say something: " + this.string); } } var foo = new Bar(); window.addEventListener("mouseover", foo.event); ``` The problem is 'this.string' becomes undefined in 'this.event', because the event listener changes 'this' to refer to the event instead. I need a way to get it to print "something" instead. Any help would be highly appreciated!
2018/05/12
[ "https://Stackoverflow.com/questions/50303246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6931415/" ]
Use an arrow function instead so that the inner function does not acquire a new context for its `this`. ```js function Foo() { this.string = "something"; this.event = (e) => { console.log("This should say something: " + this.string); } } var bar = new Foo(); window.addEventListener("mouseover", bar.event); ``` Another option would be to explicitly bind the `this.event` function to the instantiated object: ```js function Foo() { this.string = "something"; this.event = function(e) { console.log("This should say something: " + this.string); }.bind(this); } var bar = new Foo(); window.addEventListener("mouseover", bar.event); ``` You could also bind it when you assign the listener: ``` window.addEventListener("mouseover", bar.event.bind(bar)); ```
[**bind**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) foo with `foo.event` ```js function Bar() { this.string = "something"; this.event = function(e) { console.log("This should say something: " + this.string); } } var foo = new Bar(); window.addEventListener("mouseover", foo.event.bind(foo)); ```
50,303,246
I can't think of a straightforward title for this problem. I can explain it better with code: ```js function Bar() { this.string = "something"; this.event = function(e) { console.log("This should say something: " + this.string); } } var foo = new Bar(); window.addEventListener("mouseover", foo.event); ``` The problem is 'this.string' becomes undefined in 'this.event', because the event listener changes 'this' to refer to the event instead. I need a way to get it to print "something" instead. Any help would be highly appreciated!
2018/05/12
[ "https://Stackoverflow.com/questions/50303246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6931415/" ]
Use an arrow function instead so that the inner function does not acquire a new context for its `this`. ```js function Foo() { this.string = "something"; this.event = (e) => { console.log("This should say something: " + this.string); } } var bar = new Foo(); window.addEventListener("mouseover", bar.event); ``` Another option would be to explicitly bind the `this.event` function to the instantiated object: ```js function Foo() { this.string = "something"; this.event = function(e) { console.log("This should say something: " + this.string); }.bind(this); } var bar = new Foo(); window.addEventListener("mouseover", bar.event); ``` You could also bind it when you assign the listener: ``` window.addEventListener("mouseover", bar.event.bind(bar)); ```
I don’t know if you deliberately want to avoid this, but you can simply pass an anonymous function as a handler for the event and invoke `foo.event()` there. You *can* use `bind()` and arrow functions as the other guys suggested, but you can simply do that as well. ```js function Bar() { this.string = "something"; this.event = function(e) { console.log("This should say something: " + this.string); } } var foo = new Bar(); window.addEventListener("mouseover", function() { foo.event(); }); ``` This works because the event handler is called with its `this` pointing to the Window object. When `foo.event` *is* the handler, its `this` is overwritten. However, if you invoke it from an anonymous function, that anonymous function "absorbs" the listener’s `this` and when you call `foo.event()`, it works alright.
50,303,246
I can't think of a straightforward title for this problem. I can explain it better with code: ```js function Bar() { this.string = "something"; this.event = function(e) { console.log("This should say something: " + this.string); } } var foo = new Bar(); window.addEventListener("mouseover", foo.event); ``` The problem is 'this.string' becomes undefined in 'this.event', because the event listener changes 'this' to refer to the event instead. I need a way to get it to print "something" instead. Any help would be highly appreciated!
2018/05/12
[ "https://Stackoverflow.com/questions/50303246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6931415/" ]
Use an arrow function instead so that the inner function does not acquire a new context for its `this`. ```js function Foo() { this.string = "something"; this.event = (e) => { console.log("This should say something: " + this.string); } } var bar = new Foo(); window.addEventListener("mouseover", bar.event); ``` Another option would be to explicitly bind the `this.event` function to the instantiated object: ```js function Foo() { this.string = "something"; this.event = function(e) { console.log("This should say something: " + this.string); }.bind(this); } var bar = new Foo(); window.addEventListener("mouseover", bar.event); ``` You could also bind it when you assign the listener: ``` window.addEventListener("mouseover", bar.event.bind(bar)); ```
In addition to the given answers, this can also be done with a simple local variable. *And as suggested, and when using Babel to compile e.g. this as an arrow function, this it what that will translate to.* ```js function Bar() { var _this = this; this.string = "something"; this.event = function(e) { console.log("This should say something: " + _this.string); } } var foo = new Bar(); window.addEventListener("mouseover", foo.event); ```
43,897,109
I have a python script that reads in a CSV file that represents teacher evaluations, I read in this script and feed the values into a 2D dictionary. The dictionary goes like this: Teacher Names (key) > List of Questions for that teacher(key) > List of answers for each question.(value) I want this in a more presentable way, so I'm thinking of creating a website for it. You upload the CSV file to the website, the script makes the 2D dict, and then creates drop down menus from the elements of the dict. So a drop down menu that shows all the teacher names, once you choose one you choose the question from another drop down menu with the list of questions, and then the answers are displayed. How feasible is this? Or should I look for another method of doing this? I'm proficient in python and a beginner in HTML/CSS (couple of sites).
2017/05/10
[ "https://Stackoverflow.com/questions/43897109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6119061/" ]
It sound like you basically want to write a web app in Python. That is, you want to write, essentially, a custom server that handles data received from clients and then sends HTML back to them. This is very possible. To do it in a "modern" way, you'll want to use a [web framework](https://wiki.python.org/moin/WebFrameworks). Another (more oldschool and slow, but probably simpler) option would be to use a regular web server like Apache or NGINX which forwards data to/from clients and your Python program as a [CGI application](https://wiki.python.org/moin/CgiScripts). Regardless of the method chosen, you'll want your Python script to: * Serve an [HTML upload form](https://www.cs.tut.fi/~jkorpela/forms/file.html) for the CSV data * Receive the CSV data that the HTML form POSTs upon submission and interpret it * Send back an HTML page containing the parsed CSV data
You can use HTML/CSS with python by building a webapp with a python backend. There are lots of framework avaiable that allow you to do that, such as [Django](https://www.djangoproject.com/), [Pyramid](https://trypyramid.com/) and Flask. I personally like to use [Flask](http://flask.pocoo.org/) for small projects, since it's faster to prototype than django and also easy to learn/work with.
8,990,711
I have need to get the word between `.` and `)` I am using this: `\..*\)` But if there is more than one `.` I am getting the first `.` to `)` instead of the last `.` to `)`. E.g: ``` abc.def.ghi.jkl.mymodname(Object sender, CompletedEventArgs e) ``` I am getting : ``` def.ghi.jkl.mymodname(Object sender, CompletedEventArgs e) ``` I want: ``` mymodname(Object sender, CompletedEventArgs e) ``` Any pointers? I'm new to regex, as you can see...
2012/01/24
[ "https://Stackoverflow.com/questions/8990711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1167499/" ]
Be explicit. If you don't want any dots between your starting dot and the closing parenthesis, you can specify this: ``` \.[^.]*\) ``` `[^.]` is a negated [character class](http://www.regular-expressions.info/charclass.html), meaning "any character except a dot". That way, only non-dots are allowed to match after the dot. And if you don't want the leading dot to be a part of the match (but do want it to be present before the start of the match), you can use a [lookbehind assertion](http://www.regular-expressions.info/lookaround.html): ``` (?<=\.)[^.]*\) ``` This works in nearly all regex engines except for JavaScript and Ruby (until version 1.8), both of which do not support lookbehind.
try `.[a-bA-B0-9,(]*)` I did not check it but I think something like that works or you can also use somthing
8,990,711
I have need to get the word between `.` and `)` I am using this: `\..*\)` But if there is more than one `.` I am getting the first `.` to `)` instead of the last `.` to `)`. E.g: ``` abc.def.ghi.jkl.mymodname(Object sender, CompletedEventArgs e) ``` I am getting : ``` def.ghi.jkl.mymodname(Object sender, CompletedEventArgs e) ``` I want: ``` mymodname(Object sender, CompletedEventArgs e) ``` Any pointers? I'm new to regex, as you can see...
2012/01/24
[ "https://Stackoverflow.com/questions/8990711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1167499/" ]
Be explicit. If you don't want any dots between your starting dot and the closing parenthesis, you can specify this: ``` \.[^.]*\) ``` `[^.]` is a negated [character class](http://www.regular-expressions.info/charclass.html), meaning "any character except a dot". That way, only non-dots are allowed to match after the dot. And if you don't want the leading dot to be a part of the match (but do want it to be present before the start of the match), you can use a [lookbehind assertion](http://www.regular-expressions.info/lookaround.html): ``` (?<=\.)[^.]*\) ``` This works in nearly all regex engines except for JavaScript and Ruby (until version 1.8), both of which do not support lookbehind.
in PHP ``` $a='abc.def.ghi.jkl.mymodname(Object sender, CompletedEventArgs e)'; $p='/.*\.(.*?\))/'; preg_match($p,$a,$m); ``` now look at `$m[1]` Other languages analogous