source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0026061911.txt" ]
Q: Why Sliding Menu Can't Close in Android Please I have a problem, in my code like its nothing wrong, why when I select content on Sliding Menu, Sliding menus are not automatically covered? What's wrong with my code? I do not use a fragment only uses a switch to display the menu MainActivity.java public class MainActivity extends FragmentActivity { private static final String TAG = MainActivity.class.getSimpleName(); private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; private String[] mDrawerItems; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTitle = mDrawerTitle = getTitle(); mDrawerItems = getResources().getStringArray(R.array.list); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); // set a custom shadow that overlays the main content when the drawer oepns mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // Add items to the ListView mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mDrawerItems)); // Set the OnItemClickListener so something happens when a // user clicks on an item. mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); // Enable ActionBar app icon to behave as action to toggle nav drawer getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); mDrawerToggle = new ActionBarDrawerToggle( this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close ) { public void onDrawerClosed(View view) { getActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu } public void onDrawerOpened(View drawerView) { getActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu } }; mDrawerLayout.setDrawerListener(mDrawerToggle); // Set the default content area to item 0 // when the app opens for the first time if(savedInstanceState == null) { navigateTo(0); } } /* * If you do not have any menus, you still need this function * in order to open or close the NavigationDrawer when the user * clicking the ActionBar app icon. */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.about: Intent i = new Intent(MainActivity.this, tentang.class); startActivity(i); } if(mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } /* * When using the ActionBarDrawerToggle, you must call it during onPostCreate() * and onConfigurationChanged() */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } private class DrawerItemClickListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.v(TAG, "ponies"); navigateTo(position); } } private void navigateTo(int position) { Log.v(TAG, "List View Item: " + position); switch(position) { case 0: getSupportFragmentManager() .beginTransaction() .replace(R.id.content_frame, sejarah.newInstance(), sejarah.sejarah).commit(); break; case 1: getSupportFragmentManager() .beginTransaction() .replace(R.id.content_frame, pakaian.newInstance(), pakaian.pakaian).commit(); break; case 2: getSupportFragmentManager() .beginTransaction() .replace(R.id.content_frame, rumah.newInstance(), rumah.rumah).commit(); break; case 3: getSupportFragmentManager() .beginTransaction() .replace(R.id.content_frame, senjata.newInstance(), senjata.senjata).commit(); break; case 4: Intent i = new Intent(MainActivity.this, lagu.class); startActivity(i); break; case 5: getSupportFragmentManager() .beginTransaction() .replace(R.id.content_frame, musik.newInstance(), musik.musik).commit(); break; case 6: getSupportFragmentManager() .beginTransaction() .replace(R.id.content_frame, kesenian.newInstance(), kesenian.kesenian).commit(); break; } } @Override public void setTitle(CharSequence title) { mTitle = title; getActionBar().setTitle(mTitle); } } A: you miss the the part drawer.closeDrawer(mDrawerList) or mDrawerLayout.closeDrawer(mDrawerList)
[ "ru.stackoverflow", "0000351844.txt" ]
Q: Ajax подгрузка сообщений Вообще написал я такой вот простой код: $(document).ready(function(){ $("#imgLoad").hide(); var inputMessage = $("#message"); var messageList = $(".dialogs"); var num = 1; function updateShoutbox(){ function reload(){ $("#load div").click(function(){ $("#imgLoad").show(); $.ajax({ type: "POST", url: "/app/ajax/update.php", data: { id: <?php echo $dg['id'] ?>, coll: num }, complete: function(data){ if(data == 0){ alert("Больше нет записей"); $("#imgLoad").hide(); } else { $(messageList.html(data.responseText)).append(data); num = num + 5; $("#imgLoad").hide(); } } }); }); } setInterval(reload, 3000); } function checkForm(){ if( inputMessage.attr("value")) return true; else return false; } updateShoutbox(); $("#form").submit(function(){ if(checkForm()){ var message = inputMessage.attr("value"); $("#message").val(""); $("#send").attr({ disabled:true, value:"Отправляю..." }); $("#send").blur(); $.ajax({ type: "POST", url: "/app/ajax/send.php", data: { userid: <?php echo $users['id'] ?>, dgid: <?php echo $dg['id'] ?>, message: message }, complete: function(data){ $("#send").attr({ disabled:false, value:"Отправить" }); } }); } else alert("Пожалуйста, напишите сообщение"); return false; }); }); Тут возникло пару проблем, при переходе в диалог сообщения не отображаются, пока не нажата кнопка, второй момент как сделать новые сообщения внизу. третий момент при нажатии на кнопку не появляются старые сообщения сверху. Где косяки, и как исправить? A: Идея проста. На document вешается событие scroll, в котором проверяется, а не находимся ли мы на самом верху страницы (if($(this).scrollTop() < 20). Если это так, шлем AJAX с запросом ранних сообщений
[ "english.stackexchange", "0000309535.txt" ]
Q: Is there a word to describe things that do not follow a rule Is there a word (preferably an adjective) to describe things that do not follow a rule? For example if the rule is: no object heavier than 200lb is allowed inside a building. How would I reference all the objects that aren't compliant to that rule in a sentence like the one below. These are all the _____ objects A: I'd say the hyphenated compound word: non-conforming is the best choice for the example... These are all the non-conforming objects.
[ "meta.stackexchange", "0000338135.txt" ]
Q: What to do concretely about the new "Every question asker gets more reputation retroactively, no questions asked" (pun not intended) Following yet another blog post that will undoubtedly raise the distance between SE and their core user community, I am wondering whether anyone has any good idea on how to counteract the new top-down directive, or at the very least limit the damage. A few ideas out of the top of my head (mind you, most are bad): Comment on the blog post itself? Note that any criticism will likely be censored regardless of the tone. Focus efforts on downvoting old mastodontic bad questions that have been upvoted massively, mostly because of the great answers? Note that we don't really want to delete those (Makoto's answer to my old question on the matter comes to mind and I still agree). What would be the consequences of focusing moderation on questions whose users do not deserve any reputation boost for some garbage they dumped back in the day, when the rules weren't as clear? Stop upvoting questions altogethers in protest? That sounds silly even as I type it. Bonus question What will be the risks of massive fraud now that, not only substantial reputation is up for grabs, but also a lot of moderators are gone due to the other recent debacles? A: Nothing. Keep voting on posts, not people. Keep voting up good questions, keep voting down bad questions. In the meantime, how about we wait and see if there's even any damage?
[ "stackoverflow", "0048652637.txt" ]
Q: Array of undefined: reacts I'm just a beginner in react when I try to run my code I get this error, please tell me how and where to fix the error. any help would be greatly appreciated. constructor() { super(); this.state = { array: [''], url:"", }; } search() { var path = this.refs.searchbar.value this.setState({url: path}) var newArray = this.state.array; newArray.push(path); this.setState(array:newArray); newArray.map((i)=>{ console.log(i); }); } Error Failed to compile. ./src/searchfield.js Line 24: 'array' is not defined no-undef A: There are a few issues with your code that I would like to point out: Always pass the constructor argument to the super constructor. Since you're referencing the same array in newArray, you are actually mutating this.state.array when you push the url to it. This should be avoided; copy the array first before pushing the value and updating the state. There is a syntax error when you set the new array state (this is causing your error). These things are fixed below: constructor(props) { super(props); this.state = { array: [''], url: "" }; } search() { var path = this.refs.searchbar.value this.setState({url: path}) var newArray = this.state.array.splice(); newArray.push(path); this.setState({array: newArray}); newArray.map((i)=>{ console.log(i); }); }
[ "pt.stackoverflow", "0000171387.txt" ]
Q: Javascript prototype: possível mudar valor do objeto de referência? EDIT: Normalmente é no final, mas a pergunta foi mal formulada e decidi trocar por esse exemplo que é bem melhor. Segue o exemplo de uma função que não faz nada como método de Array: Array.prototype.nada = function () { var In = this; var Out = new Array(); for (var i=0; In.length>0; i++) { Out.push(In.pop()); } In = Out; console.log("Resultado interno: "); console.log(Out); } Para testar... function testeNada() { var Nada = ["Eu","Você","Nós"]; Nada.nada(); console.log("Resultado de Nada: "); console.log(Nada); } No Safari, o resultado interno de Out é a mesma Array do início (Nada) e o resultado do teste de Nada é uma Array vazia! No caso das prototypes métodos pré-existentes, funciona assim: var UmaArray = new Array(); UmaArray.push("umValor"); // UmaArray já é ["umValor"] Pela lógica, eu faria assim: Array.prototype.empurre = function(valor){ Arr = this; Arr.push(valor); this = Arr; // Aqui dá erro ReferenceError: Left side of assignment is not a reference } var UmaArray = new Array(); UmaArray.empurre("umValor"); // Sonho de ver UmaArray ser ["umValor"] Ou seja, não é possível modificar a si mesmo. Conforme já mencionado abaixo nos comentários, tirando this = Arr o método funciona. Então refaço a pergunta: existe alguma forma de realmente mudar o objeto de referência o apenas aplicando métodos nele mesmo? A: Você tem duas maneiras de fazer isso: Se você usar o this diretamente vai estar alterando o obj de ref. Array.prototype.empurre = function(valor){ this.push(valor); }; var UmaArray = new Array(); UmaArray.empurre("umValor"); A segunda maneira é parecida com a implementação do rotate Array.prototype.empurre = function(valor){ var push = Array.prototype.push; push.apply(this, [valor]); }; var UmaArray = new Array(); UmaArray.empurre("umValor");
[ "stackoverflow", "0022033773.txt" ]
Q: Can't use RestSharp Portable in PCL with both of Xamarin.IOS and Xamarin.Android frameworks Is there possible way to use portable versions of RestSharp in PCL shared between Xamarin.Android and Xamarin.Ios?? I have next error when installing RestSharp.Portable library in project: Install-Package : Could not install package 'FubarCoder.RestSharp.Portable 1.5.0.1'. You are trying to install this package into a project that targets 'portable-win+net45+sl40+wp71+MonoAndroid16+MonoTouch40', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author. A: First of all: Make sure you have the latest version of NuGet installed. Second of all: Your portable library is targeting Silverlight 4 and Windows Phone 7.5. The portable RestSharp package you are trying to install only supports Silverlight 5 or higher and Windows Phone 8. So you need to retarget your portable library to target SL5 instead of SL4 and WP8 instead of WP7.5. Third of all: It looks like you modified the PCL profiles to add Xamarin support. This was the way to do it before Xamarin added official PCL support. Now that they have, you should delete any XML files you added to the PCL profiles and just use the ones Xamarin installs.
[ "stackoverflow", "0014947050.txt" ]
Q: Compiler error vs linker error? Just reading Effective C++ and he mentions several times "linker error", as opposed to compiler error. What constitutes a "linker error" and how do they differ from "compiler errors"? Are the rules/explanations based around a set of categories to logically remember this? A: Compiler errors mean the compiler could not translate the source code you provided into object code. It usually means you have a syntactic or semantic error in your own program that you have to resolve before your program exhibits the behavior you're intending it to have. Linker errors mean the linker could not build an executable program from the object code you provided. It usually means your program does not properly interface with its own dependencies or with the outside world (e.g. external libraries).
[ "stackoverflow", "0057793561.txt" ]
Q: SAML2 for Tomcat8 First, I'm very sorry if this post is too general question. I'm trying to enable SAML2 in my Tomcat8 serverlet. This has been a pain of ass for 2 weeks. Could anyone who has an experience with this share the documentation or something? I've been searching through Google and trying every option available. One of the good articles was in this link: 1- https://medium.com/@chirangaalwis/saml-2-0-based-single-sign-on-and-logout-for-web-applications-deployed-in-apache-tomcat-part-one-6c2dc2df89a3 -> There is no .jar file in GitHub. /modules/samlsso/target/samlsso-1.0.1-SNAPSHOT-fat.jar -> I failed to run mvn clean (So this didn't work) Any advice will be highly appreciated in advance. Thank you so much. A: Question: I'm trying to enable SAML2 in my Tomcat8 serverlet. There is no .jar file in GitHub. /modules/samlsso/target/samlsso-1.0.1-SNAPSHOT-fat.jar -> I failed to run mvn clean (So this didn't work) Answer: (1) On Ubuntu 18.04, I run mvn clean successfully. But I failed to mvn install due to dependency issue. (2) On Ubuntu 14.04, I run mvn clean successfully. I also run mvn install successfully and modules/samlsso/target/samlsso-1.0.1-SNAPSHOT-fat.jar was generated. (3) Tomcat Extension for SAML SSO at GitHub repository provides the guidance on how to configure Tomcat8 to enable SAML2, as indicated by Step 3: Add the necessary configurations and libraries. Remark: The last commit for functionality/feature of Tomcat Extension for SAML SSO at GitHub repository was made on Oct 18, 2016 (almost 3 years ago). Therefore, Ubuntu 18.04 was NOT tested at that time.
[ "stackoverflow", "0030401406.txt" ]
Q: Spark: Using named arguments to submit application Is it possible to write a Spark script that has arguments that can referred to by name rather than index in the args() array? I have a script that has 4 required arguments and depending on the value of those, may require up to 3 additional arguments. For example, in one case args(5) might be a date I need to enter. I another, that date may end up in args(6) because of another argument I need. Scalding has this implemented but I don;t see where Spark does. A: I actually overcame this pretty simply. You just need to preface each argument with a name and a delimiter say "--" when you call your application spark-submit --class com.my.application --master yarn-client ./spark-myjar-assembly-1.0.jar input--hdfs:/path/to/myData output--hdfs:/write/to/yourData Then include this line at the beginning of your code: val namedArgs = args.map(x=>x.split("--")).map(y=>(y(0),y(1))).toMap This converts the default args array into a Map called namedArgs (or whatever you want to call it. From there on, just refer to the Map and call all of your arguments by name. A: Spark does not provide such functionality. You can use Args from scalding (if you don't mind the dependency for such as small class): val args = Args(argsArr.toIterable) You can also use any CLI library that provides the parsing features you may want.
[ "stackoverflow", "0041671217.txt" ]
Q: how to get row value with ajax triggered by onchange dropdown? I tried to update 1 row in table with ajax triggered by onchange dropdown, I succeed update data but it updating all data in my table. so how I can get unique value (eg :User ID) to pass it from ajax to my php so i can update it only 1 row? here's my code : my table (transactions.php) <table class="table table-bordered table-hover table-striped"> <thead> <tr> <th>User ID</th> <th>Pengirim</th> <th>Jumlah Transfer</th> <th>Berita Acara</th> <th>Status</th> <th>Rincian</th> </tr> </thead> <tbody> <?php $query = mysqli_query($koneksi, "select * from konf_transf order by tanggal desc limit 7 "); while($data1 = mysqli_fetch_array($query)){ ?> <tr> <td> <center><?php echo $data1['usr_id']; ?></center> </td> <td> <center><?php echo $data1['nm_pengirim']; ?></center> </td> <td> <center>Rp. <?php echo number_format($data1['jmlh_transf'],0,'','.'); ?>,-</center> </td> <td> <center><?php echo $data1['berita_acara']; ?></center> </td> <td> <center><?php echo $data1['status']; ?></center> </td> <td> <center> <select name="pilihstatus" id="pilihstatus" onchange="updatetransactions();"> <option value="Pilihan">Pilihan</option> <option value="Sudah">Sudah</option> <option value="Belum">Belum</option> </select> </center> </td> </tr> <?php } ?> </tbody> </table> and here my ajax function updatetransactions(){ var id = $('select option:selected').val(); $.ajax({ type:"post", url:"updatestatustransaksi.php", data:"status="+id, success:function(data){ alert('Successfully updated mysql database'); } }); } my updatestatustransaksi.php <?php require_once("koneksi.php"); session_start(); if (!isset($_SESSION['username'])) { echo "<script>alert('You must register an account first, we will redirect you to register page !'); window.location = 'registuser.php'</script>"; } $dataupd = $_POST["status"]; $query = mysqli_query($koneksi, "UPDATE `konf_transf` SET `status` = '$dataupd' WHERE `id` = '$penjualan_id'"); if ($query) { echo "<script>alert('Update Success.'); window.location = 'transactions.php' </script>"; } else { echo "<script>alert('Update Failure.'); window.location = 'transactions.php' </script>"; } A: I assume that you update all of your rows in your database, with no WHERE condition. In your script, lets also get the corresponding id of that row in your database. Lets assign first the id for each table row: while($data1 = mysqli_fetch_array($query)){ ?> <tr id="<?=($data1['user_id'])?>"> Then, lets change how you trigger your javascript. Lets first change the <select> field: <select name="pilihstatus" id="pilihstatus" class="pilihstatus"> Then, get the corresponding id using the script below: $(".pilihstatus").change(function(){ var elem = $(this), selecteditem = elem.val(), id = elem.closest('tr').attr('id'); $.ajax({ type:"post", url:"updatestatustransaksi.php", data: {'status':selecteditem, 'id':id}, success:function(data){ alert('Successfully updated mysql database'); } }); }); And on your updatestatustransaksi.php file (please use prepared statement): $stmt = $koneksi->prepare("UPDATE `konf_transf` SET `status` = ? WHERE `id` = ?"); $stmt->bind_param("si", $_POST['selecteditem'], $_POST['id']); $stmt->execute(); $stmt->close();
[ "stackoverflow", "0019778612.txt" ]
Q: change color for two geom_point() in ggplot2 Sample dataset: library(ggplot2) df = read.table(text = "id year value1 value2 value3 1 2000 1 2000 2001 1 2001 2 NA NA 1 2002 2 2000 NA 1 2003 2 NA 2003 2 2000 1 2001 2003 2 2002 2 NA 2000 2 2003 3 2002 NA 3 2002 2 2001 NA ", sep = "", header = TRUE) df$value1 <- as.factor(df$value1) I know how to change color for a factor variable with three levels: p <- ggplot(df, aes(y=id)) p <- p + scale_colour_manual(name="", values =c("yellow", "orange", "red")) p <- p + geom_point(aes(x=year, color=value1), size=4) p I can also change the color for two numeric variables: p <- ggplot(df, aes(y=id)) p <- p + scale_colour_manual(name="", values =c("value3"="grey", "value2"="black")) p <- p + geom_point(aes(x=value3, colour ='value3'), size=3) p <- p + geom_point(aes(x=value2, colour ='value2'), size=5) p But I do not know how to change the color for both in the same graph? Does it also work with scale_color_manual? p <- last_plot() + geom_point(aes(x=year, color=value1)) p A: Is this what you are looking for? ggplot(df, aes(y=id)) + geom_point(aes(x=year, color=value1), size=4) + geom_point(aes(x=value3, colour ='value3'), size=3) + geom_point(aes(x=value2, colour ='value2'), size=5) + scale_colour_manual(name="", values = c("1"="yellow", "2"="orange", "3"="red", "value3"="grey", "value2"="black")) Basically, just putting all possible colour labels in a single list.
[ "stackoverflow", "0020118846.txt" ]
Q: How to replace comma ',' in an arraylist to ' / ' using javascript How can I replace ',' with a '/' in an array list using javascript. Here my array-list has two string 'values separated by a comma ',' but I want to make it in form of a single string separating the values by '/' ? For eg : array[] = { value1, a1/a2/a3} to be replaced by array[] = {value1/a1/a2/a3} For example: Here I want to replace the outcome which comes as [3,101/102/103] by [3/101/102/103]. Can anyone please suggest ? A: This will make a one-element array with your complete string: var newArr = arr.join(',').replace(/,/g, '/').split(); A: String.prototype.replaceAll = function(target, replacement) { return this.split(target).join(replacement); }; array = new Array("a1/a2/a3") for (i = 0; i < array.length; ++i) { array[i] = array[i].replaceAll("/",",") } does this help?
[ "stackoverflow", "0009047257.txt" ]
Q: I need help installing PLT Racket, I moved the Racket folder into Applications but I don't know how to use the raco command in the terminal To explain, I have OSX and I wanted to install PLT Racket. I don't know how to use the raco command to run .rkt files in the terminal instead of using the Dr. Racket interpreter. I don't really like the DrRacket text editor. Where do I put the bin, lib, and other folders? I can't seem to access the raco command at all or any of the other commands in the Racket bin. A: Don't move subcomponents around. This potentially breaks Racket, which expects the bin directory to be in a certain place relative to its libraries. Instead: add the Racket bin directory to your PATH. See Set environment variables on Mac OS X Lion or Setting environment variables in OS X? for more details on setting up environment variables in Mac OS X. For example, I personally have Racket 5.2 under "/Applications/Racket v5.2/". I have a ~/.profile with the following contents: mithril:~ dyoo$ cat .profile ## Adding Racket 5.2 to my PATH export PATH=/Applications/Racket\ v5.2/bin:$PATH ## .. other contents omitted After a re-login, I can see Racket from the Terminal: mithril:~ dyoo$ which racket /Applications/Racket v5.2/bin/racket I have one additional file, the ~/.MacOSX/environment.plist, whose contents define more environment variables for graphical programs. Mine has the following contents: mithril:~ dyoo$ cat .MacOSX/environment.plist <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>MANPATH</key> <string>/usr/local/man:/usr/share/man:/usr/local/share/man:/usr/X11/man</string> <key>PATH</key> <string>/Users/dyoo/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11/bin:/Applications/Racket\ v5.2/bin</string> </dict> </plist> Having this file lets me run Racket from graphical programs that don't inherit their environment from the .profile login file. A: You can just cd into the Racket/bin directory and execute it from there (you might need to specify ./raco if . isn't in your path). Or you could specify the full path to raco (can't help you w/ that as I don't know where you installed it).
[ "stackoverflow", "0030425299.txt" ]
Q: Passing List from controller to View ASP.NET (null reference) I have a class. In this class I want to list the names of my .txt files in a folder and save them to List<string>: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; namespace Aplikacja.Models { public class Lists { public List<string> ListFiles() { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Kamm\Documents\ASP.NET\"); FileInfo[] files = dir.GetFiles("*.txt"); string str = ""; List<string> allfiles = new List<string>(); foreach(FileInfo file in files) { str = file.Name; allfiles.Add(str); } return allfiles; } } } Then, I have a Controller to put the values into the List to pass it to View: [HttpPost] public ActionResult Index(string listButton) { if (listButton != null) { var list = new Lists(); list.ListFiles(); var names = new List<string>(); names = list.ListFiles(); ViewBag.List = names; return View(); } } And I have a View to populate the list: <button value="List" name="listButton" type="submit" class="btn btn-primary" formmethod="post">List</button> <ul> @foreach (var item in (List<string>)ViewBag.List){ <span> @item </span> } </ul> But when I'm starting the app, I have an error: Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 12: <button value="List" name="listButton" type="submit" class="btn btn-primary" formmethod="post">List</button> Line 13: <ul> Line 14: @foreach (var item in (List<string>)ViewBag.List){ Line 15: <span> Line 16: @item Source File: c:\Users\Kamm\Documents\ASP.NET\Aplikacja\Aplikacja\Aplikacja\Views\Home\Index.cshtml Line: 14 Can someone help me? I don't know what to do, even if I would like to pass a simple List just from Controller I have the same error. Solved! I added a line in View: @if ((List<string>)ViewBag.List != null) Maybe something is wrong when the app is starting.. A: There is a lot of things wrong with your code, however the reason why you get that exception is that you are not adding your list of file names to VieBag in HTTP GET action of controller, but trying to do it in HTTP POST action. Change [HttpPost] to [HttpGet] on your Index action method or just remove that attribute (every action in controller is HttpGet by default unless you mark it with other attribute) and it will work. [HttpGet] public ActionResult Index() { var lists = new Lists(); var names = lists.ListFiles(); ViewBag.List = names; return View(); } However, cleaner solution would be to make your view strongly typed and return the list of file names from your action method.
[ "stackoverflow", "0006679104.txt" ]
Q: ASP.NET MVC - Any reason to use App_Themes? Is there any advantage to ASP.NET's App_Themes folder that could be taken advantage of in ASP.NET MVC, or is using them from the Content folder as normal the best way to handle resources like images, stylesheets, etc. Does the fact that they're in the App_Themes folder add anything special to them? Thanks, James A: App_Themes is for regular ASP.NET, not for MVC. The Themes system is built on top of ASP.NET's event model, which is not used in MVC.
[ "stackoverflow", "0041528038.txt" ]
Q: Redirect in .Net Core Application im trying to do some operation .Net Core and after this operation is done, i want to redirect it to a .cshtml page. In homepage i have table, after selecting a row in the table, im sending the value of the cell with ajax. AJAX $('#table').find('tr').click(function () { var userName = $(this).find('td').text(); $.ajax({ url: "/Profile/printUser", type: 'POST', data: { "DisplayName": userName } }); }); After this part, im going to this area FUNCTION [HttpPost] public IActionResult printUser(User user) { user.DisplayName = user.DisplayName.Replace("\n", String.Empty); user.DisplayName = user.DisplayName.Trim(' '); User findUser = UserAdapter.GetUserByUserName(user.DisplayName); return RedirectToAction("ProfileScreen",findUser); } My operations are finished, i found my user. All i want to do is print this users information in cshtml. But i cant send myselft to the page. How can i redirect myself? Thanks. INDEX public IActionResult ProfileScreen() { return View(); } A: You can't redirect from Ajax call in the backend. Use AJAX's success: function(){ windows.location.href = '/ProfileScreen'; } If you want to pass data back, return JSON from MVC action and your JavaScript would be: $('#table').find('tr').click(function () { var userName = $(this).find('td').text(); $.ajax({ url: "/Profile/printUser", type: 'POST', data: { "DisplayName": userName }, success: function(data){ window.location.href = '/ProfileScreen' + data.ID; //or whatever } }); });
[ "math.stackexchange", "0000166158.txt" ]
Q: Question on meaning of a symbol: long thin C I don't know how to write it in $\LaTeX.$ It is a tall skinny bold C. This is the context: A set is defined by: where $\complement\atop{\smash \scriptstyle i}$ is the thing I don't understand. The $i$ is actually directly underneath the weird $C$ in this case. Can anyone explain what this means? A: It's the coefficient operator. It extracts the ith coefficient of the Taylor expansion. This is used a lot in combinatorics with generating functions.
[ "stackoverflow", "0015713269.txt" ]
Q: npm API - cannot require module npm On the npm docs it says that I can require it and use it's api however when I do: $ node var npm = require("npm"); Error: Cannot find module 'npm' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module.require (module.js:362:17) at require (module.js:378:17) at repl:1:11 at REPLServer.self.eval (repl.js:109:21) at rli.on.self.bufferedCmd (repl.js:258:20) at REPLServer.self.eval (repl.js:116:5) at Interface.<anonymous> (repl.js:248:12) at Interface.EventEmitter.emit (events.js:96:17) > A: it worked to do $ sudo npm install --save npm Sorry
[ "stackoverflow", "0052914091.txt" ]
Q: android studio makes corrupted Colors.xml, then unknown errors occur Recently I was working with my android studio with no problems, suddenly my project started giving random errors(about my resources) after I tried to add a new library to my project. I completely cleaned the library but nothing got fixed, at all I wanted to make a new project, and faced new errors colors.xml:1:1: Error: Content is not allowed in prolog. Android studio made a corrupted file like this for colors.xml: ���� 3 area I ConstantValue length temperature weight <init> ()V Code LineNumberTable LocalVariableTable this array InnerClasses ,Lcom/example/a When I fixed this xml, another error: Android resource compilation failed ic_launcher_round.xml:1: error: not well-formed (invalid token). aapt2.exe compile --legacy \ I have tried: Invalidate Cache/Restart Deleting .gradle folder in my C:\Users Redownload the gradle Delete gradle folder of project Choosing diffrent names for layouts and packages Restart PC 5 Hours Googling (no result) And ic_launcher_round.xml as asked: ���� 3 � � � � 0abc_background_cache_hint_selector_material_dark I ConstantValue 1abc_background_cache_hint_selector_material_light (abc_btn_colored_borderless_text_material abc_btn_colored_text_material abc_color_highlight_material A: You don't need to reinstall Android Studio: close it, and delete the folder .AndroidStudioX.Y (X and Y depends on your Android studio version) in the user folder. The answer is old, but I have the same problem today with Android Studio 3.3.2. I give my answer with the hope it can help other developers. In a random way, Android studio cannot open some files. In the first instance, I thought that the files were corrupted. After opening the same file with an external editor I realized that is not true. In the above example, the .iml file cannot be read by Android Studio. I open the same file with Notepad++ and I luckily saw that file was good. A: This is a known bug which reported by many developers and I've faced that once. The only fix is to reinstall the Android Studio or downloading the new version of the IDE but, don't import the old config when you reinstall or updating it. To be clear, changing File-Encoding in settings to UTF-8 or System Default doesn't work either.
[ "stackoverflow", "0024978381.txt" ]
Q: Split a image tag on html string code: <div id="start"> <p>"hi split html string"<p><br>"now" <img class="image1" src="some src" master_src="some src" master_w="400" master_h="320"> "second tag is coming"<br><img class="image2" src="some src" master_src="some src" master_w="400" master_h="320"><h1>end here</h1> </div> output: <p>"hi split html string"<p><br>"now" , "second tag is coming"<br> , <h1>end here</h1> How can i achieve this ouput? what could be regex expression fot this image class in order to use split function(or any better way)?Please give me a demo A: why are you askying the same question multiple time?Here is you answer $('#start').find('img').each(function(index){ var split_text = $(this).html().split(/<img[^>]*>/)[index]; alert(split_text) });
[ "serverfault", "0000250925.txt" ]
Q: HP ProLiant DL380 G7 iLO error I have a HP ProLiant DL380 G7 server which sent me an email that's got me worried. The system has detected the following event: SNMP Trap: 9006 Date time: 03/19/2011 11:47:46 PM Computer: DC1.domain.local Source: Server Agents Type: Error Category: (4) Description: A 'Remote Insight Board Interface Error' trap signifies that the Compaq Remote Insight Board has detected a controller interface error. Details: None I looked at my event log and I have a corresponding log in the Event Viewer. I also looked back a bit further and found the following 2 events have happened 3 or 4 times since the beginning of the year. Log Name: System Source: hpqilo3 Date: 19/03/2011 07:06:00 Event ID: 78 Task Category: None Level: Information Keywords: Classic User: N/A Computer: DC1.domain.local Description: The ProLiant Monitor Service is unable to communicate with HP ProLiant iLO 3 Management Controller. Event Xml: <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> <System> <Provider Name="hpqilo3" /> <EventID Qualifiers="16642">78</EventID> <Level>4</Level> <Task>0</Task> <Keywords>0x80000000000000</Keywords> <TimeCreated SystemTime="2011-03-19T07:06:00.000000000Z" /> <EventRecordID>7147</EventRecordID> <Channel>System</Channel> <Computer>DC1.domain.local</Computer> <Security /> </System> <EventData> </EventData> </Event> Log Name: System Source: hpqilo3 Date: 19/03/2011 07:06:20 Event ID: 79 Task Category: None Level: Information Keywords: Classic User: N/A Computer: DC1.domain.local Description: The ProLiant Monitor Service is now able to communicate with HP ProLiant iLO 3 Management Controller. Event Xml: <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> <System> <Provider Name="hpqilo3" /> <EventID Qualifiers="16642">79</EventID> <Level>4</Level> <Task>0</Task> <Keywords>0x80000000000000</Keywords> <TimeCreated SystemTime="2011-03-19T07:06:20.000000000Z" /> <EventRecordID>7148</EventRecordID> <Channel>System</Channel> <Computer>DC1.domain.local</Computer> <Security /> </System> <EventData> </EventData> </Event> First of all, I notice there is a firmware update available. Do you think this will help me out or is the iLO board (which is on the motherboard right?) or motherboard faulty? A: It may help you but this is a simple bug probably due to the still-pretty-new iLO v3 code, basically update - hope if fixes it - if not ignore and/or report to HP.
[ "avp.stackexchange", "0000009873.txt" ]
Q: Is it bad form to have a different number of audio tracks from video tracks? In Premier when adding a new Audio or Video track it wants to add both. In industry is it considered good form to leave empty tracks, say: V2 Movie Clip V1 Title A1 BG Music A2 nothing Or is it better form to delete those extra tracks or not add them to begin with so instead it looks like V2 Movie Clip V1 Title A1 BG Music A: I always avoid excess tracks. You can add as many or few tracks of each types as you want in "Add Tracks..." Simply adjust the number of tracks to be added by clicking on the number. It defaults to 1 video and 1 audio track, but that can easily be changed each time you add tracks. You can also add an individual track to either by right clicking in the header area and saying Add Track. As far as industry standards go, I've never heard of a standard and I've never known anyone to think anything of having unused tracks, but cleanliness is always a plus. There is certainly no standard to intentionally use excess tracks, but in my experience nobody is going to think anything if there are a few excess tracks either. Generally cleaning up after yourself does look a little more professional though.
[ "stackoverflow", "0059139069.txt" ]
Q: 架 (U+67B6) is not graphical with en_US.UTF-8. Whats going on? This is a follow up question to: std::isgraph asserts, how to fix? After setting locale to "en_US.UTF-8", std::isgraph no longer asserts. However, the unicode character 架 (U+67B6) is reported as false in the same function. What is going on ? It's a unicode built on Windows platform. A: If you want to test characters that are too large to fit in an unsigned char, you can try using the wide-character versions, or a Unicode library as already suggested (Which is really the better option for portable code, as it removes any system or locale based differences in behavior). This program: #include <clocale> #include <cwctype> #include <iostream> int main() { wchar_t x = L'\u67B6'; char *loc = std::setlocale(LC_CTYPE, ""); std::wcout << "Using locale " << loc << ".\n"; std::wcout << "Character " << x << " is graphical: " << std::boolalpha << static_cast<bool>(std::iswgraph(x)) << '\n'; return 0; } when compiled and ran on my Ubuntu test system, outputs Using locale en_US.utf8. Character 架 is graphical: true You said you're using Windows, but I don't have a Windows computer available for testing, so I can't confirm if this'll work there or not.
[ "english.stackexchange", "0000140676.txt" ]
Q: cool vs cold (which can be used to express the temperature) which word can we use to say that temperature ? example 1 - its too cool over here, example 2 - its too cold over here, i have heard that cold means too much cool but would like to know whether is correct or not. tnx A: I agree that using the word "too" makes a big difference in this sentence. It's perfectly acceptable to my ear to say "It's too cool over here" in a context in which warmth is expected. In this case, I might also use the phrase "It's cold over here" to mean the same thing as "too cool" because it is supposed to be warm or hot. "It's too cold over here" would be most acceptable if I expected it to be cool. Basically, I think English speakers would consider air temperature "cool" to be in the 60s Fahrenheit, and "cold" to be closer to 40F. For liquids (for which internal body temperature is usually the basis for comparison, such as hot drinks or a swimming pool), I would think 80s for "cool" (e.g. below body temp), and cold starting in the low 70sF. Of course, if you're thinking of cold drinks, I would consider a soda "warm" if it was 70F. Once you use the word "too," however, you are now talking more about personal perception than actual temperature. You might also consider using the word "chilly," which generally connotes "uncomfortably cool," as opposed to "uncomfortably cold." I don't think of "chilly" as tied specifically to a temperature, more to a personal preference and contrast with what is expected or preferred.
[ "stackoverflow", "0053284127.txt" ]
Q: Unable to import sass files in react I'm using the following boilerplate : https://github.com/spravo/typescript-react-express I designed a first component : Button import * as React from 'react'; import './button.scss'; export interface IButton { value: string; onClick: () => void; } class Button extends React.Component<IButton, {}> { public render () { return ( <div className='Button'> <button onClick={this.props.onClick} className='Button__btn'> {this.props.value} </button> </div> ); } } export default Button; And in the button.scss I have this simple line : .Button { background-color: red; } But I get the following error : (function (exports, require, module, __filename, __dirname) { .Button { SyntaxError: Unexpected token . This is my webpack config (quite the same as the one from the repo) except the config.common.js for the webpack migration : 'use strict'; const path = require('path'); const webpack = require("webpack"); const config = require('../config')(process.env.NODE_ENV); const vendors = require('./vendor'); const NODE_ENV = process.env.NODE_ENV || 'development'; module.exports = function getConfig(dirname) { return { target: 'web', context: path.resolve(dirname), stats: { chunks: false, colors: true, }, entry: { vendor: vendors }, resolve: { extensions: [ '.ts', '.tsx', '.js', '.scss', '.css' ], modules: [ path.resolve(__dirname, '..', 'src'), path.resolve(__dirname, '..', 'node_modules'), ] }, output: { path: config.PUBLIC_FOLDER, filename: '[name].[hash].js', chunkFilename: '[name].[chunkhash].js', publicPath: config.PUBLIC_PATH }, module: { rules: [] }, optimization:{ splitChunks:{ name: 'vendor' } }, plugins: [ new webpack.NoEmitOnErrorsPlugin(), // new webpack.optimize.CommonsChunkPlugin({ // name: 'vendor' // }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(NODE_ENV) }, __CLIENT__: true, __SERVER__: false, __DEV__: NODE_ENV === 'development', __TEST__: false }) ] }; }; The Css loaders : 'use strict'; const isDevelopment = (process.env.NODE_ENV || 'development') === 'development'; const autoprefixer = require('autoprefixer'); module.exports = { scssLoader: [ { loader: 'css-loader', options: { minimize: !isDevelopment, sourceMap: isDevelopment } }, { loader: 'postcss-loader', options: { sourceMap: isDevelopment, plugins: [ autoprefixer({ browsers:['ie >= 8', 'last 4 version'] }) ] } }, { loader: 'sass-loader', options: { sourceMap: isDevelopment } } ] }; It seems that the only scss that works is in the styles/index.scss but I don't get why it doesn't take other scss files. My tsconfig.json { "compilerOptions": { "module": "commonjs", "baseUrl" : "./src", "target": "es5", "jsx": "react", "alwaysStrict": true, "sourceMap": true, "outDir": "dist", "lib": [ "dom", "es2015", "es5", "es6" ] }, "include": [ "src/**/*.ts", "src/**/*.tsx", "typings" ], "exclude": [ "node_modules" ] } A: It is really weird that your webpack config "module.rules" is an empty array! That is where your loader settings should be added. If I were you, I would have copied the content of css-loaders config file and pasted in your webpack.config.js file. Make sure you store it in a normal variable/object instead of module.exports. This is how my webpack config looks like: const styleLoader = { test: /\.(scss)$/, include: path.resolve(__dirname, 'src'), use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { sourceMap: true, minimize: true } }, { loader: 'postcss-loader', options: { sourceMap: true, config: { path: path.join(__dirname, 'postcss.config.js') } } }, { loader: 'sass-loader', options: { sourceMap: true } } ] }) }; And then my webpack config looks like below. Pay attention to the modules.rules section: module.exports = { entry: { app: ['babel-polyfill', 'whatwg-fetch', srcPath('index.js')], silentrenew: [srcPath('silentrenew.js')] }, output: { path: path.resolve(__dirname, 'build'), publicPath: '/', filename: '[name].js' }, devtool: 'source-map', plugins: [ htmlPlugin('index.html', 'app'), new ExtractTextPlugin('bundle.css'), ], module: { rules: [ babelLoader, fontLoader, svgLoader, styleLoader ] } };
[ "stackoverflow", "0013197951.txt" ]
Q: Add text value to jquery function (var) How can I add input text variable(value) to function(var description) ? $(".update").click(function() { var article_id=$(this).attr("article_id"); var description=$(this).attr("description"); $.ajax ({ type: "POST", url: "conf.php", data: { article_id: article_id, description: description, },.. <a href="javascript:;" class="update" article_id="$id">Description</a><input type="text"></input> A: You mean $(".update").click(function(e) { e.preventDefault(); // do not follow the link var article_id=$(this).attr("article_id"); var description=$(this).next("input").val();
[ "stackoverflow", "0012993298.txt" ]
Q: g-wan not updating dependencies of servlets When I modify hello.c included with g-wan to include a simple header with #define TEST_VALUE 50 and output it in the hello.c file I noticed that a change to the header file did not trigger an update for g-wan to update the servlet. So if I change the header file test value to 51, no change is noted in the output. If I make any change to the hello.c file, it causes g-wan to recompile the servlet including the dependencies and the change in the header is compiled. Is this the expected behavior? I'm curious because that would mean during development with many dependencies, you would need to update just one character in the main servlet file to trigger a re-compile if all the changes being made are in dependency files. This behavior was noted by Tim Bolton so I decided to also test it, and pose it as a separate question from a previous thread. Thanks for any input. G-WAN 3.3.28 64-bit (Mar 28 2012 11:24:16) - the latest version I saw in the download as of Oct 19th, 2012 ... running on Ubuntu Server 10.04.4 LTS - 64 bit A: Is this the expected behavior? Yes. that would mean during development with many dependencies, you would need to update just one character in the main servlet file to trigger a re-compile if all the changes being made are in dependency files. No. There's a better way used by programmers for (at least) the past 30 years. The touch Unix command is updating the time stamp of a file without changing its contents. Just touch the hello.c servlet when you change its headers. Also note that C headers are supposed to be more 'stable' than C files. What is stored in headers is there to be shared by many C files so you should consider to use C files for defines that change often. At least you know how to proceed in both cases now.
[ "stackoverflow", "0051995644.txt" ]
Q: How to set up a custom listener in a custom dialog for android? I'm currently having trouble setting up my custom listener. I just want to pass a string from my dialog to my fragment (where I set up the dialog). I was trying to follow this tutorial: https://www.youtube.com/watch?v=ARezg1D9Zd0. At minute 10:38, he sets up the listener. This only problem is that in this, he uses DialogFragment, but I'm extending dialog and I don't know how to attach the context to the listener. I've tried to set it up in onAttachedToWindow() and in the dialog constructor but it crashes. What should I actually do? I'd also appreciate it if someone could explain what the difference is between: onAttachedToWindow() vs. onAttach(Context context). Thanks! MY CUSTOM DIALOG BOX: public class NewListDialog extends Dialog implements View.OnClickListener { private Activity c; private TextInputLayout textInputLayout; private TextInputEditText editText; private LinearLayout dialog_root_view; private Animation fade_out; private String list_name; private NewListDialogListener listener; NewListDialog(Activity a) { super(a); this.c = a; //ANOTHER ATTEMPT TO ATTACH CONTEXT TO LISTENER //listener = (NewListDialogListener) a.getApplicationContext(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.new_list_dialog); MaterialButton cancel = findViewById(R.id.dialog_new_list_cancel_button); MaterialButton create = findViewById(R.id.dialog_new_list_create_button); textInputLayout = findViewById(R.id.dialog_text_input_layout); editText = findViewById(R.id.dialog_edit_text); dialog_root_view = findViewById(R.id.dialog_root); fade_out = AnimationUtils.loadAnimation(c, R.anim.fade_out_dialog); editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View view, int i, KeyEvent keyEvent) { if (isTextValid(editText.getText())) { textInputLayout.setError(null); return true; } return false; } }); cancel.setOnClickListener(this); create.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { //Cancel Button case R.id.dialog_new_list_cancel_button: dialog_root_view.startAnimation(fade_out); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { dismiss(); } }, 200); break; //Create Button case R.id.dialog_new_list_create_button: if (!isTextValid(editText.getText())) { textInputLayout.setError(c.getString(R.string.dialog_error)); } else { textInputLayout.setError(null); //record input string list_name = editText.getText().toString(); //send information to parent activity //What to put here? listener.createListName(list_name); dismiss(); } break; default: break; } } private boolean isTextValid(@Nullable Editable text) { return text != null && text.length() > 0; } //ATTEMPT TO ATTACH CONTEXT TO LISTENER @Override public void onAttachedToWindow() { super.onAttachedToWindow(); try { listener = (NewListDialogListener) c.getBaseContext(); } catch (ClassCastException e) { throw new ClassCastException(c.getBaseContext().toString() + "must implement ExampleDialogListener"); } } public interface NewListDialogListener { void createListName(String listname); } } A: In case you define a custom dialog then you can declare a method to allow other components call it or listen events on this dialog. Add this method to you custom dialog. public void setNewListDialogListener(NewListDialogListener listener){ this.listener = listener; } NewListDialog.java public class NewListDialog extends Dialog implements View.OnClickListener { private Activity c; private TextInputLayout textInputLayout; private TextInputEditText editText; private LinearLayout dialog_root_view; private Animation fade_out; private String list_name; private NewListDialogListener listener; NewListDialog(Activity a) { super(a); this.c = a; } public void setNewListDialogListener(NewListDialogListener listener) { this.listener = listener; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.new_list_dialog); MaterialButton cancel = findViewById(R.id.dialog_new_list_cancel_button); MaterialButton create = findViewById(R.id.dialog_new_list_create_button); textInputLayout = findViewById(R.id.dialog_text_input_layout); editText = findViewById(R.id.dialog_edit_text); dialog_root_view = findViewById(R.id.dialog_root); fade_out = AnimationUtils.loadAnimation(c, R.anim.fade_out_dialog); editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View view, int i, KeyEvent keyEvent) { if (isTextValid(editText.getText())) { textInputLayout.setError(null); return true; } return false; } }); cancel.setOnClickListener(this); create.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { //Cancel Button case R.id.dialog_new_list_cancel_button: dialog_root_view.startAnimation(fade_out); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { dismiss(); } }, 200); break; //Create Button case R.id.dialog_new_list_create_button: if (!isTextValid(editText.getText())) { textInputLayout.setError(c.getString(R.string.dialog_error)); } else { textInputLayout.setError(null); //record input string list_name = editText.getText().toString(); //send information to parent activity //What to put here? if (listener != null) { listener.createListName(list_name); } dismiss(); } break; default: break; } } private boolean isTextValid(@Nullable Editable text) { return text != null && text.length() > 0; } public interface NewListDialogListener { void createListName(String listname); } } In other components such as an activity which must implements NewListDialogListener. NewListDialog dialog = new NewListDialog(this); dialog.setNewListDialogListener(this); If you don't want the activity implements NewListDialogListener then you can pass a listener instead. NewListDialog dialog = new NewListDialog(this); dialog.setNewListDialogListener(new NewListDialog.NewListDialogListener() { @Override public void createListName(String listname) { // TODO: Your code here } });
[ "stackoverflow", "0002946052.txt" ]
Q: Kohana 3 - Query builder gives 0 rows The following query returns one row as expected when run from phpmyadmin. SELECT units . * , locations . * FROM units, locations WHERE units.id = '1' AND units.location_id = locations.id LIMIT 0 , 30 But when I try to do it in Kohana 3: $unit = DB::select('units.*', 'locations.*') ->from('units', 'locations') ->where('units.id', '=', $id)->and_where('units.location_id', '=', 'locations.id') ->execute()->as_array(); var_dump($unit); It prints array(0) { } What am I doing wrong? A: I can't immediately tell what is wrong with that query builder, however, checkout this for debugging purposes. After calling execute() on your db chain, try this. echo Database::instance()->last_query; This will show in plain SQL the last query performed. It will be worth looking at what the query builder generated, and how it differs to your SQL you used in phpmyadmin. If all else fails, just use the plain query methods. $query = "SELECT units . * , locations . * FROM units, locations WHERE units.id = :id AND units.location_id = locations.id LIMIT 0 , 30 "; $unit = Db::query(Database::SELECT, $query) ->bind(':id', (int) $id) ->execute() ->as_array();
[ "math.stackexchange", "0000353846.txt" ]
Q: Hartshorne Problem 1.2.14 on Segre Embedding This is a problem in Hartshorne concerning showing that the image of $\Bbb{P}^n \times \Bbb{P}^m$ under the Segre embedding $\psi$ is actually irreducible. Now I have shown with some effort that $\psi(\Bbb{P}^n \times \Bbb{P}^m)$ is actually equal to $V(\mathfrak{a})$ where $\mathfrak{a}$ is the ideal generated by the set of all monomials $$\Big\{z_{ij}z_{kl} - z_{il}z_{kj} \hspace{1mm} \Big| \hspace{1mm} i,k = 0,\ldots, n; \hspace{2mm} j,l = 0,\ldots,m\Big\}.$$ My main problem now is in showing that $\mathfrak{a}$ is actually equal to the kernel of the ring homomorphism $$\varphi : k[z_{ij}] \to k[x_0,\ldots,x_n,y_0,\ldots,y_m]$$ that sends $z_{ij}$ to $x_iy_j$. I have spent quite a few hours playing around with monomial orderings and trying to show that $\mathfrak{a} \supseteq \ker \varphi$ but to no avail. Of course the other inclusion is immediate. Is there anything I can do apart from playing around with monomial orderings to try and show that the kernel of $\varphi$ is equal to $\mathfrak{a}$? Perhaps maybe something along the lines of inducting on $n$, those this does not look promising. Note: Please do not close this question; my question is different from the other questions on this site concerning the Segre embedding. Also, I can show my work concerning how I arrived at the conclusion that $V(\mathfrak{a}) = \psi(\Bbb{P}^n \times \Bbb{P}^n)$. A: I outlined a proof by Bjorn Poonen at http://www.artofproblemsolving.com/Forum/viewtopic.php?p=2450856#p2450856 . As Nils Matthes has noticed, computing the kernel is not necessary to solve Hartshorne's problem, though (in my opinion) it is more interesting than the problem itself. $\newcommand{\kk}{\mathbb{k}}$ $\newcommand{\Ker}{\operatorname{Ker}}$ For the sake of self-containedness, let me repost the proof linked above here (with improved notations). I begin by restating the problem: Theorem 1. Let $\kk$ be a commutative ring with $1$. Let $n$ and $m$ be two nonnegative integers. Let $M=\left\{0,1,\ldots ,m\right\}$ and $N=\left\{0,1,\ldots ,n\right\}$. Let $R$ be the polynomial ring $\kk\left[Z_{i,j} \mid i \in M \text{ and } j \in N \right]$. Let $S$ be the polynomial ring $\kk\left[x_0, x_1, \ldots, x_m, y_0, y_1, \ldots, y_n \right]$. Let $\phi : R \to S$ be the unique $\kk$-algebra homomorphism that sends each $Z_{i,j}$ to $x_i y_j$. Let $W$ be the ideal of $R$ generated by all elements of the type $Z_{a,b} Z_{c,d} - Z_{a,d} Z_{c,b}$ with $a \in M$, $b \in N$, $c \in M$ and $d \in N$. Then, $\Ker \phi = W$. To prove this, we shall use the following easy algebraic lemma: Lemma 2. Let $C$ be a $\kk$-module. Let $A$ and $B$ be two submodules of $C$ such that $C=A+B$. Let $\psi$ be a $\kk$-module map from $C$ to another $\kk$-module $D$ such that $\psi\mid_A$ is injective and $\Ker \psi \supseteq B$. Then, $\Ker \psi = B$. Proof of Lemma 2. Let $c \in \Ker \psi$. Thus, $c \in \Ker \psi \subseteq C = A + B$; hence, we can write $c$ in the form $c = a + b$ for some $a \in A$ and $b \in B$. Consider these $a$ and $b$. We have $b \in B \subseteq \Ker \psi$, so that $\psi\left(b\right) = 0$. Applying the map $\psi$ to the equality $c = a + b$, we obtain $\psi\left(c\right) = \psi\left(a + b\right) = \psi\left(a\right) + \psi\left(b\right)$ (since $\psi$ is a $\kk$-module map). Comparing this with $\psi\left(c\right) = 0$ (which follows from $c \in \Ker \psi$), we obtain $0 = \psi\left(a\right) + \underbrace{\psi\left(b\right)}_{= 0} = \psi\left(a\right)$, so that $\psi\left(a\right) = 0 = \psi\left(0\right)$. Since $\psi\mid_A$ is injective, this entails $a = 0$ (because both $a$ and $0$ belong to $A$). Thus, $c = \underbrace{a}_{=0} + b = b \in B$. Now, forget that we fixed $c$. We thus have shown that $c \in B$ for each $c \in \Ker \psi$. Thus, $\Ker \psi \subseteq B$. Combining this with $\Ker \psi \supseteq B$, we obtain $\Ker \psi = B$. This proves Lemma 2. $\blacksquare$ Proof of Theorem 1 (Bjorn Poonen) (sketched). We notice that $\Ker \phi\supseteq W$ is very easy to prove (in fact, a trivial computation shows that $\Ker \phi$ contains $Z_{a,b}Z_{c,d}-Z_{a,d}Z_{c,b}$ for all $a$, $b$, $c$, $d$). We order the set $M\times N$ lexicographically. If $k$ is a nonnegative integer, then $S_k$ shall denote the symmetric group consisting of all permutations of $\left\{1,2,\ldots,k\right\}$. Every $k$-tuple $\left(\left(a_1,b_1\right),\left(a_2,b_2\right),\ldots ,\left(a_k,b_k\right)\right) \in \left(M\times N\right)^k$ and every permutation $\sigma \in S_k$ satisfy \begin{equation} Z_{a_1,b_1}Z_{a_2,b_2}\cdots Z_{a_k,b_k} \equiv Z_{a_1,b_{\sigma 1}}Z_{a_2,b_{\sigma 2}}\cdots Z_{a_k,b_{\sigma k}} \mod W . \label{darij.pf.thm1.1} \tag{1} \end{equation} (In fact, this is obvious from the definition of $W$ when $\sigma$ is a transposition, and hence, by induction, it also holds for every permutation $\sigma$, because every permutation is a composition of transpositions.) Now, let $T$ be the $\kk$-submodule of $\kk\left[Z_{i,j}\mid \left(i,j\right)\in M\times N\right]$ generated by all products of the form $Z_{a_1,c_1}Z_{a_2,c_2}\cdots Z_{a_k,c_k}$ with $k$ being a nonnegative integer and $\left(\left(a_1,c_1\right),\left(a_2,c_2\right),\ldots,\left(a_k,c_k\right)\right)\in \left(M\times N\right)^k$ being a $k$-tuple satisfying $a_1\leq a_2\leq \cdots\leq a_k$ and $c_1\leq c_2\leq \cdots\leq c_k$. It is easy to see that the map $\left.\phi\mid_T\right. : T \to \kk\left[x_0,x_1,\ldots,x_m,y_0,y_1,\ldots,y_n\right]$ is injective. (In fact, if $\left(\left(a_1,c_1\right),\left(a_2,c_2\right),\ldots,\left(a_k,c_k\right)\right)\in T$, then \begin{align} \left(\phi\mid_T\right)\left(Z_{a_1,c_1}Z_{a_2,c_2}\cdots Z_{a_k,c_k}\right) &= \phi\left(Z_{a_1,c_1}Z_{a_2,c_2}\cdots Z_{a_k,c_k}\right) \\ &= x_{a_1}y_{c_1}x_{a_2}y_{c_2}\cdots x_{a_k}y_{c_k} \\ &=x_{a_1}x_{a_2}\cdots x_{a_k}y_{c_1}y_{c_2}\cdots y_{c_k} \end{align} is a monomial from which we can recover the $k$-tuple $\left(a_1,a_2,\ldots ,a_k\right)$ up to order and the $k$-tuple $\left(c_1,c_2,\ldots ,c_k\right)$ up to order; but since the order of each of these two $k$-tuples is predetermined by the condition that $a_1\leq a_2\leq \cdots\leq a_k$ and $c_1\leq c_2\leq \cdots\leq c_k$, we can therefore recover these two $k$-tuples completely; hence, the map $\phi\mid_T$ sends distinct monomials to distinct monomials, and thus is injective.) Next we are going to show that: \begin{equation} \text{every monomial in $\kk\left[Z_{i,j}\mid \left(i,j\right)\in M\times N\right]$ lies in $T+W$.} \label{darij.pf.thm1.2} \tag{2} \end{equation} [Proof of \eqref{darij.pf.thm1.2}: Let $\mu$ be any monomial in $\kk\left[Z_{i,j}\mid \left(i,j\right)\in M\times N\right]$. Then, $\mu=Z_{a_1,b_1}Z_{a_2,b_2}\cdots Z_{a_k,b_k}$ for some nonnegative integer $k$ and some $k$-tuple $\left(\left(a_1,b_1\right),\left(a_2,b_2\right),\ldots,\left(a_k,b_k\right)\right)\in \left(M\times N\right)^k$ such that $\left(a_1,b_1\right)\leq\left(a_2,b_2\right)\leq \cdots\leq \left(a_k,b_k\right)$. Consider such a $k$ and such a $k$-tuple $\left(\left(a_1,b_1\right),\left(a_2,b_2\right),\ldots,\left(a_k,b_k\right)\right)$. Since $\left(a_1,b_1\right)\leq\left(a_2,b_2\right)\leq \cdots\leq \left(a_k,b_k\right)$, we have $a_1\leq a_2\leq \cdots\leq a_k$ (since our order is lexicographic). Clearly there exists a permutation $\sigma\in S_k$ such that $b_{\sigma 1}\leq b_{\sigma 2}\leq \cdots \leq b_{\sigma k}$. Consider such a $\sigma$. Let $c_i=b_{\sigma i}$ for every $i\in\left\{1,2,\ldots,k\right\}$. Hence, the chain of inequalities $b_{\sigma 1}\leq b_{\sigma 2}\leq \cdots \leq b_{\sigma k}$ rewrites as $c_1\leq c_2\leq \cdots\leq c_k$. Also, \begin{align} \mu &= Z_{a_1,b_1}Z_{a_2,b_2}\cdots Z_{a_k,b_k} \\ &\equiv Z_{a_1,b_{\sigma 1}}Z_{a_2,b_{\sigma 2}}\cdots Z_{a_k,b_{\sigma k}} \qquad \left( \text{by \eqref{darij.pf.thm1.1}} \right) \\ &= Z_{a_1,c_1} Z_{a_2,c_2} \cdots Z_{a_k,c_k} \mod W \end{align} (since $b_{\sigma i}=c_i$ for every $i\in\left\{1,2,\ldots,k\right\}$). But since $a_1\leq a_2\leq \cdots\leq a_k$ and $c_1\leq c_2\leq \cdots\leq c_k$, we have $Z_{a_1,c_1} Z_{a_2,c_2} \cdots Z_{a_k,c_k}\in T$ (by the definition of $T$), so this rewrites as follows: \begin{align} \mu &\equiv \left(\text{an element of }T\right)\mod W . \end{align} In other words, $\mu\in T+W$. Since this holds for every monomial $\mu$ in $\kk\left[Z_{i,j}\mid \left(i,j\right)\in M\times N\right]$, this proves \eqref{darij.pf.thm1.2}.] Since the monomials in $\kk\left[Z_{i,j}\mid \left(i,j\right)\in M\times N\right]$ generate the $\kk$-module $\kk\left[Z_{i,j}\mid \left(i,j\right)\in M\times N\right]$, and since $T+W$ is a submodule of this $\kk$-module, we obtain $\kk\left[Z_{i,j}\mid \left(i,j\right)\in M\times N\right]=T+W$ from \eqref{darij.pf.thm1.2}. Applying Lemma 2 to $C=\kk\left[Z_{i,j}\mid \left(i,j\right)\in M\times N\right]$, $A=T$, $B=W$ and $\psi=\phi$, we thus conclude that $\Ker \phi = W$. This proves Theorem 1. $\blacksquare$ There is yet another way to prove Theorem 1 -- namely, by revealing it to be a particular case of the Second Fundamental Theorem of Invariant Theory for GL. See https://mathoverflow.net/questions/202005/a-vector-version-of-the-segre-embedding-what-is-the-kernel-of-the-ring-map for this generalization. (Another place where this generalization appears with proof is Theorem 5.1 of J. Désarménien, Joseph P. S. Kung, Gian-Carlo Rota, Invariant Theory, Young Bitableaux, and Combinatorics, unofficial re-edition 2017; you just need to set $d = 1$, and realize that every standard $\left(\mathcal{X},\mathcal{U}\right)$-bideterminant of shape strictly longer than $\left(d\right)$ contains at least one row of length $\geq 2$, which is easily seen to place it inside the ideal $W$.) A: Indeed as Nils Matthes suggested we don't know need to go through such a mess and just use the hint of Hartshorne. Define a map $\varphi : k[T_{00} , \ldots, T_{nm}] \to k[X_0,\ldots,X_n,Y_0,\ldots,Y_m]$ that sends $T_{ij}$ to $X_iY_j$. Let $\mathfrak{a} := \ker \varphi$. We claim that $\psi (\Bbb{P}^n \times \Bbb{P}^m) = V(\mathfrak{a})$. For one inclusion if a point $$a = [a_{00} : \ldots : a_{nm}] \in V(\mathfrak{a})$$ then in particular $a$ is a zero of all the polynomials $T_{ij}T_{kl} - T_{il}T_{kj}$. But this means that $a \in \psi(\Bbb{P}^n \times \Bbb{P}^m)$. The reverse inclusion follows immediately from the definition of $\varphi$. Thus $V(\mathfrak{a}) = \psi(\Bbb{P}^n \times \Bbb{P}^m)$ and the projective Nullstellensatz implies that $\psi(\Bbb{P}^n \times \Bbb{P}^m)$ is a projective variety. A: It's easy to show the preimage under the Segre map of an algebraic set is an algebraic subset of $\mathbb{P}^n \times \mathbb{P}^m.$ If $V$ were reducible, we could write $V = V_1 \cup V_2,$ where $V_i\neq V$ are closed. Then $$ \mathbb{P}^n \times \mathbb{P}^m = S^{-1}(V) = S^{-1} (V_1) \bigcup S^{-1}(V_2)$$ where $S^{-1}(V_i)$ are closed. Picking $x_i \in V\setminus V_i$ we have $S^{-1}(x_i)\cap S^{-1}(V_i)=\emptyset$ so $S^{-1}(V_i) \subset S^{-1}(V)$ is a strict inclusion, contradicting that $\mathbb{P}^n \times \mathbb{P}^m$ is irreducible.
[ "stackoverflow", "0022951458.txt" ]
Q: Split 4 digit value into 3 integers I'm trying to split a user entered 4 digit value (ex. 0123) into 3 integer values (ex. 0,1,23) and then do some calculations using the individual values. The way that I have it set up here is just for testing purposes to make sure that my math works. They user would enter 0123 and they should be broken up into int variables. (0, 1, and 23) and saved. Then they are put back together in the end after calculations are completed and given back to the user. I can't seem to quite figure out how to split the input into this pattern. Thanks! } A: Here is how I would split it up given the rules from the comments above, public static void main(String[] args) { String[] tests = new String[] { "0123", "9876" }; for (String test : tests) { int a = Integer.parseInt(test.substring(0, 1)); int b = Integer.parseInt(test.substring(1, 2)); int c = Integer.parseInt(test.substring(2)); System.out.printf("%s = a=%d, b=%d, c=%d\n", test, a, b, c); } } Output is (as described) - 0123 = a=0, b=1, c=23 9876 = a=9, b=8, c=76
[ "diy.meta.stackexchange", "0000001352.txt" ]
Q: Should I incorporate information and suggestions posted as comments into my answer? For example, several good comments were made on my answer. In the interest of housekeeping, should I add them to my answer and provide attribution, then flag them for removal, or should I simply leave them as comments? A: Add them to the answer. Comments are meant to be temporary.
[ "physics.stackexchange", "0000513014.txt" ]
Q: Why aren't salt water batteries used to power cars instead of lithium-ion? I know salt water batteries are less efficient than lithium-ion, but water is safer, can be found anywhere, is cheap and 100% ecological. Even if it doesn't last long, you can refill anywhere. Why can't salt water batteries be used to power electric cars? A: Water has one major setback: It is chemically stable only up to a voltage of 1.22 volts. This means that a water cell supplies three times less voltage than a customary lithium ion cell with 3.7 volts, which makes it poorly suited for applications in electric cars. However, water-based batteries, could be interesting for stationary electricity storage applications. Secondly it is not true that water is lighter; Lithium is the least dense of all the metals, it has a density nearly half that of water $0.534 g/cm^3$.
[ "arduino.stackexchange", "0000031022.txt" ]
Q: Error: Expected primary-expression before void We have been working on this "disaster bot" code for days and hours. AFter all of our hard work, Arduino gives us this error code: expected primary-expression before void. Please please please assist we are so desperate to get this to work. Here is our code below. Please. // HEARTBEAT SENSOR (displays heart rate on LCD screen) int sensorPin = A0; // This is the analog sensor pin the backwards S pin is connected to // you can use any of the analog pins, but would need to change this to match double alpha = 0.75; // This code uses a rather cool way of averaging the values, using 75% of the // average of the previous values and 25% of the current value. int period = 20; // This is how long the code delays in milliseconds between readings (20 mSec) int in = 8; int Reset=6; int start=7; int count=0,i=0,k=0,rate=0; // LCD SCREEN #include<LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // BIG SOUND SENSOR int soundDetectedPin = 10; int soundDetectedVal = HIGH; boolean bAlarm = false; unsigned long lastSoundDetectTime; int soundAlarmTime = 500; // PUSH BUTTON AND BUZZER int buzzer = 3; int ledPin = 13; int inPin = 7; int val = 0; #define sing #define NOTE_B0 31 #define NOTE_C1 33 #define NOTE_CS1 35 #define NOTE_D1 37 #define NOTE_DS1 39 #define NOTE_E1 41 #define NOTE_F1 44 #define NOTE_FS1 46 #define NOTE_G1 49 #define NOTE_GS1 52 #define NOTE_A1 55 #define NOTE_AS1 58 #define NOTE_B1 62 #define NOTE_C2 65 #define NOTE_CS2 69 #define NOTE_D2 73 #define NOTE_DS2 78 #define NOTE_E2 82 #define NOTE_F2 87 #define NOTE_FS2 93 #define NOTE_G2 98 #define NOTE_GS2 104 #define NOTE_A2 110 #define NOTE_AS2 117 #define NOTE_B2 123 #define NOTE_C3 131 #define NOTE_CS3 139 #define NOTE_D3 147 #define NOTE_DS3 156 #define NOTE_E3 165 #define NOTE_F3 175 #define NOTE_FS3 185 #define NOTE_G3 196 #define NOTE_GS3 208 #define NOTE_A3 220 #define NOTE_AS3 233 #define NOTE_B3 247 #define NOTE_C4 262 #define NOTE_CS4 277 #define NOTE_D4 294 #define NOTE_DS4 311 #define NOTE_E4 330 #define NOTE_F4 349 #define NOTE_FS4 370 #define NOTE_G4 392 #define NOTE_GS4 415 #define NOTE_A4 440 #define NOTE_AS4 466 #define NOTE_B4 494 #define NOTE_C5 523 #define NOTE_CS5 554 #define NOTE_D5 587 #define NOTE_DS5 622 #define NOTE_E5 659 #define NOTE_F5 698 #define NOTE_FS5 740 #define NOTE_G5 784 #define NOTE_GS5 831 #define NOTE_A5 880 #define NOTE_AS5 932 #define NOTE_B5 988 #define NOTE_C6 1047 #define NOTE_CS6 1109 #define NOTE_D6 1175 #define NOTE_DS6 1245 #define NOTE_E6 1319 #define NOTE_F6 1397 #define NOTE_FS6 1480 #define NOTE_G6 1568 #define NOTE_GS6 1661 #define NOTE_A6 1760 #define NOTE_AS6 1865 #define NOTE_B6 1976 #define NOTE_C7 2093 #define NOTE_CS7 2217 #define NOTE_D7 2349 #define NOTE_DS7 2489 #define NOTE_E7 2637 #define NOTE_F7 2794 #define NOTE_FS7 2960 #define NOTE_G7 3136 #define NOTE_GS7 3322 #define NOTE_A7 3520 #define NOTE_AS7 3729 #define NOTE_B7 3951 #define NOTE_C8 4186 #define NOTE_CS8 4435 #define NOTE_D8 4699 #define NOTE_DS8 4978 #define melodyPin 3 //Hotline Bling Melody int hotlineb_melody[] = { 0, NOTE_D5, NOTE_D5, NOTE_D5, NOTE_F5, NOTE_E5, NOTE_D5, NOTE_C5, NOTE_E5, NOTE_C5, 0, NOTE_F5, NOTE_E5, NOTE_D5, NOTE_C5, NOTE_E5, NOTE_C5, NOTE_A4, NOTE_F5, NOTE_E5, NOTE_D5, NOTE_C5, NOTE_E5, NOTE_C5, 0, NOTE_F5, NOTE_E5, NOTE_D5, NOTE_C5, NOTE_E5, NOTE_C5, NOTE_A4, NOTE_F5, NOTE_C6, NOTE_C6, NOTE_C6, NOTE_A5, NOTE_C6, NOTE_C6, NOTE_D6, 0, NOTE_F5, NOTE_A5, NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5, NOTE_A5, 0, NOTE_C6, NOTE_C6, NOTE_C6, NOTE_A5, NOTE_C6, NOTE_C6, NOTE_D6, 0, NOTE_F5, NOTE_A5, NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5, NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6, NOTE_A5, NOTE_D6, NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5, NOTE_F5, NOTE_C6, NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6, NOTE_A5, NOTE_D6, NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_G5 }; //HotlineBLING tempo int hotlineb_tempo[] = { 12, 12, 12, 12, 12, 12, 12, 12, 6, 2, 3, 12, 12, 12, 12, 3, 3, 3, 12, 12, 12, 12, 6, 2, 3, 12, 12, 12, 12, 3, 3, 4, 12, 12, 12, 12, 12, 12, 12, 2, 3, 12, 12, 12, 12, 12, 12, 2, 3, 12, 12, 12, 12, 12, 12, 3, 3, 12, 12, 12, 12, 12, 12, 2, 12, 12, 12, 12, 12, 12, 12, 12, 1.5, 12, 12, 12, 12, 12, 12, 12, 12, 6, 2, 12, 12, 12, 12, 12, 12, 12, 12, 6, 2, 12, 12, 12, 12, 12, 12, 12, 12, 6, 2.4, 12, 12, 12, 12, 12, 12, 12, 12, 12, 1.5, 12, 12, 12, 12, 12, 12, 12, 12, 6, 2, 12, 12, 12, 12, 12, 12, 12, 12, 6, 2, 12, 12, 12, 12, 12, 12, 12, 12, 8, 24, 2 }; void setup() { { //lcd.createChar(1, heart); lcd.begin(16,2); lcd.print("Heart Beat"); lcd.write(1); lcd.setCursor(0,1); lcd.print("Monitering"); pinMode(in, INPUT); pinMode(Reset, INPUT); pinMode(start, INPUT); digitalWrite(Reset, HIGH); digitalWrite(start, HIGH); delay(1000); lcd.begin(16,2); lcd.print("need to talk?"); delay(1000); lcd.begin(16,2); lcd.print("not yet satisfied with care?"); delay(1000); } // This code runs on startup, it sets ledPin to output so it can blink the LED that is built into the // Arduino (but then never does), and sets the serial port up for fast 115,200 baud communication // of the values (make sure you change your serial monitor to match). Serial.begin (115200); // the baud rate of the serial data { Serial.begin(115200); pinMode (soundDetectedPin, INPUT); } //PUSH BUTTON AND BUZZER { pinMode(buzzer, OUTPUT); pinMode(13, OUTPUT); pinMode(inPin, INPUT); } } void loop() { // HEARTBEAT SENSOR static double oldValue = 0; // used for averaging. static double oldChange = 0; // not currently used int rawValue = analogRead (sensorPin); // This reads in the value from the analog pin. // this is a 10 bit number, and will be between 0 and 1023 // If this value doesn't change, you've connected up // something wrong unsigned long time2,time1; unsigned long time; double value = alpha * oldValue + (1 - alpha) * rawValue; // Calculate an average using 75% of the // previous value and 25% of the new Serial.print (rawValue); // Send out serially the value read in Serial.print (","); // Send a comma Serial.println (value); // Send out the average value and a new line oldValue = value; // Save the average for next iteration delay (period); // Wait 20 mSec if((digitalRead(start))) { k=0; lcd.clear(); lcd.print("Please wait......."); while(k<5) { if(digitalRead(in)) { if(k==0) time1=millis(); k++; while(digitalRead(in)); } } time2=millis(); rate=time2-time1; rate=rate/5; rate=60000/rate; lcd.clear(); lcd.print("Heart Beat Rate:"); lcd.setCursor(0,1); lcd.print(rate); lcd.print(" "); lcd.write(1); k=0; rate=0; } if(!digitalRead(Reset)) { rate=0; lcd.clear(); lcd.print("Heart Beat Rate:"); lcd.setCursor(0,1); lcd.write(1); lcd.print(rate); k=0; } // LCD SCREEN (helpful hotlines message) { lcd.setCursor(0,1); lcd.clear(); lcd.begin(16,2); lcd.print("1-800-273-8255"); delay(1000); lcd.clear(); lcd.begin(16,2); lcd.print("1-877-726-4727"); delay(1000); } // BIG SOUND SENSOR { soundDetectedVal = digitalRead(soundDetectedPin); if (soundDetectedVal == LOW) { lastSoundDetectTime = millis(); if (!bAlarm){ Serial.println("you're doing great :)"); bAlarm = true; } } else { if( (millis()-lastSoundDetectTime) > soundAlarmTime && bAlarm) { Serial.println("keep breathing"); bAlarm = false; } } } // LCD SCREEN (are feeling better/listen to these sick tunes buddy message) { lcd.setCursor(0,1); lcd.clear(); lcd.begin(16,2); lcd.print("if still need comfort"); delay(500); lcd.clear(); lcd.begin(16,2); lcd.print("hold button"); delay(1000); } //PUSH BUTTON AND BUZZER { val = digitalRead(inPin); if (val == HIGH) { digitalWrite(buzzer, LOW); } else { digitalWrite(buzzer, HIGH); } } // BUZZER {{ sing(1); sing(1); sing(2); } int song = 0; void sing(int s) { song = s; if (song == 1) { Serial.println("recognize this?"); int size = sizeof(hotlineb_melody) / sizeof(int); for (int thisNote = 0; thisNote < size; thisNote++) { int noteDuration = 1000 / hotlineb_tempo[thisNote]; buzz(melodyPin, hotlineb_melody[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); buzz(melodyPin, 0, noteDuration); } } } { void buzz(int targetPin, long frequency, long length) { digitalWrite(13, HIGH); long delayValue = 1000000 / frequency / 2; long numCycles = frequency * length / 1000; for (long i - 0; i < numCycles; i++) { digitalWrite(targetPin, HIGH); delayMicroseconds(delayValue); digitalWrite(targetPin, LOW); delayMicroseconds(delayValue); } digitalWrite(13, LOW); } } } } } } A: Here are the problems I found while trying to make your code compile: Opening and closing braces should match Trying to autoformat your code gave me the error: Auto Format Canceled: Too many right curly braces. I had to remove the last two braces for Auto Format to succeed. Functions cannot be nested You should move the declarations of sing() and buzz() out of loop(). You can call them from loop() though. Other random errors #define sing is defining sing as an empty string, and you cannot give a function an empty name the variable song should be either global or local to sing(), not local to loop() to declare and initialize a variable to zero you should write int i = 0, not int i - 0 soundAlarmTime should be unsigned oldChange and time should be removed (they are not used)
[ "stackoverflow", "0046754964.txt" ]
Q: How Create Sidenav from bottom to top Is there anyone who can help me? How to open sidenav from bottom to top. This is the code from left to right. I want to make the code below open sidenav from bottom to top. This code now opens sidenav from left to right. This is my CSS code: .sidenav { height: 100%; width: 0; position: fixed; z-index: 1; top: 0; left: 0; background-color: #111; overflow-x: hidden; transition: 0.5s; padding-top: 60px; text-align:center; } And this is javascript code: function openNav() { document.getElementById("mySidenav").style.width = "100%"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; } Can somebody help me correct the code, I am new. A: You may try this : function openNav() { document.querySelector(".sidenav").style.height = "100vh"; document.querySelector(".sidenav").style.paddingTop = "60px"; } function closeNav() { document.querySelector(".sidenav").style.height = "0"; document.querySelector(".sidenav").style.paddingTop = "0"; } .sidenav { height: 0; width: 100%; position: fixed; z-index: 1; bottom: 0; left: 0; background-color: #111; overflow-x: hidden; transition:height 0.5s; padding-top:0; text-align:center; } button { position:relative; z-index:9999; } <div class="sidenav"></div> <!-- the button used for test --> <button onClick='openNav()'>Open</button> <button onClick='closeNav()'>Close</button>
[ "stackoverflow", "0053330964.txt" ]
Q: Adding the JS/jQuery click functionality for extra elements I've written 4 different click functions for every nav header element. I don't think this is an efficient way to do it. I want to know what logic I can use to get this done in 1 block itself rather than writing the 4 different blocks for 4 nav header. //First Nav Header $(".header-experience").click(function() { $(".sub-nav-inner-container div").show(); if(($(window).innerWidth() >= 993)) { $('.sub-nav-inner-container .slick-list.draggable').css("left","-100px"); $('.sub-nav-inner-container .slick-list.draggable').animate({ left:"0" },{ duration: 300, easing: "linear" }); } if(($(window).innerWidth() < 993)) { $('.sub-nav-inner-container .slick-list.draggable').css("left","50px"); $('.sub-nav-inner-container .slick-list.draggable').animate({ left:"0" },{ duration: 200, easing: "linear" }); } if(($(window).innerWidth() < 476)) { $('.sub-nav-inner-container').css("padding-left","150px"); $('.sub-nav-inner-container').animate({ paddingLeft:"65px" },{ duration: 200, easing: "linear" }); } $(".sub-nav-inner-container").hide(); $(".container-experience").show(); $(".container-experience .sub-nav-inner-container").css("display","flex"); }); //Second Nav Header $(".header-shop").click(function() { $(".sub-nav-inner-container div").show(); if(($(window).innerWidth() >= 993)) { $('.sub-nav-inner-container .slick-list.draggable').css("left","-100px"); $('.sub-nav-inner-container .slick-list.draggable').animate({ left:"0" },{ duration: 300, easing: "linear" }); } if(($(window).innerWidth() < 993)) { $('.sub-nav-inner-container .slick-list.draggable').css("left","50px"); $('.sub-nav-inner-container .slick-list.draggable').animate({ left:"0" },{ duration: 200, easing: "linear" }); } if(($(window).innerWidth() < 476)) { $('.sub-nav-inner-container').css("padding-left","150px"); $('.sub-nav-inner-container').animate({ paddingLeft:"65px" },{ duration: 200, easing: "linear" }); } $(".sub-nav-inner-container").hide(); $(".container-shop").show(); $(".container-shop .sub-nav-inner-container").css("display","flex"); }); //Third Nav Header $(".header-extra-label").click(function() { $(".sub-nav-inner-container div").show(); if(($(window).innerWidth() >= 993)) { $('.sub-nav-inner-container .slick-list.draggable').css("left","-100px"); $('.sub-nav-inner-container .slick-list.draggable').animate({ left:"0" },{ duration: 300, easing: "linear" }); } if(($(window).innerWidth() < 993)) { $('.sub-nav-inner-container .slick-list.draggable').css("left","50px"); $('.sub-nav-inner-container .slick-list.draggable').animate({ left:"0" },{ duration: 200, easing: "linear" }); } if(($(window).innerWidth() < 476)) { $('.sub-nav-inner-container').css("padding-left","150px"); $('.sub-nav-inner-container').animate({ paddingLeft:"65px" },{ duration: 200, easing: "linear" }); } $(".sub-nav-inner-container").hide(); $(".container-extra-label").show(); $(".container-extra-label .sub-nav-inner-container").css("display","flex"); }); //Fourth Nav Header $(".header-extra-equity").click(function() { $(".sub-nav-inner-container div").show(); if(($(window).innerWidth() >= 993)) { $('.sub-nav-inner-container .slick-list.draggable').css("left","-100px"); $('.sub-nav-inner-container .slick-list.draggable').animate({ left:"0" },{ duration: 300, easing: "linear" }); } if(($(window).innerWidth() < 993)) { $('.sub-nav-inner-container .slick-list.draggable').css("left","50px"); $('.sub-nav-inner-container .slick-list.draggable').animate({ left:"0" },{ duration: 200, easing: "linear" }); } if(($(window).innerWidth() < 476)) { $('.sub-nav-inner-container').css("padding-left","150px"); $('.sub-nav-inner-container').animate({ paddingLeft:"65px" },{ duration: 200, easing: "linear" }); } $(".sub-nav-inner-container").hide(); $(".container-extra-equity").show(); $(".container-extra-equity .sub-nav-inner-container").css("display","flex"); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div class="sidebar-sub-nav display-none wrapper"> <div class="slider"></div> <ul class="sub-nav-category nav nav-tabs nav-justified"> <li class="nav-item active"><a class="nav-link" data-toggle="tab"> <span class="nav-header header-shop">Shop</span> </a></li> <li class="nav-item"><a class="nav-link" data-toggle="tab"> <span class="nav-header header-experience">Bars</span> </a></li> <li class="nav-item"><a class="nav-link" data-toggle="tab"> <span class="nav-header header-extra-label">Discover BrewDog</span> </a></li> <li class="nav-item"><a class="nav-link" data-toggle="tab"> <span class="nav-header header-extra-equity">Equity for Punks</span></a></li> </ul> <div class="sub-nav-container"> <!-- SHOP NAV START --> <div class="sub-nav-inner-container container-shop carousel"> <div> <p class="sub-nav-header"><a href="{{store url="beers"}}">Beer</a></p> <div class="sub-nav-contents"> <p><a href="{{store url="beer/new-in.html"}}">New In</a></p> <p><a href="{{store url="beer/headliners.html"}}">Headliners</a></p> <p><a href="{{store url="beer/seasonal.html"}}">Seasonal</a></p> <p><a href="{{store url="beer/year-round.html"}}">Year round</a></p> <p><a href="{{store url="beer/high-octane.html"}}">High Octane</a></p> <p><a href="{{store url="beer/overworks.html"}}">OverWorks</a></p> <p><a href="{{store url="beer/abstrakt.html"}}">Abstrakt</a></p> <p><a href="{{store url="beer/guest.html"}}">Guest</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="{{store url="merch.html"}}">Merch</a></p> <div class="sub-nav-contents"> <p><a href="{{store url="merch/clothing.html"}}">Clothing</a></p> <p><a href="{{store url="merch/chain-gang.html"}}">Chain Gang</a></p> <p><a href="{{store url="merch/barware-glasses.html"}}">Barware &amp; Glasses</a></p> <p><a href="#">Accessories</a></p> <p><a href="{{store url="merch/sale.html"}}">Sale</a></p> <p><a href="{{store url="merch/gifts.html"}}">Gifts</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="spirits.html">Spirits</a></p> <div class="sub-nav-contents"> <p><a href="{{store url="gin.html"}}">Gin</a></p> <p><a href="{{store url="vodka.html"}}">Vodka</a></p> <p><a href="{{store url="whisky.html"}}">Whisky</a></p> <p><a href="{{store url="mixers.html"}}">Mixers</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="#">Subscriptions</a></p> <div class="sub-nav-contents"> <p><a href="{{store url="bottlebox"}}">Bottle Box</a></p> <p><a href="{{store url="fanzine"}}fanzine/">Fanzine</a></p> <p><a href="#">Build and buy</a></p> </div> </div> </div> <!-- SHOP NAV END --> <!-- BARS NAV START --> <div class="sub-nav-inner-container container-experience carousel"> <div> <p class="sub-nav-header"><a href="{{store url="bars"}}">Bars</a></p> <div class="sub-nav-contents"> <p><a href="{{store url="bars/uk"}}">UK</a></p> <p><a href="{{store url="bars/global"}}">International</a></p> <p><a href="{{store url="bars/us"}}">USA</a></p> <p><a href="{{store url="bars/coming-soon"}}">Coming Soon</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="#">Bar Experience</a></p> <div class="sub-nav-contents"> <p><a href="{{store url="lowdown/chain-gang"}}">Chain Gang</a></p> <p><a href="{{store url="bars/uk/dogtap"}}">Dog Tap</a></p> <p><a href="{{store url="bars/beer-visa"}}">Beer Visa</a></p> <p><a href="#">EFP Franchise Opportunities</a></p> <p><a href="{{store url="bars/festive"}}">Festive</a></p> </div> </div> </div> <!-- BARS NAV END --> <!-- DISCOVER NAV START --> <div class="sub-nav-inner-container container-extra-label carousel"> <div> <p class="sub-nav-header"><a href="#">About</a></p> <div class="sub-nav-contents"> <p><a href="{{store url="lowdown/brewdog-believe"}}">BrewDog Believe</a></p> <p><a href="{{store url="about/culture/the-charter"}}">The Charter</a></p> <p><a href="{{store url="about/culture/culture-check"}}">Culture</a></p> <p><a href="{{store url="about/history"}}">History</a></p> <p><a href="{{store url="about/brewdogfoundation"}}">BrewDog Foundation</a></p> <p><a href="https://jobs.brewdog.com">Jobs</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="{{store url="lowdown/blog"}}">Blog</a></p> <div class="sub-nav-contents"> <p><a href="{{store url=""}}">Brewdog News</a></p> <p><a href="{{store url=""}}">Business for Punks</a></p> <p><a href="{{store url=""}}">Video Blog</a></p> <p><a href="{{store url=""}}">Beer Rocks</a></p> <p><a href="{{store url=""}}">Brewery Updates</a></p> <p><a href="{{store url=""}}">Caption Competition</a></p> <p><a href="{{store url=""}}">Dog's Blogs</a></p> <p><a href="{{store url=""}}">BrewDog Bars</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="{{store url="brewery"}}">Brewery</a></p> <div class="sub-nav-contents"> <p><a href="{{store url="brewery/ellon-brewery"}}">Beer Making Process</a></p> <p><a href="#">Ellon</a></p> <p><a href="{{store url="brewery/overworks-brewery"}}">OverWorks</a></p> <p><a href="{{store url="brewery/usa-brewery"}}">Columbus</a></p> <p><a href="{{store url="brewery/brisbane-brewery"}}">Brisbane</a></p> <p><a href="#">DIY Dog</a></p> <p><a href="{{store url="dog-house"}}">DogHouse</a></p> <p><a href="#">Quality Labs</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="#">Events</a></p> <div class="sub-nav-contents"> <p><a href="{{store url="events/collabfest"}}">Collabfest</a></p> <p><a href="{{store url="events/metro-mayhem"}}">Metro Mayhem</a></p> <p><a href="{{store url="events/agm2018"}}">AGM</a></p> </div> </div> </div> <!-- DISCOVER NAV END --> <!-- EFP NAV START --> <div class="sub-nav-inner-container container-extra-equity carousel"> <div> <p class="sub-nav-header">Equity For Punks</p> <div class="sub-nav-contents"> <p><a href="{{store url="lowdown/brewdog-believe"}}">EFP UK</a></p> <p><a href="{{store url="about/culture/the-charter"}}">EFP USA</a></p> <p><a href="{{store url="about/culture/culture-check"}}">EFP Australia</a></p> <p><a href="{{store url="about/history"}}">EFP Re-Brews</a></p> <p><a href="{{store url="about/brewdogfoundation"}}">Blue Print</a></p> </div> </div> </div> <!-- EFP NAV END --> </div> </div> Code is same for all 4 nav header except the first click function line and the last 2 line codes A: Change first line to $(".nav-header").click(function() {. For last two lines. Replace it with following snippet. I've fetched index of clicked header and displayed .sub-nav-inner-container of same index. var index = $(".nav-header").index(this); $(".sub-nav-inner-container:nth(" + index + ")").show(); $(".sub-nav-inner-container:nth(" + index + ")").find(".sub-nav-inner-container").css("display", "flex"); // All Nav Header $(".nav-header").click(function() { $(".sub-nav-inner-container div").show(); if (($(window).innerWidth() >= 993)) { $('.sub-nav-inner-container .slick-list.draggable').css("left", "-100px"); $('.sub-nav-inner-container .slick-list.draggable').animate({ left: "0" }, { duration: 300, easing: "linear" }); } if (($(window).innerWidth() < 993)) { $('.sub-nav-inner-container .slick-list.draggable').css("left", "50px"); $('.sub-nav-inner-container .slick-list.draggable').animate({ left: "0" }, { duration: 200, easing: "linear" }); } if (($(window).innerWidth() < 476)) { $('.sub-nav-inner-container').css("padding-left", "150px"); $('.sub-nav-inner-container').animate({ paddingLeft: "65px" }, { duration: 200, easing: "linear" }); } $(".sub-nav-inner-container").hide(); var index = $(".nav-header").index(this); $(".sub-nav-inner-container:nth(" + index + ")").show(); $(".sub-nav-inner-container:nth(" + index + ")").find(".sub-nav-inner-container").css("display", "flex"); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div class="sidebar-sub-nav display-none wrapper"> <div class="slider"></div> <ul class="sub-nav-category nav nav-tabs nav-justified"> <li class="nav-item active"> <a class="nav-link" data-toggle="tab"> <span class="nav-header header-shop">Shop</span> </a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab"> <span class="nav-header header-experience">Bars</span> </a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab"> <span class="nav-header header-extra-label">Discover BrewDog</span> </a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab"> <span class="nav-header header-extra-equity">Equity for Punks</span></a> </li> </ul> <div class="sub-nav-container"> <!-- SHOP NAV START --> <div class="sub-nav-inner-container container-shop carousel"> <div> <p class="sub-nav-header"><a href="{{store url=" beers "}}">Beer</a></p> <div class="sub-nav-contents"> <p><a href="{{store url=" beer/new-in.html "}}">New In</a></p> <p><a href="{{store url=" beer/headliners.html "}}">Headliners</a></p> <p><a href="{{store url=" beer/seasonal.html "}}">Seasonal</a></p> <p><a href="{{store url=" beer/year-round.html "}}">Year round</a></p> <p><a href="{{store url=" beer/high-octane.html "}}">High Octane</a></p> <p><a href="{{store url=" beer/overworks.html "}}">OverWorks</a></p> <p><a href="{{store url=" beer/abstrakt.html "}}">Abstrakt</a></p> <p><a href="{{store url=" beer/guest.html "}}">Guest</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="{{store url=" merch.html "}}">Merch</a></p> <div class="sub-nav-contents"> <p><a href="{{store url=" merch/clothing.html "}}">Clothing</a></p> <p><a href="{{store url=" merch/chain-gang.html "}}">Chain Gang</a></p> <p><a href="{{store url=" merch/barware-glasses.html "}}">Barware &amp; Glasses</a></p> <p><a href="#">Accessories</a></p> <p><a href="{{store url=" merch/sale.html "}}">Sale</a></p> <p><a href="{{store url=" merch/gifts.html "}}">Gifts</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="spirits.html">Spirits</a></p> <div class="sub-nav-contents"> <p><a href="{{store url=" gin.html "}}">Gin</a></p> <p><a href="{{store url=" vodka.html "}}">Vodka</a></p> <p><a href="{{store url=" whisky.html "}}">Whisky</a></p> <p><a href="{{store url=" mixers.html "}}">Mixers</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="#">Subscriptions</a></p> <div class="sub-nav-contents"> <p><a href="{{store url=" bottlebox "}}">Bottle Box</a></p> <p><a href="{{store url=" fanzine "}}fanzine/">Fanzine</a></p> <p><a href="#">Build and buy</a></p> </div> </div> </div> <!-- SHOP NAV END --> <!-- BARS NAV START --> <div class="sub-nav-inner-container container-experience carousel"> <div> <p class="sub-nav-header"><a href="{{store url=" bars "}}">Bars</a></p> <div class="sub-nav-contents"> <p><a href="{{store url=" bars/uk "}}">UK</a></p> <p><a href="{{store url=" bars/global "}}">International</a></p> <p><a href="{{store url=" bars/us "}}">USA</a></p> <p><a href="{{store url=" bars/coming-soon "}}">Coming Soon</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="#">Bar Experience</a></p> <div class="sub-nav-contents"> <p><a href="{{store url=" lowdown/chain-gang "}}">Chain Gang</a></p> <p><a href="{{store url=" bars/uk/dogtap "}}">Dog Tap</a></p> <p><a href="{{store url=" bars/beer-visa "}}">Beer Visa</a></p> <p><a href="#">EFP Franchise Opportunities</a></p> <p><a href="{{store url=" bars/festive "}}">Festive</a></p> </div> </div> </div> <!-- BARS NAV END --> <!-- DISCOVER NAV START --> <div class="sub-nav-inner-container container-extra-label carousel"> <div> <p class="sub-nav-header"><a href="#">About</a></p> <div class="sub-nav-contents"> <p><a href="{{store url=" lowdown/brewdog-believe "}}">BrewDog Believe</a></p> <p><a href="{{store url=" about/culture/the-charter "}}">The Charter</a></p> <p><a href="{{store url=" about/culture/culture-check "}}">Culture</a></p> <p><a href="{{store url=" about/history "}}">History</a></p> <p><a href="{{store url=" about/brewdogfoundation "}}">BrewDog Foundation</a></p> <p><a href="https://jobs.brewdog.com">Jobs</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="{{store url=" lowdown/blog "}}">Blog</a></p> <div class="sub-nav-contents"> <p><a href="{{store url=" "}}">Brewdog News</a></p> <p><a href="{{store url=" "}}">Business for Punks</a></p> <p><a href="{{store url=" "}}">Video Blog</a></p> <p><a href="{{store url=" "}}">Beer Rocks</a></p> <p><a href="{{store url=" "}}">Brewery Updates</a></p> <p><a href="{{store url=" "}}">Caption Competition</a></p> <p><a href="{{store url=" "}}">Dog's Blogs</a></p> <p><a href="{{store url=" "}}">BrewDog Bars</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="{{store url=" brewery "}}">Brewery</a></p> <div class="sub-nav-contents"> <p><a href="{{store url=" brewery/ellon-brewery "}}">Beer Making Process</a></p> <p><a href="#">Ellon</a></p> <p><a href="{{store url=" brewery/overworks-brewery "}}">OverWorks</a></p> <p><a href="{{store url=" brewery/usa-brewery "}}">Columbus</a></p> <p><a href="{{store url=" brewery/brisbane-brewery "}}">Brisbane</a></p> <p><a href="#">DIY Dog</a></p> <p><a href="{{store url=" dog-house "}}">DogHouse</a></p> <p><a href="#">Quality Labs</a></p> </div> </div> <div> <p class="sub-nav-header"><a href="#">Events</a></p> <div class="sub-nav-contents"> <p><a href="{{store url=" events/collabfest "}}">Collabfest</a></p> <p><a href="{{store url=" events/metro-mayhem "}}">Metro Mayhem</a></p> <p><a href="{{store url=" events/agm2018 "}}">AGM</a></p> </div> </div> </div> <!-- DISCOVER NAV END --> <!-- EFP NAV START --> <div class="sub-nav-inner-container container-extra-equity carousel"> <div> <p class="sub-nav-header">Equity For Punks</p> <div class="sub-nav-contents"> <p><a href="{{store url=" lowdown/brewdog-believe "}}">EFP UK</a></p> <p><a href="{{store url=" about/culture/the-charter "}}">EFP USA</a></p> <p><a href="{{store url=" about/culture/culture-check "}}">EFP Australia</a></p> <p><a href="{{store url=" about/history "}}">EFP Re-Brews</a></p> <p><a href="{{store url=" about/brewdogfoundation "}}">Blue Print</a></p> </div> </div> </div> <!-- EFP NAV END --> </div> </div>
[ "stackoverflow", "0019526177.txt" ]
Q: How to COUNT from another table in Access Database Write a query that displays for each customer their customer code, name, total, balance(from Customer table), and their total purchases (from Invoice). This column can be called Total_purchases. Alright, so yes this is a lab question, however I have spent a significant amount of time trying to figure out how this works. CUSTOMER table has a foreign key in INVOCE (CUS_CODE). INVOICE keeps track by INV_NUMBER a customer can be listed in that table more then once if they have had several transactions. I've tried a number of things my latest thing is: SELECT CUSTOMER.CUS_CODE, CUSOMTER.CUS_FNAME + " " + CUSTOMER.CUS_LNAME as NAME, CUSTOMER.CUS_BALANCE FROM (SELECT COUNT(*) as total_purchases FROM INVOICE WHERE CUSTOMER.CUS_CODE = INVOICE.CUS_CODE); However, it asks for a Parameter Value for each thing. Here is the tables: **CUSTOMER** CUS_CODE CUS_FNAME CUS_LNAME CUS_BALANCE **INVOICE** INV_NUMBER CUS_CODE INV_DATE Some help in understanding how to select something for another table and count it would be extremely helpful. I tried just having two SELECT, but then I get the operator error on the FROM clause. I've tried to make this post as detailed as possible if any information seems missing or incomplete please do not hesitate to call me out in comments. Thank You A: SELECT CUSTOMER.CUS_CODE, CUSOMTER.CUS_FNAME + " " + CUSTOMER.CUS_LNAME as NAME, CUSTOMER.CUS_BALANCE, ( SELECT COUNT(INVOICE.CUS_CODE) FROM INVOICE WHERE (CUSTOMER.CUS_CODE = INVOICE.CUS_CODE) ) AS Total_purchases FROM CUSTOMER This uses what is known as a subquery. In the WHERE clause in the subquery note CUSTOMER.CUS_CODE = INVOICE.CUS_CODE. This is where the invoice table is mapped to the customers table. Hence, the subquery uses the outer query CUSTOMER.CUS_CODE A: there are a couple of approaches you could take Just join the two table and do a count on the invoice table is one SELECT CUSTOMER.CUS_CODE, CUSOMTER.CUS_FNAME + " " + CUSTOMER.CUS_LNAME as NAME, CUSTOMER.CUS_BALANCE , COUNT (INVOICE.CUS_CODE) FROM CUSTOMER INNER JOIN INVOICE ON CUSTOMER.CUS_CODE = INVOICE.CUS_CODE GROUP BY CUSTOMER.CUS_CODE, CUSOMTER.CUS_FNAME + " " + CUSTOMER.CUS_LNAME, CUSTOMER.CUS_BALANCE Another way to go if you don't want to do the group by on the customer fields is to create an inline view in the from clause and join to that SELECT CUSTOMER.CUS_CODE, CUSOMTER.CUS_FNAME + " " + CUSTOMER.CUS_LNAME as NAME, CUSTOMER.CUS_BALANCE , purchasecount.total_purchases FROM CUSTOMER INNER JOIN (SELECT COUNT(*) as total_purchases , INVOICE.CUS_CODE) FROM INVOICE GROUP BY INVOICE.CUS_CODE)) purchasecount ON CUSTOMER.CUS_CODE = purchasecount.CUS_CODE ; Another option is to create a query and then use that in the from. The other option is Jack's answer uses an inline view inside the select.
[ "stackoverflow", "0058479275.txt" ]
Q: Is there a way to memorize a subSequence into a variable? I'm making a program that should ignore ( and ) in words (without the use of RegExp), and through the method I created, I want my variable x to memorize the new String. How can I access subSequence in such way or circumvent my issue through another method that doesn't include the use of RegExp? public int removeParentheses(char[] str) { // To keep track of '(' and ')' characters count int count = 0; for (int i = 0; i < str.length; i++) if (str[i] != '(' && str[i] != ')') str[count++] = str[i]; return count; } public String foo(String input) { for (String index : input.split(" ")) { char[] charArray = index.toCharArray(); int k = removeParentheses(charArray); String x = String.valueOf(charArray).subSequence(0, k); // that's what i want to do. it doesn't work. System.out.println(String.valueOf(charArray).subSequence(0, k)); // this is the only way i can make it work, but it doesn't suffice my needs } } The current output is error: incompatible types: CharSequence cannot be converted to String String x = String.valueOf(charArray).subSequence(0, k); ^ 1 error I expect the output of boo) to be boo in my x variable, not just on-screen through the System.out.println method. A: You said this is "what i want to do. it doesn't work.": String x = String.valueOf(charArray).subSequence(0, k); The return value of subSequence() is a CharSequence which is not a String. It makes sense that it wouldn't work. Since you are starting from an array of characters – char [] – you could use Arrays.copyOfRange() to create a new array of some smaller subset of charArray, like this: char[] copy = Arrays.copyOfRange(charArray, 0, k); From there, you could construct a new String – new String(copy) – or possibly just use that new character array directly.
[ "stackoverflow", "0020830102.txt" ]
Q: Why is this 'if' statement failing? I am trying to determine if I have a duplicate record in CoreData using MagicalRecord. To do that, I am comparing the updated data with the first existing record: This is the code I am using to do the search: // set up predicate to find single appointment if(selectedApptKey.length > 0) { NSPredicate *predicate = ([NSPredicate predicateWithFormat: @"((aApptKey == %@) && (aStartTime == %@) && (aEndTime == %@) && (aServiceTech == %@))", selectedApptKey, tStartDate, tEndDate, tStaff]); NSLog(@"\n\nselectedApptKey: %@\ntStartDate: %@\ntEndDate: %@\ntStaff: %@",selectedApptKey, tStartDate, tEndDate, tStaff); ai = [AppointmentInfo MR_findFirstWithPredicate:predicate inContext:localContext]; if((ai.aApptKey == selectedApptKey) && (ai.aStartTime == tStartDate) && (ai.aEndTime == tEndDate) && (ai.aServiceTech == tStaff)) { updateFlag = YES; } } This is the predicate data I am using to search for an existing record: selectedApptKey: RolfMarsh3911 tStartDate: 2013-12-29 20:15:00 +0000 tEndDate: 2013-12-29 22:15:00 +0000 tStaff: Kellie This is the resulting record as obtained from the above code: Printing description of ai: <NSManagedObject: 0xb705430> (entity: AppointmentInfo; id: 0xb7bca00 <x-coredata://649CD00C-3C88-4447-AA2B-60B792E3B25F/AppointmentInfo/p22> ; data: { aApptKey = RolfMarsh3911; aEndTime = "2013-12-29 22:15:00 +0000"; aImage = nil; aNotes = ""; aPosH = 200; aPosW = 214; aPosX = 0; aPosY = 231; aServiceTech = Kellie; aServices = ""; aStartTime = "2013-12-29 20:15:00 +0000"; client = nil; }) As you can see, the record and search data are exact. Qustion is: why is the if statement failing (the updateFlag is not being set to YES)? A: You need to use isEqualToString: instead of ==, since you want to compare the actual object values, not the pointers. Assuming these are all strings. If you have some date objects use isEqualToDate:. == always compares the pointers, which in this case are not equal, since they are pointing to different objects.
[ "raspberrypi.stackexchange", "0000074651.txt" ]
Q: function button.is_pressed from gpiozero do not work Im working on a university project with raspberry and gpiozero. I need to manage the button response to take diferent actions. The problem is that de function button.is_pressed its always true (even if nobody press the button). I tryed to read again and again the oficial gpiozero documentation but its the same as i type on my script. The only thing I can imagine is that for some reason the button have a minimum voltage that python interpreter as a True in the is_pressed function. import RPi.GPIO as GPIO import random from time import sleep from gpiozero import LED from gpiozero import Button buttonRed = Button(13) red = LED(20) while True: if buttonRed.is_pressed: sleep(.3) print('button pressed') else: print('nobody pressed') this is the output: %Run test1.py button pressed button pressed button pressed button pressed button pressed button pressed button pressed button pressed Please if anybody have an idea of what is happening i would be glad to know about it. Regards !! A: I can do this: import RPi.GPIO as GPIO import random from time import sleep from gpiozero import LED from gpiozero import Button ## I forgot put this in the befor script !!! GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) buttonRed = Button(13) buttonGreen = Button(6) buttonBlue = Button(5) buttonYellow = Button(22) red = LED(20) green = LED(12) blue = LED(25) yellow = LED(24) while True: inputValue1 = GPIO.input(13) if (inputValue == True): <<----(if buttonRed.is_pressed:) print('button pressed') red.on() sleep(.3) red.off() else: print('nobody pressed') And the red (are using gpio LED and the BCM pin numbered) and work perfectly.The red led y have on my raspi conected to a protoboard start on and off as well i press boton. Insted of that, the buttonRed.is_pressed do not work with the same pin numbered, so i fixed by using something more basic "inputValue1 = GPIO.input(13)", but i do not want used it. If a have imported gpiozero library its just for using all the functions !!! Finally, i forgot to mention that i' ve worked with a raspberry PI 2 so the pins number are right. Regards !!!
[ "stackoverflow", "0001941910.txt" ]
Q: How does the hashlife alg go on forever in Golly? In hashlife the field is typically treated as a theoretically infinite grid, with the pattern in question centered near the origin. A quadtree is used to represent the field. Given a square of 2^(2k) cells, 2k on a side, at the kth level of the tree, the hash table stores the 2^(k-1) by 2^(k-1) square of cells in the center, 2^(k-2) generations in the future. For example, for a 4x4 square it stores the 2x2 center, 1 generation forward; and for an 8x8 square it stores the 4x4 center, 2 generations forward. So given a 8x8 initial configuration we get a 4x4 square 1 generation forward centered w.r.t. the 8x8 square and a 2x2 square 2 generations forward (1 generation forward w.r.t the 4x4 square) centered w.r.t the 8x8 square. With every new generation our view of the grid reduces, in-turn we get the next state of the automata. We canot go any further after getting the inner most 2x2 square 2^(k-2) generations forward. So how does the hashlife in Golly go on forever? Also its view of the field never seems to reduce. It seems to show the state of the whole automata after 2^(k-2) generations. More so given a starting configuration which expands with time, the view of the algorithm seems to increase. The view of the grid zooms out to show the expanding automata? A: There's a good article on Dr. Dobb's which goes into detail about how HashLife works. The basic answer is that you don't merely run the algorithm on the existing nodes, you also use new shifted nodes to get the next generation. A: To be clear (because your ^ symbols were missing), you are asking: Given a square of 2^(2k) cells, 2^k on a side, at the kth level of the tree, the hash table stores the 2^(k-1)-by-2^(k-1) square of cells in the center, 2^(k-2) generations in the future. [...] So given a 8x8 initial configuration [...] With every new generation our view of the grid reduces, in-turn we get the next state of the automata. We canot go any further after getting the inner most 2x2 square 2^k-2 generations forward. So how does the hashlife in Golly go on forever? Also its view of the field never seems to reduce. Instead of starting with your 8x8 pattern, imagine instead that you start with a bigger pattern that happens to contain your 8x8 pattern inside it. For example, you could start with a 16x16 pattern that has your 8x8 pattern in the center, and a 4-row margin of blank cells all around the edges. Such a pattern is easy to construct, by assembling blank 4x4 nodes with the 4x4 subnodes of your 8x8 start pattern. Given such a 16x16 pattern, the HashLife algorithm can give you an 8x8 answer, 4 generations in the future. You want more? Okay, start with a 32x32 pattern that contains mostly blank space, with the 8x8 pattern in the center. With this you can get a 16x16 answer that is 8 generations into the future. What if your pattern contains moving objects that move fast enough that they go outside that 16x16 area after 8 generations? Simple -- start with a 64x64 start pattern, but instead of trying to run it for a whole 16 generations, just run it for 8 generations. In general, all cases of arbitrarily large, possibly expanding patterns, over arbitrarily long periods of time, can be handled (and in fact are handled in Golly) by adding as much blank space as needed around the outside of the pattern.
[ "stackoverflow", "0025086559.txt" ]
Q: WCF Custom Class Arguments I have a WCF method which takes an argument that is a custom class, say, void MyWCFMethod(MyCustomClass MethodArgument) In the above, MyCustomClass has a number of constructor overloads. The service has a reference to the class but not the client. I want to allow the client to use the other overloads but the default constructor is the only one that seems to be allowed. Is there a way to do this? A: You can certainly do this, but I think it is important to know why the Data Transfer Objects (DTOs) do not expose logic over the service reference. The WSDL\XSD metadata that is used in order to generate the client proxy to access the WCF Service only describes the web service by the operations exposed and the datatypes exchanged. Specifically, XSD only describes the structure of your DTOs and not the logic - that is why there is only the default constructor and public properties/fields available on the client proxy. So the solution is to put all of your custom classes exchanged between the client and service in a separate shared library. This way both sides of the wire have access to the additional logic (like your parameterized constructors) that you could not obtain via WSDL\XSD.
[ "stackoverflow", "0000929350.txt" ]
Q: How to make a Java PlugIn? I need to make my Java program as a PlugIn to OME - an Image processing web based s/w having Java API www.openmicroscopy A: OmeroJava is the appropriate API for the latest version of OME (OMERO 4.2), if you are writing a client. If you would like to embed your code inside of Insight (the OMERO Java client), then you should start with How to write a client. Other links to OME-Java libraries are for a legacy version and should not be used.
[ "stackoverflow", "0042432359.txt" ]
Q: Bitwise and shift operands to clear a chosen hexadecimal number I have been trying for a while now (and cant seem to succeed) to write a program in C++ that takes in a value (in hex) and converts any of the numbers within that number to zero. The user chooses which number starting from the left (LSB). I would like to be able to accomplish this task by only using bitwise functions and the shift operand. #include "stdafx.h" #include <iostream> using namespace std; int zero(int, int); int main() { int hex_num; int byte_num; cout << "Enter a hexadecimal number please: " << endl; cin >> hex >> hex_num; cout << "Which byte would you like to zero: " << endl; cin >> byte_num; cout << hex << zero(hex_num, byte_num) << endl; system("pause"); return 0; } int zero(int hex_num, int byte_num) { int b; int mask = 0x0001; b = hex_num & ~(mask << byte_num); return b; } A: The problems are indeed in the zero() function. I don't want to give you the working code, so here are some inputs that will hopefully help you (if not, just ask): Like in the comments already said, a byte has not only one bit. If you want to set one whole byte to zero you need to set 8 bits to zero (hint: look at your mask) Bit shifting only shifts for one single bit NOT one byte (or 8 bits). So (0b0011 << 1) == 0b0110 will only shift for one bit. Just for the looks: b is unnecessary. You can use return hex_num & ~(mask << byte_num);
[ "christianity.stackexchange", "0000007744.txt" ]
Q: Has the matter of salvation - whether it is by works or by faith alone - ever been considered on any councils of the Catholic and Orthodox churches? Prior to Luther's Reformation, has the matter of salvation - whether it is by works or by faith alone - ever been considered on any councils of the Catholic and Orthodox churches? A: The first big controversy on this topic emerged with the teachings of Pelagius. His doctrine (about salvation from deeds and about Adam and Christ only "giving example") were condemned on local councils of Diopolis and Carthage and on the Ecumenical Council of Ephesus. Search the web for the term 'pelagianism' to learn more.
[ "stackoverflow", "0045474513.txt" ]
Q: How to show ratings from web service in the ratings bar I am using JSON web service and I want to show the ratings which are coming from the web service, in the ratings bar. But I have no idea how to deal with this. I am only getting examples for the hard coded ratings. Help would be appreciated. Thanks in advance. A: You must be getting the rating from web service in the String format, so for displaying the Rating in the RatingBar you need to convert it into the Float data type Float ratingFromServer = Float.valueOf(mResponse.getRating());// this is the rating you are getting from server and for setting the Rating in the RatingBar you need to add the below code mRatingBar.setRating(ratingFromServer);//setting the rating in ratingBar Try this and do let me know if this helped you.
[ "unix.stackexchange", "0000003380.txt" ]
Q: Rosetta Stone for Linux Distributions? Is there is something like a Rosetta Stone for the different Linux Distributions? Perhaps a site where you can look up a commands, configuration files or problem solutions for a specific task organized as translations of ones of another distribution (you know well). For example you know Debian based distributions well and you want to know the Fedora equivalent to dpkg -S /bin/bar or dpkg --get-selections > foo dpkg --set-selections < foo or apt-cache search foobar --names-only etc. There is a Rosetta Stone for different Unices, but it is not that detailed and does not really differentiates between different Distributions. A: I think the service is called http://unix.stackexchange.com.
[ "stackoverflow", "0021853509.txt" ]
Q: Quadratic Complex roots solver Cannot seem to make the console print out the complex roots correctly. If quad4ac < 0 Then Dim quad4acComplex As Long = quad4ac * -1 Dim quadiComplex As Long = -1 Dim quadrComplex As Long Console.WriteLine(vbNewLine & "Your Roots Are Complexed!" & vbNewLine) quadrComplex = (-quadCoB / (2 * quadCoA) & "+" & (quad4ac * -1) ^ 0.5 / (2 * quadCoA)) Console.WriteLine(quadrComplex) Seems to be causing the console to crash. A: You are trying to assign a string value to a long value and then print the long value. I don't really know what you are trying to do. In case you want to print out the calculated value try: quadrComplex = CType((-quadCoB / (2 * quadCoA) + (quad4ac * -1) ^ 0.5 / (2 * quadCoA)), Long) Console.Writeline(quadrComplex.Tostring) In case you want to print out the expression try Dim quadrComplex as String quadrComplex = "(-" & quadCoB.Tostring & " / (2 * " & quadCoA.ToString & ") + (" & quad4ac.ToString & " * -1) ^ 0.5 / (2 * " & quadCoA.ToString & "))" Console.Writeline(quadrComplex) You should consider enabling Option Strict in your program. That way you are forced by the compiler to use the correct type conversions yourself. This avoids many many errors.
[ "stackoverflow", "0032653367.txt" ]
Q: Command /bin/sh failed with exit code 23 I tried to update an app from Swift 1.2 to iOS 9.0, Xcode 7 and Swift 2.0 - but I have some problems with my pods when I try to compile the app. I get the following error: sent 29 bytes received 20 bytes 98.00 bytes/sec total size is 0 speedup is 0.00 rsync error: some files could not be transferred (code 23) at /SourceCache/rsync/rsync-45/rsync/main.c(992) [sender=2.6.9] Command /bin/sh failed with exit code 23 Already checked for some solutions, but nothing worked for me: Already tried: deleted all pods, and installed them again updated cocoapods (to a beta version) with sudo gem update cocoapods --pre removed cocoapods and installed again tried with "use_frameworks!" for all pods, and without But still the same error. Any ideas? A: I resolved the same issue, I removed "Build" folder once in my project. Same issue: upgraded to swift 2, and cocoapods -.38.2 now getting build error Command /bin/sh failed with exit code 23 But I can't use "Clean Build Folder", so I removed "Build" folder in my Mac Finder.
[ "codereview.stackexchange", "0000093770.txt" ]
Q: Changing look and feel for all current frames I am using JGoodies Looks to change the look and feel of the application I'm currently working on. I've just created a JMenu with some different themes options for the user to choose. The thing is, I want to make sure the changes affect the program instantly, on all current windows, so I did this: @Override public void doActionPerformed(ActionEvent event) { PlasticLookAndFeel lookAndFeel = new PlasticXPLookAndFeel(); lookAndFeel.setPlasticTheme(new SkyBlue()); try { UIManager.setLookAndFeel(lookAndFeel); for(Frame f: Frame.getFrames()) { SwingUtilities.updateComponentTreeUI(f); } } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } } It works perfectly, like magic. But I don't know if it is a good practice or not, or if there is a better or easier (if possible) way. I didn't even know that Frame had that method. I've just tried (thanks to IntelliJ magic code completion) and it worked so easy on the first try. So maybe that's why I'm concerned about it. Also, what is the difference between the code above and this one (as they appear to work the exact same way): for(Window window : JFrame.getWindows()) { SwingUtilities.updateComponentTreeUI(window); } I mean, when and why should I be using Frame over JFrame, Frame over Window, or vice versa? A: Java GUIs: Swing & AWT In standard Java there are two ways to make GUIs: Swing and AWT. To be short, Swing is platform-independent and AWT is platform-dependent. Typically you pick either AWT or Swing and stick to it. I believe Swing is the more popular choice today as it is easier to work with. You can tell Swing code from AWT code by the fact that Swing component classes are prefixed with a J. For example Frame is AWT and JFrame is the Swing equivalent. The Swing components inherit from the AWT components so a JFrame is a Frame. Windows and Frames Now the difference between Window and Frame (and JWindow and JFrame respectively) is that a Window is a plain window without any decorations; no borders, no title bar, no window management buttons. A Frame is a Window with all these decorations. And I put emphasis on is a in the above as Frame actually inherits Window. So the inheritance tree looks like this: lang.Object | awt.Component | awt.Container | awt.Window | +--------+-------+ | | swing.JWindow awt.Frame | swing.JFrame To answer your question about which of the methods is better. Note that getWindows() is defined in Window and inherited by JWindow, Frame and JFrame. Calling getWindows() will get all windows, even owner-less dialogues and system windows associated with the application, regardless of if they have decorations or not. On the other hand getFrames() is defined in Frame so calling getFrames() will get all windows with decorations (frames). If your application doesn't have any frame-less windows, the two pieces of code you posted will be equivalent. The Code Your code is likely fine as it is wither either approach as plain Windows are kind of rare and often transient. The approach you're using is the standard one. If you want to be absolutely sure you get every window there is and be picky about it, this is how I would write it: for(Window window: Window.getWindows()) { SwingUtilities.updateComponentTreeUI(window); } For your reference, see the Java Docs for JWindow and JFrame and their super classes.
[ "stackoverflow", "0016834983.txt" ]
Q: I am trying to config my own map server with mapnik mod_tile and apache no tiles are generated and i get the following errors I started this renderd -f -c /usr/local/etc/renderd.conf got this renderd[1620]: Rendering daemon started renderd[1620]: Initiating reqyest_queue iniparser: syntax error in /usr/local/etc/renderd.conf (7): -> ;[renderd01] iniparser: syntax error in /usr/local/etc/renderd.conf (14): -> ;[renderd02] iniparser: syntax error in /usr/local/etc/renderd.conf (33): -> ;** config options used by mod_tile, but not renderd ** iniparser: syntax error in /usr/local/etc/renderd.conf (42): -> ;[style2] iniparser: syntax error in /usr/local/etc/renderd.conf (49): -> ;** config options used by mod_tile, but not renderd ** renderd[1620]: Parsing section renderd renderd[1620]: Parsing render section 0 renderd[1620]: Parsing section mapnik renderd[1620]: Parsing section default renderd[1620]: config renderd: unix socketname=/var/run/renderd/renderd.sock renderd[1620]: config renderd: num_threads=4 renderd[1620]: config renderd: num_slaves=0 renderd[1620]: config renderd: tile_dir=/var/lib/mod_tile renderd[1620]: config renderd: stats_file=/var/run/renderd/renderd.stats renderd[1620]: config mapnik: plugins_dir=/usr/local/lib/mapnik/input renderd[1620]: config mapnik: font_dir=/usr/share/fonts/truetype/ttf-dejavu renderd[1620]: config mapnik: font_dir_recurse=1 renderd[1620]: config renderd(0): Active renderd[1620]: config renderd(0): unix socketname=/var/run/renderd/renderd.sock renderd[1620]: config renderd(0): num_threads=4 renderd[1620]: config renderd(0): tile_dir=/var/lib/mod_tile renderd[1620]: config renderd(0): stats_file=/var/run/renderd/renderd.stats renderd[1620]: config map 0: name(default) file(/home/mayank/src/mapnik-style/osm.xml) uri(/osm_tiles/) htcp() host(localhost) renderd[1620]: Initialising unix server socket on /var/run/renderd/renderd.sock renderd[1620]: Created server socket 5 renderd[1620]: Renderd is using mapnik version 2.0.3 renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono-Bold.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-BoldOblique.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-Bold.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Oblique.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSerifCondensed.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono-BoldOblique.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-BoldItalic.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSerifCondensed-Italic.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-ExtraLight.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSansCondensed-Oblique.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono-Oblique.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSansCondensed-BoldOblique.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSerifCondensed-BoldItalic.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSansCondensed.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSansCondensed-Bold.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSerifCondensed-Bold.ttf renderd[1620]: DEBUG: Loading font: /usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-Italic.ttf Running in foreground mode... debug: init_storage_backend: initialising file storage backend at: /var/lib/mod_tile renderd[1620]: Starting stats thread /home/mayank/src/mapnik-style/inc/entities.xml.inc:9: parser warning : PEReference: %layers; not found %layers; ^ debug: init_storage_backend: initialising file storage backend at: /var/lib/mod_tile /home/mayank/src/mapnik-style/inc/entities.xml.inc:9: parser warning : PEReference: %layers; not found %layers; ^ debug: init_storage_backend: initialising file storage backend at: /var/lib/mod_tile debug: init_storage_backend: initialising file storage backend at: /var/lib/mod_tile /home/mayank/src/mapnik-style/inc/entities.xml.inc:9: parser warning : PEReference: %layers; not found %layers; ^ /home/mayank/src/mapnik-style/inc/entities.xml.inc:9: renderd[1620]: An error occurred while loading the map layer 'default': XML document not well formed: Entity 'datasource-settings' not defined (encountered in file '/home/mayank/src/mapnik-style/osm.xml' at line 4066) parser warning : PEReference: %layers; not found %layers; ^ renderd[1620]: An error occurred while loading the map layer 'default': XML document not well formed: Entity 'datasource-settings' not defined (encountered in file '/home/mayank/src/mapnik-style/osm.xml' at line 4066) renderd[1620]: An error occurred while loading the map layer 'default': XML document not well formed: Entity 'datasource-settings' not defined (encountered in file '/home/mayank/src/mapnik-style/osm.xml' at line 4066) renderd[1620]: An error occurred while loading the map layer 'default': XML document not well formed: Entity 'datasource-settings' not defined (encountered in file '/home/mayank/src/mapnik-style/osm.xml' at line 4066) renderd[1620]: DEBUG: Got incoming connection, fd 8, number 1 renderd[1620]: DEBUG: Got command RenderPrio fd(8) xml(default), z(0), x(0), y(0) renderd[1620]: Received request for map layer 'default' which failed to load renderd[1620]: DEBUG: Connection 0, fd 8 closed, now 0 left I am using http://switch2osm.org/serving-tiles/manually-building-a-tile-server-12-04/ for refrence. any help and I have tried building a map server from packages had a sock problem so switched here the sock problem can be rectified using sudo mkdir /var/run/renderd sudo chown mayank /var/run/renderd A: What a drama! The article at switch2osm.org could do with some updating. Anyway, to fix the above errors: Go to ~/src/mapnik-style and run python generate_xml.py --dbname gis --world_boundaries "/usr/local/share/world_boundaries" --accept-none This will reset your mapnik style configuration and fix those %layers errors. NOTE: Your world_boundaries folder location might be different to mine. Find yours by typing find /usr -type d -name "*world_boundaries*" -print Next, you may have errors like An error occurred while loading the map layer 'default': Could not create datasource for type: 'shape'. This is because renderd has the wrong plugin directory. To find yours, type find /usr -type d -name "*mapnik*" -print you'll get something like one of the following (and maybe a few others we don't care about): /usr/lib/mapnik /usr/local/lib/mapnik /usr/lib64/mapnik Go to the folder you found and check that it has the input dir. Mine has nothing else in it. This is your renderd mapnik plugin directory. Edit your /usr/local/etc/renderd.conf file to change the plugin directory to this location. For reference, my final renderd.conf file contained: [renderd] socketname=/var/run/renderd/renderd.sock num_threads=4 tile_dir=/var/lib/mod_tile stats_file=/var/run/renderd/renderd.stats [mapnik] plugins_dir=/usr/lib/mapnik/input font_dir=/usr/share/fonts/truetype/ttf-dejavu font_dir_recurse=1 [default] URI=/osm_tiles/ TILEDIR=/var/lib/mod_tile XML=/home/julian/src/mapnik-style/osm.xml HOST=localhost TILESIZE=256 I deleted all the commented lines in renderd.conf because they didn't seem useful and were creating the syntax errors at the top of the renderd output. Also, my ~/src/mapnik-style/inc/datasource-settings.xml.inc file contained: <Parameter name="type">postgis</Parameter> <!-- <Parameter name="password"></Parameter> --> <!-- <Parameter name="host"></Parameter> --> <!-- <Parameter name="port"></Parameter> --> <!-- <Parameter name="user"></Parameter> --> <Parameter name="dbname">gis</Parameter> <!-- this should be 'false' if you are manually providing the 'extent' --> <Parameter name="estimate_extent">false</Parameter> <!-- manually provided extent in epsg 900913 for whole globe --> <!-- providing this speeds up Mapnik database queries --> <Parameter name="extent">-20037508,-19929239,20037508,19929239</Parameter> I think that's everything you need to get rid of these errors. If not, please comment and I'll do my best to update this answer.
[ "stackoverflow", "0022496021.txt" ]
Q: IL: how to generate specific C# function? I have a need to dynamically generate such classes: public class SomeProxyClass { public Action<some_vars> ActionName; public rettype InvokeActionName(some_vars) { if(this.ActionName != null) { return this.ActionName(some_vars); } return default(rettype); } } public class SomeClass { public static SomeProxyClass parentProxy; public static rettype ActionName(some_vars) { this.parentProxy.InvokeActionName(some_vars); } } My main problem is that I don't know how to generate even such simple methods with IL instructions, so I'm looking for your help! Thank you in advance! A: If you want to generate class dynamically you can use CodeDom or Reflection.Emit. CodeDom creates C# code dynamically and then compiles it whereas Reflection.emit creates MSIL for the code. If you want to write in IL you can just create this class like you do normally and then use ILDASM.exe to decompile your class into IL. Now that you know what your code should be like in IL you can generate your class dynamically using Reflection.emitsILGenerator` class. For step by step process please refer this article: http://www.codeproject.com/Articles/121568/Dynamic-Type-Using-Reflection-Emit Hope it helps you.
[ "stackoverflow", "0040028916.txt" ]
Q: Log response ratios with 'Metafor' with zeros I'm using the 'metafor' package in R to perform log response ratios. Some of my means are zero, which seems to be the cause of a warning after my escalc command (since log(0) is -inf). The metafor package provides a method of adding a small value to zero to avoid this. The documentation states: "Cell entries with a zero can be problematic especially for the relative risk and the odds ratio. Adding a small constant to the cells of the 2 × 2 tables is a common solution to this problem [...] When to = "only0", the value of add is added to each cell of the 2 × 2 tables only in those tables with at least one cell equal to 0." For some reason this is not resolving my error, perhaps because my data is not a 2x2 table? (It is output from summarise with ddply from the ply package, similar to the formatting in this example). Must I replace the zero values with a small number manually or is there a more elegant way? (Note that in this example the rows with zero also have sample size of 1 and thus no variance and will be dropped from the analysis anyway. I just want to know how this works for the future). Reproducible example: dat<-dput(Bin_Y_count_summary_wide) structure(list(Species.ID = c("CAFERANA", "TR11", "TR118", "TR500", "TR504", "TR9", "TR9_US1"), Y_num_mean.early = c(2, 147.375, 4.5, 0.5, 12.5, 93.4523809523809, 5), N.early = c(1L, 4L, 2L, 4L, 4L, 7L, 2L), sd.early = c(NA, 174.699444284558, 6.36396103067893, 1, 22.4127939653523, 137.506118190001, 7.07106781186548), se.early = c(NA, 87.3497221422789, 4.5, 0.5, 11.2063969826762, 51.9724274972283, 5), Y_num_mean.late = c(0, 3.625, 2.98482142857143, 0.8, 3, 47.2, 0), N.late = c(1L, 4L, 7L, 10L, 10L, 8L, 1L), sd.late = c(NA, 7.25, 5.10407804830748, 1.75119007154183, 8.03118920210451, 40.7351024477486, NA), se.late = c(NA, 3.625, 1.9291601697265, 0.553774924194538, 2.53968501984006, 14.4020335865659, NA), Y_num_mean.wet = c(NA, 71.5, 0, 12, 27, 0, NA), N.wet = c(NA, 2L, 1L, 2L, 2L, 2L, NA ), sd.wet = c(NA, 17.6776695296637, NA, 9.89949493661167, 38.1837661840736, 0, NA), se.wet = c(NA, 12.5, NA, 7, 27, 0, NA)), row.names = c(NA, 7L), .Names = c("Species.ID", "Y_num_mean.early", "N.early", "sd.early", "se.early", "Y_num_mean.late", "N.late", "sd.late", "se.late", "Y_num_mean.wet", "N.wet", "sd.wet", "se.wet"), class = "data.frame", reshapeWide = structure(list( v.names = c("Y_num_mean", "N", "sd", "se"), timevar = "early_or_late", idvar = "Species.ID", times = c("early", "late", "wet"), varying = structure(c("Y_num_mean.early", "N.early", "sd.early", "se.early", "Y_num_mean.late", "N.late", "sd.late", "se.late", "Y_num_mean.wet", "N.wet", "sd.wet", "se.wet"), .Dim = c(4L, 3L))), .Names = c("v.names", "timevar", "idvar", "times", "varying"))) # Warning produced from this command test <- escalc(measure="ROM", m1i=Y_num_mean.early, sd1i=sd.early, n1i=N.early, m2i=Y_num_mean.late, sd2i=sd.late, n2i=N.late, data=dat, add=1/2, to="only0") A: The paragraph you are quoting applies to measures that one can calculate based on 2x2 tables (i.e., RR, OR, RD, AS, and PETO). The add and to arguments do not have any effect for measures such as SMD and ROM. The only way you can get a mean of 0 for a ratio scale variable (which is what use of response ratios assumes) is if every value is equal to 0. Therefore, by definition, the variance must also be 0. This applies whether the sample size is 1 (in which case the variance is of course also 0) or whether you have a larger sample size. In general, whenever at least one of the two means is 0, one cannot calculate the log response ratio. Of course, one could start adding some kind of constant to the means manually (and the same for the SDs), but this seems rather arbitrary. The adjustments we can do to counts in 2x2 tables are motivated based on statistical theory (those adjustments are actually bias reductions, which also happen to make the calculation of certain measures possible when there is a 0 count).
[ "ux.stackexchange", "0000024502.txt" ]
Q: Where should I put "Check for updates" functionality? Our application (running on Windows, but not a traditional application with menus and toolbars) has a feature that it can check for updates of the application, or of the firmware of the attached (medical) device that the application is controlling. We're having a difficult time deciding where to put this functionality. In other applications that have a traditional menu bar, we often see the function under the Help menu. We don't have such a menu bar, but we do have a side menu with some buttons with icons that represent the main actions, some of which fold out into a menu with several options. There is a help menu among these. However, we feel that the Check for Updates it out of place with the About... option and the actual Help option there. We also have a settings dialog, where you can tune all kinds of preferences. However, again, checking for updates is not a preference, so it does not really belong between there either. Last, we have a status-bar like area where we display things like the currently logged on user name with a logout button, and a status display of the devive (connected/disconnected). Perhaps it could find a place there? Or, perhaps we should check for updates automatically, and only display something in that status area if there if an update has been found? I would love to get some other suggestions of where auto-update functionality belongs in an application. A: Check for updates automatically, I mean, why would it need user control? I'd be curious how many people actually click on the Check for Updates menu versus the number of people who update after they get a notificaion. However, beware that industrial users might not want to update / want to know what is in the update. After all, a medical device, even if just diagnostical, is a matter of life and death... a wrong diagnosis because of an outdated firmware or a new buggy one is more responsibility than "adium crashed, let's update"..
[ "stackoverflow", "0047911765.txt" ]
Q: Function that accepts any indexable data type as an argument I am trying to make a function that can take any class that accepts the [] operator. I would like it to be able to accept: Arrays either by reference or by value Vectors or any other container that can be indexed By some experimenting I found that I also need some other traits like PartialOrd, PartialEq. I also need to find out how many objects are in the container. Here is my code: use std::ops::Index; use std::iter::ExactSizeIterator; use std::cmp::PartialEq; pub fn find<'a, I>(input: I, key: <I as std::ops::Index<u32>>::Output) -> Option<u32> where I: Index<u32> + ExactSizeIterator, <I as std::ops::Index<u32>>::Output: PartialEq + std::marker::Sized + std::cmp::PartialOrd, { if input.len() == 0 { return None; } if key < input[0] || key > input[(input.len() - 1) as u32] { return None; } let mut index: u32 = (input.len() - 1) as u32; loop { if key < input[index] { index /= 2; continue; } else if input[index] < key && input[index + 1] > key { return None; } else if key > input[index] { index += index / 2; continue; } else if input[index] == key { return Some(index); } else { return None; } } } fn main() { assert_eq!(find(&[1, 2], 2), Some(1)); assert_eq!(find([1, 2], 2), Some(1)); assert_eq!(find(vec![1, 2], 2), Some(1)); } It produces these errors: error[E0277]: the trait bound `&[{integer}; 2]: std::ops::Index<u32>` is not satisfied --> src/main.rs:36:16 | 36 | assert_eq!(find(&[1, 2], 2), Some(1)); | ^^^^ the type `&[{integer}; 2]` cannot be indexed by `u32` | = help: the trait `std::ops::Index<u32>` is not implemented for `&[{integer}; 2]` = note: required by `find` error[E0277]: the trait bound `&[{integer}; 2]: std::iter::ExactSizeIterator` is not satisfied --> src/main.rs:36:16 | 36 | assert_eq!(find(&[1, 2], 2), Some(1)); | ^^^^ the trait `std::iter::ExactSizeIterator` is not implemented for `&[{integer}; 2]` | = note: required by `find` error[E0277]: the trait bound `[{integer}; 2]: std::ops::Index<u32>` is not satisfied --> src/main.rs:37:16 | 37 | assert_eq!(find([1, 2], 2), Some(1)); | ^^^^ the type `[{integer}; 2]` cannot be indexed by `u32` | = help: the trait `std::ops::Index<u32>` is not implemented for `[{integer}; 2]` = note: required by `find` error[E0277]: the trait bound `[{integer}; 2]: std::iter::ExactSizeIterator` is not satisfied --> src/main.rs:37:16 | 37 | assert_eq!(find([1, 2], 2), Some(1)); | ^^^^ the trait `std::iter::ExactSizeIterator` is not implemented for `[{integer}; 2]` | = note: required by `find` error[E0277]: the trait bound `std::vec::Vec<{integer}>: std::ops::Index<u32>` is not satisfied --> src/main.rs:38:16 | 38 | assert_eq!(find(vec![1, 2], 2), Some(1)); | ^^^^ the type `std::vec::Vec<{integer}>` cannot be indexed by `u32` | = help: the trait `std::ops::Index<u32>` is not implemented for `std::vec::Vec<{integer}>` = note: required by `find` error[E0277]: the trait bound `std::vec::Vec<{integer}>: std::iter::ExactSizeIterator` is not satisfied --> src/main.rs:38:16 | 38 | assert_eq!(find(vec![1, 2], 2), Some(1)); | ^^^^ the trait `std::iter::ExactSizeIterator` is not implemented for `std::vec::Vec<{integer}>` | = note: required by `find` A: I found a way to implement it but with some limitations. pub struct Validator { data: Vec<i32>, } impl<'a> From<&'a [i32; 2]> for Validator { fn from(input: &'a [i32; 2]) -> Self { Validator { data: input.iter().map(|c| *c).collect(), } } } impl From<[i32; 2]> for Validator { fn from(input: [i32; 2]) -> Self { Validator { data: input.iter().map(|c| *c).collect(), } } } impl From<Vec<i32>> for Validator { fn from(input: Vec<i32>) -> Self { Validator { data: input } } } pub fn find<T>(input: T, key: i32) -> Option<usize> where T: std::convert::Into<Validator>, Validator: std::convert::From<T>, { let input: Vec<i32> = input.into().data; if input.len() == 0 { return None; } if key < input[0] || key > input[(input.len() - 1)] { return None; } let mut index = input.len() - 1; loop { if key < input[index] { index /= 2; continue; } else if input[index] < key && input[index + 1] > key { return None; } else if key > input[index] { index += index / 2; continue; } else if input[index] == key { return Some(index); } else { return None; } } } fn main() { assert_eq!(find(&[1, 2], 2), Some(1)); assert_eq!(find([1, 2], 2), Some(1)); assert_eq!(find(vec![1, 2], 2), Some(1)); } If you need a function that accepts an array of 3 or more numbers you will have to implement it for each number of elements. You can add support for more structs like VecDeque or custom ones by implementing the Into trait for the validator struct and the type you want to support.
[ "stackoverflow", "0005856644.txt" ]
Q: php wait till previous function has finished I'm trying to create some xml , basically by reading rss feeds and adding to them some custom tags. I've made a function that contains my code, and now i want to call the function several times with different rss urls. Each call will produce a different .xml file. I use DOMDocument to load and parse the rss, and simple_html_dom to load and parse the link of each rss item to get some content from the html. Here is a simplified example of my code: <?php include('simple_html_dom.php'); load_custom_rss('http://www.somesite.com/rssfeed/articles', 'articles.xml'); load_custom_rss('http://www.somesite.com/rssfeed/jobs', 'jobs.xml'); load_custom_rss('http://www.somesite.com/rssfeed/press', 'press.xml'); //up to 20 similar function calls here... function load_custom_rss($link, $filename){ $doc = new DOMDocument(); $doc->load($link); $newDoc = new DOMDocument('1.0', 'UTF-8'); $rss = $newDoc->createElement('rss'); $channel = $newDoc->createElement('channel'); $newDoc->appendChild($rss); $rss->appendChild($channel); foreach ($doc->getElementsByTagName('item') as $node) { //here is some code to read items from rss xml / write them to new xml document. //Code missing for simplicity //Next lines used to get some elements from the html of the item's link $html = new simple_html_dom(); html->load_file($node->getElementsByTagName('link')->item(0)->nodeValue); $ret = $html->find('#imgId'); } $newDoc->formatOutput = true; $fh = fopen($filename, 'w') or die("can't open file"); fwrite($fh, $newDoc->saveXML()); fclose($fh); unset($doc); //unset ALL variables and objects created in this function... //........ }//function end ?> My problem is that each call of the function consumes quite an amount of memory, so after the 3rd or 4th call of the function apache throws Fatal Error, as the script consumes memory amount bigger than the memory_limit, even though i unset ALL variables and objects created in the function. If i reduce the function calls to 1 or 2 everything works fine. Is there any way it could work? I was thinking about each function call waits for the previous to finish before starting, but how could this be done? Hope somebody could help. thanks in advance. A: The thing you want is normal behaviour in php. It's worked through from top to bottom. Each function has to wait, till the previous function has finished. I think you problem is rather the memory-limit within the php.ini. Open the file and search for the directive: memory_limit http://www.php.net/manual/en/ini.core.php#ini.memory-limit Increase it to fit your needs.
[ "ethereum.stackexchange", "0000071921.txt" ]
Q: Can I pass my mnemonic to ganache/ ganache-cli when it is starting up? I am wondering if I can pass the mnemonic that I created using metamask to boot up my local ganache network so that I do not have to log out and login metamask with different mnemonic everytime for a new project. A: When you are booting up ganache-cli, you can pass your mnemonic using -m or -menmonic. In ganache desktop app with UI, instead of doing quickstart, use New Workspace and navigate to ACCOUNT&KEYS Tab. There is a field to pass your mnemonic.
[ "stackoverflow", "0039574751.txt" ]
Q: Gulp and Pixi.js - ReferenceError: window is not defined I've recently switched to gulp and thought I'd try out pixi.js, I've been using the cdn of pixi but now I want pixi-timer to delay certain functions. So I thought, why not start bundling all of it with gulp? However I run into the following error: ReferenceError: window is not defined I thought that the newest versions of pixi.js supported gulp and even browserify, however it fails as soon as I try to require pixi.js. Got any pointers? My gulp file: var gulp = require('gulp'); var concat = require('gulp-concat'); var PIXI = require('pixi.js'); // var timer = require('pixi-timer'); var browserify = require('gulp-browserify'); gulp.task('game', function(){ return gulp.src('interface/js/gamelogic/**/*.js') .pipe(concat('game.js')) .pipe(gulp.dest('Vamp.Website/Resources/')); }); gulp.task('default', function(){ gulp.watch('interface/js/gamelogic/**/*.js', ['game']); }); Full error log: D:\Stuff\Vamp\vamp\Vamp>gulp D:\Stuff\Vamp\vamp\Vamp\node_modules\pixi.js\src\polyfill\index.js:5 if(!window.ArrayBuffer){ ^ ReferenceError: window is not defined at Object. (D:\Stuff\Vamp\vamp\Vamp\node_modules\pixi.js\src\polyfill\index.js:5:5) at Module._compile (module.js:413:34) at Object.Module._extensions..js (module.js:422:10) at Module.load (module.js:357:32) at Function.Module._load (module.js:314:12) at Module.require (module.js:367:17) at require (internal/module.js:16:19) at Object. (D:\Stuff\Vamp\vamp\Vamp\node_modules\pixi.js\src\index.js:2:1) at Module._compile (module.js:413:34) at Object.Module._extensions..js (module.js:422:10) D:\Stuff\Vamp\vamp\Vamp> A: You need to remove this line: var PIXI = require('pixi.js'); Here you are requiring pixi.js during your gulp build. That's wrong for several reasons. You are not actually doing anything with PIXI anywhere in your gulpfile. So why are you requiring it? PixiJs is a WebGL renderer that's targeting browsers. Your gulp build runs in node.js which doesn't have a window object. That's why you're getting that error. You want to bundle pixi.js and other files into a single game.js file. You don't need to require pixi.js for that. You just need to pass the path of your pixi.js installation to gulp.src() like this: gulp.task('game', function(){ return gulp.src([ 'node_modules/pixi.js/bin/pixi.js', 'interface/js/gamelogic/**/*.js' ]) .pipe(concat('game.js')) .pipe(gulp.dest('Vamp.Website/Resources/')); });
[ "stackoverflow", "0017221580.txt" ]
Q: RESTful application Roy fielding came with this idea and a lot of application is built around this. But I am really really confused why it is called Representational state transfer. Don't we go from one page to other page in almost every application and the application changes its state as we move from one page to other page? After reading a few article I know it 1. is built on HTTP, 2. Allows caching. 3. Resources can be accessed using URI. What are the advantages of REST over regular ASP.Net web form application? Why and where would I need RESTful application. Please help. BTW I have been programming ASP.Net web forms for long time and really don't know about new technologies. Thanks in advance. A: Here is the trend I see: 1996 - Classic ASP 2002 - ASP.NET 2009 - ASP.NET MVC 2012 - ASP.NET Web Api and Single-page applications Perhaps by "RESTful application" you mean a single-page application: http://en.wikipedia.org/wiki/Single-page_application This is where the trend is going I believe - instead of creating both UI and business logic on the server side, you can build rich client-side UIs which communicate with the server via REST protocol (thus having only business logic and RESTful endpoint on the server side), allowing you to provide a better use experience to your users. Also you can build multiple UIs for different platforms (Web UI, iOS, Android, Windows Phone, Windows 8 app etc.) which all are consuming the same REST API service.
[ "stackoverflow", "0062395140.txt" ]
Q: How does iteration with each method over product of arrays work in Ruby? I would like some help on clarifying how iteration over the product of arrays works in Ruby. After checking the documentation on product and each methods I wasn't able to find the answer. I have two arrays: arr = [1, 2, 3] arr1 = ['a', 'b', 'c'] Using the product method and specifying only one argument (product) to the each method: arr.product(arr1).each do |product| p product end Prints: # [1, "a"] # [1, "b"] # [1, "c"] When passing two arguments (number and letter) to each method in this way: arr.product(arr1).each do |number, letter| p number p letter end Results in the following output: # 1 # "a" # 1 # "b" # 1 # "c" # 2 # "a" # 2 # "b" # 2 # "c" # 3 # "a" # 3 # "b" # 3 # "c" Do I understand correctly that in the second case, Ruby iterates over each array (arr and arr1) which was supplied to the product method? A: What your block receives is always the same, a pair (a two elements array). In the second case you're basically destructuring the pair. a = [1, 'a'] # a = [1, 'a'] a, b = [1, 'a'] # a = 1, b = 'a'
[ "stackoverflow", "0016932913.txt" ]
Q: CSS : span in left with fixed width, span in right with fixed width, the center table fills up rest of the space markup : <div> <span class="left"></span> <table></table> <span class="right"></span> </div> Desired output : |------------------------------------------------------------------------| | | | | |.left | |.right| | | | | | | table | | | | dynamic width | | |width | |width | | 1em | | 1em | | | | | | | | | | | | | | | | | |------------------------------------------------------------------------| The solutions i saw on other answers just don't work when center element is a table. A: You can use float, also using span as a container is not a good idea. Instead use div. Also put your table inside a div: .container { overflow: hidden; } .left { float: left; width: 100px; background: yellow; } .right { float: right; width: 100px; background: yellow; } .main { background: orange; margin: 0 100px; } <div class="container"> <div class="left">Left</div> <div class="right">Right</div> <div class="main"> Hello World </div> </div>
[ "stackoverflow", "0040164431.txt" ]
Q: Why does my regex pattern allow digits? I have tried creating a regex pattern that matches only letters and allows a whitespace: import re user_input = raw_input('Input: ') if re.match('[A-Za-z ]', user_input): print user_input However, When inputting o888, or something similar, a match seems to still occur A: That happens because your regex allows partial matches. Use if re.match('[A-Za-z ]*$', user_input): ^^ to anchor the pattern at the end and match 0+ chars. As re.match anchors the pattern at the start of the string, the ^ anchor is not necessary, but $ - end of string - is required to enforce the full string match. If you do not want to allow an empty string, use + quantifier - one or more occurrences - rather than * (zero or more occurrences).
[ "stackoverflow", "0012028976.txt" ]
Q: NSDictionary Predicate filter on child objects I'm trying to filter a response from Facebook's API, the JSON looks like this: { "Data": [ { "first_name" : "Joe", "last_name" : "bloggs", "uuid" : "123" }, { "first_name" : "johnny", "last_name" : "appleseed", "uuid" : "321" } ] } I load this into a NSDictionary, accessing it like [[friendDictionary objectForKey:@"data"] allObjects] I'm now trying to filter based on the first_name and last_name based on when someone inputs a name into a textfield. Here's what I have but its failing horribly: NSPredicate *filter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"ANY.first_name beginswith[c] %@ OR ANY.last_name beginswith[c] %@", friendField.text, friendField.text]]; NSLog(@"%@", [[[friendDictionary objectForKey:@"data"] allObjects] filteredArrayUsingPredicate:filter]); Any help is greatly appreciated, thanks guys A: You are thinking too complicated. stringWithFormat within predicateWithFormat makes no sense here. No need for the "ANY" aggregate in the predicate, that is used with to-many-relationships in Core Data objects. [friendDictionary objectForKey:@"Data"] returns an array, allObjects is wrong here. The key is "Data", not "data". That gives NSPredicate *filter = [NSPredicate predicateWithFormat:@"first_name beginswith[c] %@ OR last_name beginswith[c] %@", friendField.text, friendField.text]; NSArray *filteredArray = [[friendDictionary objectForKey:@"Data"] filteredArrayUsingPredicate:filter];
[ "stackoverflow", "0003263857.txt" ]
Q: Can I load mysql data trunk by trunk in java? Currently I am using statement.executeQuery(qStr) in java to select a large amount of data from mysql. Unfortunatly, java keeps running out of memory at the statement.executeQuery(qStr) statement with exception java.lang.OutOfMemoryError: Java heap space. I am wondering if there is a method to stream load data from mysql. So that I can handle the selected data trunk by trunk to avoid running out of memory? Note that: I am using eclipse and this post shows me how to increase the heap memory for java to use inside eclipse. But after I followed it's method, i am still running into the same problem. Thanks in advance. A: Yes, you can set the FetchSize on a Statement to Integer.MIN_VALUE , the ResultSet should be TYPE_FORWARD_ONLY as well, though I believe that's the default.. MySQL treats that specially and enables streaming of the ResultSet instead of reading it all into memory, it's documented here PreparedStatement stmt = conn.prepareStatement(sql,ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(Integer.MIN_VALUE);
[ "stackoverflow", "0014964939.txt" ]
Q: Remove "Done" button of ActionMode 0I'm using startActionMode(ActionMode) on my app. By default it's add a "Done" button on the bar, I want to remove it. Also, if there's a way to change it's text, I want to know too, cause a different description than "Done" can make the action be correspondent to the behaviour of what it does. A: I agree with @CommonsWare that it is invalid design to hide the Done button. However, there are customers that want to have this button removed and I can understand that the checkmark may cause confusion to users because it actually does nothing in some cases. So, here is how to remove the button with styles: <style name="AppTheme" parent="android:Theme.Holo"> <item name="android:actionModeCloseButtonStyle">@style/NoCloseButton</item> </style> <style name="NoCloseButton" parent="@android:style/Widget.ActionButton.CloseMode"> <item name="android:visibility">gone</item> </style> A: Even I was stuck with same and I found this way to solve it. int doneButtonId = Resources.getSystem().getIdentifier("action_mode_close_button", "id", "android"); LinearLayout layout = (LinearLayout) findViewById(doneButtonId); TextView doneview = (TextView) layout.getChildAt(1); doneview.setText(""); Hope this helps!!
[ "stackoverflow", "0026613177.txt" ]
Q: Passing value from helper thread to main thread I have a thread with a try-catch block. Inside the try block I have the HTML stored in a variable which I want to load into a webview. Now Android/Java doesn't allow Webview to be called any other place apart from main thread. How can I pass this String variable value outside the scope of thread? Making string variable final and declaring outside thread doesn't help. public class MyCustomView extends LinearLayout { //UI elements private WebView mWebView; final Activity activity = (Activity) this.getContext(); new Thread(new Runnable() { @Override public void run() { try { //Using thread because accessing network URL obj = new URL(adrequesturl); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); if (con.getResponseCode() == 200) { //*****Need this variable's value in the Main Thread String dataToLoad="some_custom_html"; //mWebView is a webview that I have created and below can not get executed from inside helper thread //mWebView.loadData(dataToLoad, "text/html", "utf-8");- } else { //Some code } } catch (Exception e) { //Some code } } }).start(); //**solution which worked for me** activity.runOnUiThread(new Runnable() { public void run() { mWebView.loadData(dataToLoad, "text/html", "utf-8"); } }); //Now we are back to main thread //********Main Problem************** //Below mWebView.loadData is allowed but I can not get dataToLoad value here //mWebView.loadData(dataToLoad, "text/html", "utf-8"); } A: You can run a part of code in the UI Thread this way : this.getContext().runOnUiThread(new Runnable() { public void run() { mWebView.loadData(dataToLoad, "text/html", "utf-8"); } });
[ "stackoverflow", "0050894926.txt" ]
Q: Jenkins PER USER default parameter values? We are using a parameterized Jenkins build job, and I would like to have default values for some parameters specific for myself, e.g. the dev branch name I mostly use. Is it possible? We do have personal users in Jenkins. A: You could do it by: Create a scriptler which checks the current user and returns the appropriate value: def user = jenkins.model.Jenkins.getAuthentication().getName(); def returnValue switch (user) { case ['user1','user2']: returnValue = 'xyz' break; case ['user3']: returnValue = 'abc' break; default: returnValue = '00' break; } return returnValue If you want to use the Active Choices Plugin your script will need to return a list: def user = jenkins.model.Jenkins.getAuthentication().getName(); def returnValue = []; switch (user) { case ['user1','user2']: returnValue << 'xyz' break; case ['mtlelj']: returnValue << 'abc' break; default: returnValue << '00' break; } return returnValue Configure your parameterized build to have a Dynamic Parameter (Scriptler) or an Active Choices parameter and reference the script you created as it's source. If you don't want a script centrally managed by admins, the Active Choices Parameter allows you to use the code within the parameter definition. I'm using: Jenkins ver 2.32.3 Scriptler Plugin ver 2.9 Dynamic Parameter Plugin ver 2.9 Active Choices Plugin ver 2.9
[ "unix.stackexchange", "0000119731.txt" ]
Q: Unable to connect after ChrootDirectory within sshd_config After adding the following to my sshd_config file... Match user myuser ChrootDirectory /var/www/html X11Forwarding no AllowTcpForwarding no ForceCommand internal-sftp I am unable to connect using the user 'myuser' 'myuser' has read and write access to /var/www/html (in fact it is the owner) and that directory is set as its home directory. If I remove these lines I can connect, but I have access to folders below this (which I don't want) What am I doing wrong? A: The problem here, because you are in a chroot enviroment (in your case is /var/www/html), therefore there is no things like /bin/bash under your file system, which really means /var/www/html/bin/bash because your / is now /var/www/html. For using ssh chroot, you must copy some tools, library to your chroot enviroment, creating some devices like /dev/null, /dev/tty... It's very complicated tasks. Fortunately, this script can do those tasks for us.
[ "stackoverflow", "0005624370.txt" ]
Q: How do I parse a URL in PHP? Possible Duplicate: Parsing Domain From URL In PHP how do i get http://localhost/ from http://localhost/something/ using php I tried $base = strtok($url, '/'); A: You can use parse_url to get down to the hostname. e.g.: $url = "http://localhost/path/to/?here=there"; $data = parse_url($url); var_dump($data); /* Array ( [scheme] => http [host] => localhost [path] => /path/to/ [query] => here=there ) */ A: $url = 'http://localhost/something/'; $parsedurl = parse_url($url); echo $parsedurl['scheme'].'://'.$parsedurl['host'];
[ "stackoverflow", "0012341796.txt" ]
Q: Memory allocation while passing environment variable as command line argument I am trying simple buffer overflow attacks in linux. I have a vulnerable program which accepts a command line argument. I have another program that sets an environment variable that has some code i want to execute (typically shellcode). Now I am trying to overflow the buffer of my vulnerable program with the address of this environment variable. I have the following questions: When I pass an environment variable as a command line argument, is the content of the variable copied into argv of my vulnerable program? Where in the process' address space will the environment variables (command line args) be stored? Will it be on the process stack or somewhere else? A: Yes. It's up to the implementation. You're presumably doing something like: victim "$SHELLCODE" If $SHELLCODE is also an environment variable, the program will get one copy in the environment, preceded by SHELLCODE= so it could be retrieved via getenv(), and one copy in the argv argument list.
[ "math.stackexchange", "0002855330.txt" ]
Q: Modulus of continuity under homeomorphisms Let $f:C:=[0,1]^{d}\longrightarrow \mathbb{R}$ be continuous, and define the (usual) modulus of continuity of $f$ of order $\epsilon$ as $\omega(f;\epsilon):=\sup\{|f(x)-f(y)|:x,y\in C, \|x-y\|\leq \epsilon\}$ , where $\|\cdot\|$ denotes the Euclidean norm. Consider an orientation-preserving homeomorphisms, or simplily an homeomorphism, $\phi:C\longrightarrow C$. What is the relation between $\omega(f;\epsilon)$ and $\omega(f\circ \phi;\epsilon)$? Can be stated, for a such $\phi$, an inequality of the form $\omega(f\circ \phi;\epsilon) \leq k \omega(f;\epsilon)$ $k$ being a constat independent of $\phi$? It is seems clear, from the definition, that $\omega(f\circ \phi;\epsilon) =\omega(f;\omega(\phi;\epsilon))$, but I do not see clear if an inequality like above is possible. Or, in other words, if there is an upper bound for $\omega(\phi;\epsilon)$, independent of $\phi$. Many thanks in advances for your comments. A: In fact for just one homeomorphism this can fail. On $[0,1],$ let $f(x)=x,\phi(x) = \sqrt x.$ Suppose we have $\omega(f\circ \phi,\epsilon)\le k \omega(f,\epsilon)$ for all $\epsilon.$ Then $$f\circ \phi(\epsilon) - f\circ \phi(0) = \sqrt \epsilon \le \omega(f\circ \phi,\epsilon) \le k\omega(f,\epsilon) =k\epsilon$$ for all $\epsilon>0.$ Dividing by $\sqrt \epsilon,$ we obtain $1\le k\sqrt \epsilon$ for all $\epsilon>0.$ Letting $\epsilon\to 0$ then shows $1\le 0,$ contradiction.
[ "stackoverflow", "0027304117.txt" ]
Q: Wordpress remove from admin bar menu I tried to remove User right section but with no luck any help ? WP version 3.8 This code not working ... add_action( 'init', 'remove_user_account_menu' ); function remove_user_account_menu() { remove_action( 'admin_bar_menu', 'wp_admin_bar_my_account_menu', 0 ); remove_action( 'admin_bar_menu', 'wp_admin_bar_my_account_item', 7 ); } A: The following will do the trick: add_action( 'wp_before_admin_bar_render', 'so27304117_before_admin_bar_render' ); function so27304117_before_admin_bar_render() { global $wp_admin_bar; $wp_admin_bar->remove_menu('my-account'); } Dive into the admin toolbar API.
[ "stackoverflow", "0029595589.txt" ]
Q: How do I test emailing in a Velocity end-to-end test? I'm working on writing end-to-end (client) tests in Velocity, and am trying to figure out how to make sure that emails are being sent. I'm currently using Mocha, but I'm willing to switch to another testing framework if it makes this task easier. A: You can use a fixture and override the Email send function like this: Email.send = function (options) { // store those somewhere like an emailsCollection emailsCollection.insert(options); }; Now you can assert on the emailsCollection in your tests
[ "meta.stackexchange", "0000192403.txt" ]
Q: Comment on posts that you have an open bounty on, despite reputation I think it would be very useful. I have a question that I have an open bounty on. Putting up said bounty brought my reputation below the point where I am allowed to comment on other peoples' posts. It's so frustrating not to be able to comment and give feedback on the answers given! Especially since it would be helpful, for them, me, and the readers, to know particularly what is good and isn't good about their answer, and therefore give some better guidelines to future answerers on how they can win the bounty. A: I agree this is a problem, but let's admit something, it will probably occur very rarely. The real problem is "someone had a privilege and lost it without doing anything wrong" which doesn't sound fair at all. My opinion is, there should be a fix for this if (and only if) they fix the complete issue, because it is not worth fixing this small-never-happening-again-issue alone. Some ideas to fix it all can be: store somwhere the highest reputation and use this as a reference prevent dropping below X reputation
[ "stackoverflow", "0052923816.txt" ]
Q: Splitting and replacing strings in a 2D list I have a set of data as shown below: [['05-Feb-2001 12:00:01','A','<>TG:MIN MAX W1 GRN RED'], ['05-Feb-2001 12:00:01','B','MIN MAX'], ['05-Feb-2001 12:00:07','A','<i>TG:MAX MIN W2'], ['05-Feb-2001 12:00:07','C','MAX RED GRN'], ['05-Feb-2001 12:00:20','A','MIN MAX RED'], ['05-Feb-2001 12:01:00','A','<i>TG:MAX MIN RED GRN']] As shown in the 3 value of the line, it may or maynot include "<>TG". I would like to detect for "<i>" and split it out of the string then add it to become the 4th column The desired output will be [['05-Feb-2001 12:00:01', 'A', '<>TG:MIN MAX W1 GRN RED'], ['05-Feb-2001 12:00:01', 'B', 'MIN MAX'], ['05-Feb-2001 12:00:07', 'A', 'TG:MAX MIN W2', '<i>'], ['05-Feb-2001 12:00:07', 'C', 'MAX RED GRN'], ['05-Feb-2001 12:00:20', 'A', 'MIN MAX RED'], ['05-Feb-2001 12:01:00', 'A', 'TG:MAX MIN RED GRN', '<i>']] Please Advice! A: Does this work for you? Just iterate over the sublists and update inplace. for l in lst: if '<i>TG' in l[-1]: l[-1] = l[-1].replace('<i>', '') l.append('<i>') print(lst) [['05-Feb-2001 12:00:01', 'A', '<>TG:MIN MAX W1 GRN RED'], ['05-Feb-2001 12:00:01', 'B', 'MIN MAX'], ['05-Feb-2001 12:00:07', 'A', 'TG:MAX MIN W2', '<i>'], ['05-Feb-2001 12:00:07', 'C', 'MAX RED GRN'], ['05-Feb-2001 12:00:20', 'A', 'MIN MAX RED'], ['05-Feb-2001 12:01:00', 'A', 'TG:MAX MIN RED GRN', '<i>']] If you want to check for the token at the start of the string, change if '<i>TG' in l[-1] to if l[-1].startswith('<i>TG') (You don't need regex.)
[ "stackoverflow", "0040174866.txt" ]
Q: How to render HTML element that is a variable in an Angular 2 component I want to have a component that renders an arbitrary number of canvas elements that contain images or videos or whatever. Sometimes there will be one image. Other times I'll want to have two or three side-by-side. Maybe there's a button to toggle between one or two images. So my component looks roughly like this: @Component({ selector: 'canvas-container', template: `<div *ngFor="let canvas of canvases">???</div>` }) export class CanvasContainerComponent { canvases: HTMLCanvasElement[] = []; addCanvas(image) { const canvas = <HTMLCanvasElement> document.createElement('canvas'); // some stuff to do with sizing and drawing this.canvases.push(canvas); } } So another component will call the addCanvas method, or the canvases will be passed in as an @Input. How can I wrestle with Angular 2 to then render these canvases that are stored as HTMLCanvasElement variables? Using {{canvas}} just displays the string form of the element: [object HTMLCanvasElement]. Or is there a better way to approach this whole endeavour? A: Instead of <div *ngFor="let canvas of canvases">...</div>, you can simply use <canvas myCanvasDirective *ngFor="let canvas of canvases" [inputs ...]></canvas>. Then you can write a directive that deals with how to render each canvas based on the inputs you send in. import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[myCanvasDirective]' }) export class MyCanvasDirective { constructor(el: ElementRef) { const canvas: HTMLCanvasElement = el.nativeElement; // Do all the canvas context and drawing stuff here } }
[ "stackoverflow", "0013783195.txt" ]
Q: Parse error: syntax error, unexpected T_LOGICAL_OR I have the following error with my php code.. Parse error: syntax error, unexpected T_BOOLEAN_OR in... My code is... <?php if( !is_home()) or ( !is_archive()) { ?> (my code is here) <?php ?> The error is on the first line. I have tried googling this, but cannot see what I have done wrong. Can you spot anything wrong with the above code? Thanks in advance A: Try with: <?php if( !is_home() or !is_archive()) { ?>
[ "pt.stackoverflow", "0000089693.txt" ]
Q: Chamar uma variável SetInterval Eu tenho a variavel X X = setInterval(function() { ... e depois de um tempo eu dei um stop nesse setInterval com a função clearInterval(X) Como faço para chamar essa variável para ela continuar o loop depois de tê-la "apagado"? A: Não podes parar e recomeçar um setInterval. O que podes fazer é: recomeçar se não houver dados que precisem ser re-utilizados simular pausa via retorno de dentro da função Primeiro caso: Define a função fora do setInterval e depois começa/recomeça: function beeper(){ // fazer algo } var x = setInterval(beeper, 1000); // para parar: clearInterval(x); // para recomeçar: x = setInterval(beeper, 1000); Segudo caso var semaforoVermelho = false; function beeper(){ if (semaforoVermelho) return; // fazer algo } setInterval(beeper, 1000); // para pausar: semaforoVermelho = true; // para recomeçar: semaforoVermelho = false;
[ "stackoverflow", "0041847422.txt" ]
Q: Reducing aggregation execution time I'm able to have the result that I want, but I would like to know if there is some ways to reduce the execution time of the aggregation that I do. First, here is my data : .................................................................................. table activites : { "_id" : ObjectId("58872a885bd87fa3b7e736cf"), "jour" : "2015-01-01", "sgt_id" : 1, "produit_id" : 1, "affichages" : 1525, "clics" : 16, "consultations" : 20, "ajoutsPanier" : 1, "unites" : 0, "commandes" : 0, "recettes" : 0, "demandeBrute" : 0, "txDispo" : "NULL" } { "_id" : ObjectId("58872a885bd87fa3b7e736d0"), "jour" : "2015-01-01", "sgt_id" : 1, "produit_id" : 3, "affichages" : 519, "clics" : 6, "consultations" : 7, "ajoutsPanier" : 0, "unites" : 0, "commandes" : 0, "recettes" : 0, "demandeBrute" : 0, "txDispo" : "NULL" } { "_id" : ObjectId("58872a885bd87fa3b7e736d1"), "jour" : "2015-01-01", "sgt_id" : 1, "produit_id" : 5, "affichages" : 421, "clics" : 5, "consultations" : 6, "ajoutsPanier" : 1, "unites" : 0, "commandes" : 0, "recettes" : 0, "demandeBrute" : 0, "txDispo" : "NULL" } and 14 millions of entries like that... .................................................................................. table categories2 : { "_id" : ObjectId("5888609e5bd87fa3b7c72551"), "categorie_id" : 108, "type" : 1, "niveau" : 2, "hierarchie" : 2, "cat_id_client" : "Accessories", "categorie" : "Accessories", "label" : "NULL", "createur_id" : "NULL", "produit_id" : [ 867, 2943, 6443, 6447, 6525 ] } { "_id" : ObjectId("5888609e5bd87fa3b7c7259f"), "categorie_id" : 110, "type" : 1, "niveau" : 2, "hierarchie" : 2, "cat_id_client" : "Jewelry & watches", "categorie" : "Jewelry & watches", "label" : "NULL", "createur_id" : "NULL", "produit_id" : [ 2849, 2853, 2857, 2867, 2873, 2885, 2891, 2893, 2897, 2903, 2907, 2913, 2919, 2927, 2945, 2957, 2963, 3531, 3533, 3535, 3537, 3539, 3541, 3543, 3545, 3547, 3549, 3551, 3553, 3555, 3557, 3559, 3561, 3563, 3565, 3567, 3569, 3571, 3573, 3575, 3577, 3579, 3581, 3583, 3585, 3587, 3589, 3591, 3593, 3595, 3597, 3599, 3601, 3603, 3605, 3607, 3609, 3611, 3613, 3615, 3617, 3619, 3621, 3623, 3625, 3627, 3629, 3631, 6441, 6443, 6445, 6449, 6451, 6453, 6455, 6457, 6459, 6461, 6463, 6465, 6467, 6469, 6471, 6473, 6475, 6477, 6479, 6481, 6483, 6485, 6487, 6489, 6491, 6493, 6495, 6497, 6499, 6501, 6503, 6505, 6507, 6509, 6511, 6513, 6515, 6517, 6519, 6521, 6523, 6527 ] } { "_id" : ObjectId("5888609e5bd87fa3b7c725a2"), "categorie_id" : 106, "type" : 1, "niveau" : 2, "hierarchie" : 2, "cat_id_client" : "Clothing", "categorie" : "Clothing", "label" : "NULL", "createur_id" : "NULL", "produit_id" : [ 1485, 1487, 1489, 1491, 1493, 1495, 1497, 1499, 1501, 1503, 1505, 1507, 1509, 1511, 1513, 1515, 1517, 1519, 1521, 1523, 1525, 1527, 1681, 1683, 1685, 1687, 1689, 1691, 1693, 1695, 1697, 1699, 1701, 1703, 1705, 1707, 1709, 1711, 1713, 1715, 1717, 1721, 1723, 1725, 1727, 1729, 1731, 1733, 1735, 1737, 1739, 1741, 1743, 1745, 1747, 1749, 1751, 1753, 1755, 1757, 1759, 1761, 1763, 1765, 1767, 1769, 1771, 1773, 1775, 1777, 1779, 1781, 1783, 1785, 1787, 1789, 1791, 1793, 1795, 1797, 1799, 1801, 1803, 1805, 1807, 1809, 1811, 1813, 1815, 1817, 1819, 1821, 1823, 1825, 1827, 1829, 1831, 1833, 1835, 1837, 1839, 1841, 1843, 1845, 1847, 1849, 1851, 1853, 1855, 1857, 1859, 1861, 1863, 1867, 1869, 1871, 1873, 1875, 1877, 1879, 1881, 2845, 2851, 2855, 2859, 2863, 2869, 2871, 2877, 2879, 2881, 2887, 2895, 2905, 2909, 2911, 2917, 2923, 2925, 2929, 2933, 2935, 2939, 2941, 2947, 2951, 2953, 2959, 3849, 3851, 3853, 3855, 3857, 3859, 3861, 3863, 3865, 3867, 3869, 3871, 3873, 3875, 3877, 3879, 3881, 3883, 3885, 3887, 3889, 3891, 3893, 3895, 3897, 3899, 3901, 3903, 3905, 4969, 4971, 4973, 4975, 4977, 4979, 4981, 4983, 4985, 4987, 4989, 4991, 4993, 4995, 4997, 4999, 5001, 5003, 5005, 5007, 5009, 5011, 5013, 5015, 5017, 5019, 5021, 5023, 5025, 5027, 5029, 5031, 5033, 5035, 5037, 5039, 5041, 5043, 5045, 5047, 5049, 5743, 5745, 5747, 5749, 5751, 5753, 5755, 5757, 5759, 5761, 5763, 5765, 5767, 5769, 5771, 5773, 5775, 5777, 5779, 5781, 5783, 5785, 5787, 5789, 5791, 5793, 5795, 5797, 5799, 5801, 5803, 5805, 5807, 5809, 5811, 5813, 5815, 5817, 5819, 5821, 5823, 5825, 5827, 5829, 5831, 5833, 5835, 5837, 5839, 5841, 5843, 5845, 5847, 5849, 5851, 5853, 5855, 5857, 5859, 5861, 5863, 5865, 5867, 5869, 5871, 5873, 5875, 5877, 5879, 5881, 5883, 5885, 5887, 5889, 5891, 5893, 5895, 5897, 5899, 5901, 5903, 5905, 5907, 5909, 5911, 5913, 5915, 5917, 5919, 5921, 5923, 5925, 5927, 5929, 5931, 5933, 5935, 5937, 5939, 5941, 5943, 5945, 5947, 5949, 5951, 5953, 5955, 5957 ] } { "_id" : ObjectId("5888609e5bd87fa3b7c725c0"), "categorie_id" : 107, "type" : 1, "niveau" : 2, "hierarchie" : 2, "cat_id_client" : "Shoes", "categorie" : "Shoes", "label" : "NULL", "createur_id" : "NULL", "produit_id" : [ 1719, 1865, 2861, 2875, 2883, 2889, 2899, 2901, 2915, 2921, 2931, 2937, 2949, 2955, 2961, 5487, 5489, 5491, 5493, 5495, 5497, 5499, 5501, 5503, 5505, 5507, 5509, 5511, 5513, 5515, 5517, 5519, 5521, 5523, 5525, 5527, 5529, 5531, 5533, 5535, 5537, 5539, 5541, 5543, 5545, 5547, 5549, 5551, 5553, 5555, 5557, 5559, 5561, 5563, 5565, 5567, 5569 ] } { "_id" : ObjectId("5888609e5bd87fa3b7c725ea"), "categorie_id" : 109, "type" : 1, "niveau" : 2, "hierarchie" : 2, "cat_id_client" : "Handbags", "categorie" : "Handbags", "label" : "NULL", "createur_id" : "NULL", "produit_id" : [ 845, 847, 849, 851, 853, 855, 857, 859, 861, 863, 865, 2847, 2865 ] } { "_id" : ObjectId("5888609e5bd87fa3b7c725f9"), "categorie_id" : 111, "type" : 1, "niveau" : 2, "hierarchie" : 2, "cat_id_client" : "Health & beauty", "categorie" : "Health & beauty", "label" : "NULL", "createur_id" : "NULL", "produit_id" : [ 3249, 3251, 3253, 3255, 3257, 3259, 3261, 3263, 3265 ] } What I would like to have in result is that : { "_id" : 106, "categorie" : "Clothing", "consultations" : 185507, "recettes" : 1592183.49 } { "_id" : 107, "categorie" : "Shoes", "consultations" : 53636, "recettes" : 277869.81 } { "_id" : 110, "categorie" : "Jewelry & watches", "consultations" : 47071, "recettes" : 116746.03 } { "_id" : 109, "categorie" : "Handbags", "consultations" : 7149, "recettes" : 90921.05 } { "_id" : 111, "categorie" : "Health & beauty", "consultations" : 4542, "recettes" : 7671.51 } { "_id" : 108, "categorie" : "Accessories", "consultations" : 1718, "recettes" : 15689.43 } For each categorie, have the sum of the consultations and recettes for each product which belongs to this categorie. My code to obtain this result : db.categories2.aggregate([ { $match: { type: 1, niveau: 2, hierarchie: 2 } }, { "$unwind": "$produit_id" }, { $lookup: { from: "activites", localField: "produit_id", foreignField: "produit_id", as: "activites" } }, { $project: { _id: 1, categorie_id: 1, categorie: 1, produit_id: 1, activites : { $filter: { input: "$activites", as: "activite", cond : { $and: [ { $gte: [ "$$activite.jour", "2016-09-01" ] }, { $lte: [ "$$activite.jour", "2016-11-03" ] }, { $eq : [ "$$activite.sgt_id", 1] } ] } } } } }, { $unwind: "$activites" }, { $group: { _id: "$categorie_id", consultations: { $sum: "$activites.consultations" }, recettes: { $sum: "$activites.recettes" } } }, { $sort: { "consultations" : -1 } } ]) Explanation : Match the categories asked by the user. Each categories contains a produits field which is an array of products id Unwind this array For each line (so each product), look into the activites table to obtain consultations and recettes fields Filter the activites result to match the dates given by the user Unwind all the activites found to have one line per activite per day Group the result by categorie_id to do the sum of consultations and recettes The problem is : the $lookup from activites take approximately 1~2 seconds (I don't think that we can do better because of the 14 millions of entries of this table) the last $group take something like 5 seconds to group all thecategorie_id` and do the sum So in total, the request is done in 7,5 seconds. Is there a way to do better, with another kind of request maybe ? Thanks a lot for your help ! UPDATE : I thought maybe there is a way to group the children activites after the $project, and so avoid the $unwind and $group after that ? A: I achieve to reduce the execution time to 300 ms, by splitting in two functions and doing the sum by hand in Javascript : var before = new Date() var pdtCat = db.categories2.aggregate([ { $match: { type: 1, niveau: 2, hierarchie: 2 } }, { "$unwind": "$produit_id" } ]); var produits_id = []; var categories = []; var prev = []; pdtCat.forEach(produit => { produits_id.push(produit.produit_id); var index = prev.indexOf(produit.categorie_id); if(index > -1) { categories[index].produits_id.push(produit.produit_id); } else { prev.push(produit.categorie_id); categories.push({ categorie_id: produit.categorie_id, categorie: produit.categorie, consultations: 0, recettes: 0, produits_id : [ produit.produit_id ] }); } }); var produits = db.activites.find({ "jour" : { $gte: "2016-09-01", $lte: "2016-11-03" }, sgt_id: 1, produit_id : { $in: produits_id } }).forEach(produit => { for(var i=0; i < categories.length; i++) { if(categories[i].produits_id.indexOf(produit.produit_id) > -1) { categories[i].consultations += produit.consultations; categories[i].recettes += produit.recettes; } } }); categories.sort(function(a, b) { return b.consultations - a.consultations; }); categories.forEach(categorie => { delete categorie.produits_id; print(JSON.stringify(categorie)); }); var after = new Date() execution_mills = after - before
[ "stackoverflow", "0049014074.txt" ]
Q: Excel function to sum all actual costs plus estimates on blank rows with no calculation column In Excel 2013, I need to sum all numbers in a column of actual costs plus estimates in a second column in rows where the actual costs are blank. Estimate (A) Actual (B) Row 1 106 Row 2 212 230 Row 3 318 295 Row 4 424 totals 1060 525 I need to return 106 + 230 + 295 + 424. (or 525 + 106 + 424) What I have tried: --I have solved the problem if I put a placeholder (like "missing") in the blanks and then using a SUMIF nested in a simple SUM. But that badly clutters the chart. =SUM(A5, SUMIF(B1:B4,"missing",A1:A4)) --I have also solved the problem by creating a calculation column that has an ISBLANK function and then using the SUMIF over that result. However, I can't figure out how to consolidate. I realize I could create another sheet to hold the calculation column, but the workbook will already have a number of sheets and I want to avoid an extra. C1=ISBLANK(B1) dragged down to C4 and then =SUM(A5, SUMIF(C1:C4, "TRUE", A1:A4)) --I have found a number of online descriptions of managing similar tasks with pivot tables and months, but I can't seem to figure it out for a simple table. I think my ISBLANK attempt is failing on consolidation because of something to do with absolute references vs. ranges in the column, but I can't figure it out. Any advice would be greatly appreciated--thanks A: Use SUMIF() to sum all numbers in column A if the value to the right is blank. Then add the sum of column B. See this formula: =SUMIF(B:B, "", A:A) + SUM(B:B)
[ "stackoverflow", "0004647584.txt" ]
Q: Why do I get errors about non-staic methods being referenced from the static context? In the following block of code, I am trying to print the properties whose location, monthlyRent, numberOfBedrooms defined in the Property class being equal to this method's parameters in LettingAgent class. When I compiled, the error is occured in the if line where it says non-static method like getlocation() can't be referenced from static context. /** * Java coursework on class property which present detail information about the property public class Property { // instance variables of class property. private String address; private char location; private double monthlyRent; private int numberOfBedrooms; private boolean occupied; private String tenantName; /** * Constructor for object of class Property with required parameters. */ public Property( String addressinput, char locationinput, double Rentinput, int Bedsinput ) { //initialise the instance variables or fields of property class. address = addressinput; location = locationinput; monthlyRent = Rentinput; numberOfBedrooms = Bedsinput; occupied = false; tenantName = ""; } /** * Return the address of the property */ public String getAdress( ) { return address; } /** * Return the location of the property */ public char getLocation( ) { return location; } /** * Return the monthlyRent of the property */ public double getmonthlyRent( ) { return monthlyRent; } /** * Return the numberOfBedrooms of the property */ public int getnumberOfBedrooms( ) { return numberOfBedrooms; } /** * Return the occupied value of the property */ public boolean isoccupied( ) { return occupied; } /** * Return the tenant's name of the property */ public String gettenantName( ) { return tenantName; } /** * Set the monthly rent to a new value */ public void setmonthlyRent( double newRent ) { monthlyRent = newRent; } /** * Adding tenant's name to the property */ public void addtenantName(String newTenant) { if(occupied == false) { tenantName = newTenant; occupied = true; } else { System.out.println(" The property is already occupied"); } } /** * Removing tenant's name of the property */ public void removetenantName( ) { if( occupied == true) { tenantName = ""; occupied = false; } else { System.out.println(" The property is new and not occupied"); } } /** * Print all the property attributes */ public void printProperty( ) { //simulate the printing of the property attributes. System.out.println( "The details of the property are as follow" ); System.out.println("Address:" + address ); switch(location){ case 'n': case 'N': System.out.println("Location: North london" );break; case 's': case 'S': System.out.println("Location: South london" );break; case 'e': case 'E': System.out.println("Location: East london" );break; case 'w': case 'W': System.out.println("Location: West london" ); } System.out.println("Monthly-Rent:" + monthlyRent ); System.out.println("Number of Bedrooms:" + numberOfBedrooms ); System.out.println("Status of property:" + occupied ); if(occupied == true) { System.out.println("Tenant Name:" + tenantName ); } else { System.out.println("Property is empty at moment" ); } } } LettingAgent Class (calling class) import java.util.ArrayList; /** * Write a description of class LettingAgent here. */ public class LettingAgent { // instance variables of LettingAgent Class. private ArrayList<Property>agproperty; private int Propnumber; /** * Constructor for objects of class LettingAgent */ public LettingAgent() { // initialise instance variables agproperty = new ArrayList<Property>(); Propnumber = 0; } /** * Return the property number of the Class LettingAgent. */ public int getPropnumber(){ return Propnumber; } /** *Method to add new property to the class LettingAgent via class Property. */ public void addNewProperty(String addressinput, char locationinput, double Rentinput, int Bedsinput) { // put your code here Property newProperty = new Property(addressinput,locationinput,Rentinput,Bedsinput); agproperty.add(newProperty); } /** * @Description Method for removing the propety from the class LettingAgent. * @param int propnumber */ public void removalOfProperty(int Propnumber) { // initialise instance variables if( Propnumber<agproperty.size()){ agproperty.remove(Propnumber); System.out.println("The property has been removed"); } else{ System.out.println("The Property number is not valid"); } } /** * Method for adding tenant to the property within class LettingAgent via class Property. */ public void addTenant(int Propnumber, String newName, Property newProperty) { // initialise instance variables if( Propnumber<agproperty.size()){ agproperty.get(Propnumber); newProperty.addtenantName(newName); } else{ System.out.println("The Property number is not valid"); } } /** * Method for removing tenant from the class LettingAgent via Property class. */ public void removeTenant(int Propnumber,Property newProperty) { // initialise instance variables if( Propnumber<agproperty.size()){ agproperty.get(Propnumber); newProperty.removetenantName( ); } else{ System.out.println("The Property number is not valid"); } } /** *Method for searching property within the LettingAgent class. */ public void searchProperty(String Address) { // initialise instance variables for(Property Property : agproperty){ if (agproperty.get(Propnumber).equals( Address)){ System.out.println("The details of the property is as follow"+ Property); } else{ System.out.println("The property is not in the Letting agent's Stock"); } } } /** * Method for printing unoccupied property of the class LettingAgent. */ public void printListOfUnoccupiedProperty( char Location, double maxmonthlyRent, int miniNoBeds) { // initialise instance variables for(Property property : agproperty){ if((Property.getLocation().equals(Location))&&(Property.get(monthlyRent).equals(maxmonthlyRent))&&(agproperty.get(numberOfBedrooms).equals(miniNoBeds))){ System.out.Println(Propnumber); Property.printProperty(); } else{ System.out.println("The Property number is not valid"); } } } } A: In the last method you define (formatted below): /** * Method for printing unoccupied property of the class LettingAgent. */ public void printListOfUnoccupiedProperty(char Location, double maxmonthlyRent, int miniNoBeds) { // initialise instance variables for (Property Property : agproperty) { if ((Property.getLocation().equals(Location)) && (Property.get(monthlyRent).equals(maxmonthlyRent)) && (agproperty.get(numberOfBedrooms).equals(miniNoBeds))) { System.out.Println(Propnumber); Property.printProperty(); } else { System.out.println("The Property number is not valid"); } } } on the line: && (Property.get(monthlyRent).equals(maxmonthlyRent)) you're calling the get method of the Property variable. I think that should be Property.getMonthlyRent(). One other thing, in Java you should name your variables differently than their class names. I would use something like for (Property property : agproperty) { ... I know it's a small change, but it makes a big difference in the readability of your code. You can read about other Java code conventions in Code Conventions for the Java Programming Language.
[ "stackoverflow", "0003041273.txt" ]
Q: What's special about mouse capture and middle mouse button in WPF? When I call CaptureMouse() in response to a MouseDown from the middle mouse button, it will capture and then release the mouse. Huh? I've tried using Preview events, setting Handled=true, doesn't make a difference. Am I not understanding mouse capture in WPF? Here's some minimal sample code that reproduces the problem. // TestListBox.cs using System.Diagnostics; using System.Windows.Controls; namespace Local { public class TestListBox : ListBox { public TestListBox() { MouseDown += (_, e) => { Debug.WriteLine("+MouseDown"); Debug.WriteLine(" Capture: " + CaptureMouse()); Debug.WriteLine("-MouseDown"); }; GotMouseCapture += (_, e) => Debug.WriteLine("GotMouseCapture"); LostMouseCapture += (_, e) => Debug.WriteLine("LostMouseCapture"); } } } Generating a default WPF app that has this for its main window will use the test class: <Window x:Class="Local.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Local" Title="MainWindow" Height="350" Width="525"> <local:TestListBox> <ListBoxItem>1</ListBoxItem> <ListBoxItem>2</ListBoxItem> <ListBoxItem>3</ListBoxItem> <ListBoxItem>4</ListBoxItem> </local:TestListBox> </Window> Upon clicking the middle button down, I get this output: +MouseDown GotMouseCapture LostMouseCapture Capture: True -MouseDown So I'm calling CaptureMouse, which in turn grabs and then releases capture, yet returns true that capture was successfully acquired. What's going on here? Is it possible that this is something with my Logitech mouse driver doing something goofy, trying to initiate 'ultrascroll' or something? A: This can be diagnosed by setting your debugger to break on UIElement.ReleaseMouseCapture() method and looking at the call stack. If you do this you will find that it is ListBox's OnMouseMove that is causing the problem. So all you have to do to is override OnMouseMove and not call the base class if the middle button is down: public class TestListBox : ListBox { protected override void OnMouseMove(MouseEventArgs e) { if(Mouse.MiddleButton!=MouseButtonState.Pressed) base.OnMouseMove(e); } }
[ "stackoverflow", "0010016887.txt" ]
Q: inheritance, scope, and template constructors in c++ I have a quick question. I am writing C++ code; I have two classes in the same file. One inherits from the other, and I am trying to use templates to make the classes more general. Here is the file for the base class: template<class E> // this is the class we will execute upon class Exec{ protected: typedef void (*Exe)(E*); // define a function pointer which acts on our template class. Exe* ThisFunc; // the instance of a pointer function to act on the object E* ThisObj; // the object upon which our pointer function will act public: Exec(Exe* func, E* toAct){ThisFunc = func; ThisObj=toAct;} Exec(){;} // empty constructor void Execute(){ThisFunc(ThisObj);} // here, we pass our object to the function }; And here is the inherited class: template<class E> // this is the class we will execute upon class CondExec : protected Exec<E>{ // need the template! protected: typedef bool (*Cond)(E*); // a function returning a bool, taking a template class Cond* ThisCondition; public: CondExec(Exe* func, E* toAct,Cond* condition): Exec<E>(func,toAct){ThisCondition=condition;} void ExecuteConditionally(){ if (ThisCondition(ThisObj)){ Execute(); } } }; However, when I try this, I get the following errors: executables.cpp:35: error: expected `)' before ‘*’ token executables.cpp: In member function ‘void CondExec<E>::ExecuteConditionally()’: executables.cpp:37: error: ‘ThisObj’ was not declared in this scope executables.cpp:37: error: there are no arguments to ‘Execute’ that depend on a template parameter, so a declaration of ‘Execute’ must be available It seems that the Exec (ie: the base) class isn't getting properly declared; if I include the typedef and the instance variables from the base class in the inherited class, I don't get these errors. However, if I include everything from the base class, then its pointless to use inheritance! I've tried doing a "declaration" of the base class, as some have recommended (ie: class Base;), but that doesn't seem to help. I've been doing some google-fu on this for some hours; if anyone has any ideas, that'd be super! A: You need to say typename Exec<E>::Exe. Because the baseclass is dependent. Same for Execute, you need to qualify the call with the baseclass name in front: Exec<E>::Execute();. Otherwise those unqualified names ignore the dependent base class.
[ "mathematica.stackexchange", "0000014160.txt" ]
Q: Plotting a Phase Portrait I'm trying to plot a phase portrait for the differential equation $$x'' - (1 - x^2) x' + x = 0.5 \cos(1.1 t)\,.$$ The primes are derivatives with respect to $t$. I've reduced this second order ODE to two first order ODEs of the form $ x_1' = x_2$ and $x_2' - (1 - x_1^2) x_2 + x_1 = 0.5 \cos(1.1 t)$. Now I wish to use mathematica to plot a phase portrait. Unfortunately, I'm unsure of how to do this because of the dependence of the second equation on an explicit $t$. A: again just a slight modification from the documentation splot = StreamPlot[{y, (1 - x^2) y - x}, {x, -4, 4}, {y, -3, 3}, StreamColorFunction -> "Rainbow"]; Manipulate[ Show[splot, ParametricPlot[ Evaluate[ First[{x[t], y[t]} /. NDSolve[{x'[t] == y[t], y'[t] == y[t] (1 - x[t]^2) - x[t] + 0.5 Cos[1.1 t], Thread[{x[0], y[0]} == point]}, {x, y}, {t, 0, T}]]], {t, 0, T}, PlotStyle -> Red]], {{T, 20}, 1, 100}, {{point, {3, 0}}, Locator}, SaveDefinitions -> True] Or just to show off (again a rip off from the documentation) splot = LineIntegralConvolutionPlot[{{y, (1 - x^2) y - x}, {"noise", 1000, 1000}}, {x, -4, 4}, {y, -3, 3}, ColorFunction -> "BeachColors", LightingAngle -> 0, LineIntegralConvolutionScale -> 3, Frame -> False]; Manipulate[ Show[splot, ParametricPlot[ Evaluate[ First[{x[t], y[t]} /. NDSolve[{x'[t] == y[t], y'[t] == y[t] (1 - x[t]^2) - x[t]+0.5 Cos[1.1 t], Thread[{x[0], y[0]} == point]}, {x, y}, {t, 0, T}]]], {t, 0, T}, PlotStyle -> White]], {{T, 20}, 1, 100}, {{point, {3, 0}}, Locator}, SaveDefinitions -> True] A: The EquationTrekker package is a great package for plotting and exploring phase space << EquationTrekker` EquationTrekker[x''[t] - (1 - x[t]^2) x'[t] + x[t] == 0.5 Cos[1.1 t], x[t], {t, 0, 10}] This brings up a window where you can right click on any point and it plots the trajectory starting with that initial condition: You can do more as well, such as add parameters to your equations and see what happens to the trajectories as you vary them: EquationTrekker[x''[t] - (1 - x[t]^2) x'[t] + x[t] == a Cos[\[Omega] t], x[t], {t, 0, 10}, TrekParameters -> {a -> 0.5, \[Omega] -> 1.1} ] A: You can solve the equation with (you might want to change the initial conditions) : sol[t_] = NDSolve[{x''[t] - (1 - x[t]^2) x'[t] + x[t] == 0.5 Cos[1.1 t], x[0] == 0, x'[0] == 1}, x[t], {t, 0, 10}][[1, 1, 2]] Now you can use the solution as any other function; in particular, you can plot it versus its derivative : ParametricPlot[{sol[t], sol'[t]}, {t, 0, 10}]
[ "stackoverflow", "0045505183.txt" ]
Q: Is compact() and with() interchangeable? There seems to be two most used way to pass data to the view and though there are several questions asking the difference between the two functions, I don't see a single stackoverflow answer that explains whether they are interchangeable, which is used more often and if they are not interchangeable, in what situation to use the two functions. A: compact() is a standard PHP Function that builds an array from a list of variables, assigning the variable name as the array element key, and the variable value as the array element value. It can be used as a convenient way of passing variables to a view in Laravel, because Laravel's View::make() will accept a second argument of an array of key/value pairs. You could just as easily specify an array of key/value pairs, but PHP's compact() provides an easy way of doing this. $x = "Hello"; $y = "world"; $view = View::make('myViewName', compact('x', 'y'); is the same as $x = "Hello"; $y = "world"; $view = View::make('myViewName', ['x' => $x, 'y' => $y]); but with compact() your variables must already exist. Specifying an array manually is more flexible because you could do $x = "Hello"; $y = "world"; $view = View::make('myViewName', ['salutation' => $x, 'addressTo' => $y]); which would give variables called $salutation and $addressTo inside your blade template, even though your original variables were just called $x and $y. or you can even do $view = View::make('myViewName', ['salutation' => "Hello", 'addressTo' => "world"]); with() is Laravel-specific, and (in this View building context) allows you to specify individual keys and values to be passed to the view. The main difference is that you can specify the key name as whatever you want (in much the same way as using your own-built array as a second argument to View::make()), and the value can be a direct return from a function call. $x = "Hello"; $y = "world"; $view = View::make('myViewName')->with('x', $x)->with('y', $y); or $view = View::make('myViewName')->with('x', "Hello")->with('y', "World"); or $view = View::make('myViewName') ->with('salutation', "Hello") ->with('addressTo', "World"); It's basically the same as passing a user-built array to View::make(), but arguably more readable In both cases, the key/value pairs (whether specified via the second argument to View::make() or using with()) are extracted inside the blade template, with the key being used for the element name. The two approaches can even be used together.
[ "stackoverflow", "0063531235.txt" ]
Q: Can bash be used to rename by pattern? I have files: alpha_123_abc_file.txt beta_456_def_file.txt gamma_789_ghi_file.txt Is there a way to rename all to cut the parts after the first _ character? To become: 123_abc_file.txt 456_def_file.txt 789_ghi_file.txt I've looked into the perl tool but I an unsure if it has the capability to search out a pattern like that. A: for file in *_*; do echo mv -- "$file" "${file#*_}"; done Remove the echo when you're done testing and ready to actually do the mv.
[ "math.stackexchange", "0002733876.txt" ]
Q: Proof of uniqueness to the right There is a function $f: \mathbb{R} \times \mathbb{R} \rightarrow \mathbb{R}$ given. This function is non-increasing, so that we have: $$\forall\,{x_1, x_2 \in \mathbb{R}},\; x_1< x_2 \implies f(t, x_1) - f(t, x_2) \ge 0.$$ There is also a differential equation given with the initial condition: $$\begin{cases} x'=f(t,x)\\x(t_0) = x_0.\end{cases}$$ Let's consider two solutions of the equation above: $\phi_1, \phi_2$. To show uniqueness, it should be proved that $\phi_1 \equiv\phi_2$. This is my attempt: assume $\phi_1 \not\equiv \phi_2$ and $\phi_1 < \phi_2$. Because both $\phi_1$ and $\phi_2$ are solutions I can write: $$\begin{cases} \phi_1'=f(t,\phi_1)\\\phi(t_0) = x_0\end{cases}$$ and also $$\begin{cases} \phi_2'=f(t,\phi_2)\\\phi_2(t_0) = x_0.\end{cases}$$ Now I can consider this $$\phi_1' - \phi_2' = f(t,\phi_1) - f(t,\phi_2) \ge 0,$$ thus $$\phi_1' \ge \phi_2'.$$ By integrating both sides of the equation above I do get $$\phi_1 - \phi_2 \ge C.$$ However that doesn't lead me to anything useful. I was trying to show that $\phi_1$ and $\phi_2$ differ by at most a constant and then use Picard's theorem. Unfortunately my attempt failed. I would appreciate any hints or tips. A: You get $$ \frac{d}{dt}[ϕ_1(t)-ϕ_2(t)]^2=2[ϕ_1(t)-ϕ_2(t)][f(t,ϕ_1(t))-f(t,ϕ_2(t))]\le 0 $$ by the non-increasing assumption. Thus $$ [ϕ_1(t)-ϕ_2(t)]^2\le[ϕ_1(t_0)-ϕ_2(t_0)]^2~\text{ for }~ t>t_0 $$ with the obvious consequence.
[ "stackoverflow", "0051098194.txt" ]
Q: Is any library of nodejs work with GitHub API v4 exist? Thank you guys cause reading my question. The title is exactly what i wanna known. Hope it do not cost your time much. A: Some of the most common graphql client are graphql.js and apollo-client. You can also use the popular request module. The graphql API is a single POST endpoint on https://api.github.com/graphql with a JSON body consisting of the query fields and the variables fields (if you have variables in the query) Using graphql.js const graphql = require('graphql.js'); var graph = graphql("https://api.github.com/graphql", { headers: { "Authorization": "Bearer <Your Token>", 'User-Agent': 'My Application' }, asJSON: true }); graph(` query repo($name: String!, $owner: String!){ repository(name:$name, owner:$owner){ createdAt } } `)({ name: "linux", owner: "torvalds" }).then(function(response) { console.log(JSON.stringify(response, null, 2)); }).catch(function(error) { console.log(error); }); Using apollo-client fetch = require('node-fetch'); const ApolloClient = require('apollo-client').ApolloClient; const HttpLink = require('apollo-link-http').HttpLink; const setContext = require('apollo-link-context').setContext; const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache; const gql = require('graphql-tag'); const token = "<Your Token>"; const authLink = setContext((_, { headers }) => { return { headers: { ...headers, authorization: token ? `Bearer ${token}` : null, } } }); const client = new ApolloClient({ link: authLink.concat(new HttpLink({ uri: 'https://api.github.com/graphql' })), cache: new InMemoryCache() }); client.query({ query: gql ` query repo($name: String!, $owner: String!){ repository(name:$name, owner:$owner){ createdAt } } `, variables: { name: "linux", owner: "torvalds" } }) .then(resp => console.log(JSON.stringify(resp.data, null, 2))) .catch(error => console.error(error)); Using request const request = require('request'); request({ method: 'post', body: { query: ` query repo($name: String!, $owner: String!){ repository(name:$name, owner:$owner){ createdAt } } `, variables: { name: "linux", owner: "torvalds" } }, json: true, url: 'https://api.github.com/graphql', headers: { Authorization: 'Bearer <Your Token>', 'User-Agent': 'My Application' } }, function(error, response, body) { if (error) { console.error(error); throw error; } console.log(JSON.stringify(body, null, 2)); });
[ "stackoverflow", "0047503566.txt" ]
Q: Overriding object method with the Python3 C API I'm working on porting the core functionality of a project from python to C, but want to retain the ability to call into modular Python components. So I'm embedding the python interpreter in my project. I've gotten to the point where calls can be made on both the C, and Python side to the other end, and shared data is converted and correctly handled. However, I seem unable to override methods in my defined Python classes. Rather, there's no errors, however self is not set for my PyCFunction. Basic example code is like: component.py class Component(object): def my_function(self): print("orig function") class CompObj(Component): def test(self): self.my_function() example.c #include <Python.h> static PyObject *my_function_override(PyObject *self, PyObject *args) { printf("Override method %p\n", self); return Py_None; } PyMethodDef override_method = { "my_function", (PyCFunction)my_function_override, METH_VARARGS, NULL }; int main () { wchar_t *program; PyObject *sys_path, *module_path; PyObject *pModule, *pCompObj, *pCompObjInst; PyObject *cfunc, *cmeth; program = Py_DecodeLocale("exmaple", NULL); Py_SetProgramName(program); Py_InitializeEx(0); sys_path = PySys_GetObject("path"); module_path = PyUnicode_FromString("/Users/dwalker/ex"); PyList_Append(sys_path, module_path); Py_DECREF(module_path); if ((pModule = PyImport_ImportModule("component")) == NULL) { printf("No Module\n"); return -1; } pCompObj = PyObject_GetAttrString(pModule, "CompObj"); pCompObjInst = PyObject_CallFunction(pCompObj, NULL); cfunc = PyCFunction_New(&override_method, NULL); cmeth = PyMethod_New(cfunc, pCompObjInst); PyObject_SetAttrString(pCompObjInst, "my_function", cmeth); PyObject_CallMethod(pCompObjInst, "test", NULL); Py_Finalize(); PyMem_RawFree(program); return 0; } CMakeLists.txt set(SRC_CORE example.c ) add_executable(example ${SRC_CORE}) set_property(TARGET example PROPERTY C_STANDARD 90) find_package(PythonInterp) find_package(PythonLibs) include_directories(${PYTHON_INCLUDE_PATH}) target_link_libraries(example ${PYTHON_LIBRARIES}) So, here after I build and run this I get the output: Override method 0x0 The override method is being called, but the instance is not being passed as the first self argument. I assume I'm doing something wrong binding the method to the instance. For what it's worth, I've also tried similar execution paths, by setting the method via PyInstanceMethod_New to pCompObj and not the instance. But no matter what, I'm unsure how to get the self value correctly passed. A: After more playing, and finally looking at the CPython source (https://github.com/python/cpython/blob/master/Objects/methodobject.c) it became obvious that using PyMethod_New(PyObject *func, PyObject *self) and setting this return was not correct. The PyCFunction call accepts two arguments, the latter being the instance to use for self. So in my example, changed to the following we have success: pCompObj = PyObject_GetAttrString(pModule, "CompObj"); pCompObjInst = PyObject_CallFunction(pCompObj, NULL); cfunc = PyCFunction_New(&override_method, pCompObjInst); PyObject_SetAttrString(pCompObjInst, "my_function", cfunc); Py_DECREF(cfunc); So this seems to be what I'm intending to do, however, anyone much more versed in the Python C API can follow up with a "more correct" answer.
[ "stackoverflow", "0009784351.txt" ]
Q: Jsf2.0 forwarding page error without parameter Hello i have error when i am forwarding page without parameter. that is happen only in constructor. not happening with methods. like public EditNewsBean() throws Exception { log.info("In EditNewsBean Constructor"); Object o1=request.getParameter("countryCode"); Object o2=request.getParameter("editNewsID"); if(o1==null || o2==null || o1.toString().length()==0 || o2.toString().length()==0) { FacesContext.getCurrentInstance().getExternalContext().redirect("/HeWebEV/admin/ManageNews.jsf"); } setEditNews(Facade.othfac().getTVecNewsFindAllValidTill(request.getParameter("countryCode").toString(),Integer.valueOf(request.getParameter("editNewsID")))); } and when i am passing request form without parameter i am getting error like, com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: com.efacec.sg.he.plugme.admin.EditNewsBean. at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:193) at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102) at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409) at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269) at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244) at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116) at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176) at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203) at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:61) at org.apache.el.parser.AstValue.getValue(AstValue.java:107) at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186) at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109) at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194) at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182) at javax.faces.component.UIOutput.getValue(UIOutput.java:169) at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164) at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:312) at com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(GridRenderer.java:185) at com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(GridRenderer.java:129) at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845) at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:59) at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:47) at org.primefaces.component.panel.PanelRenderer.encodeContent(PanelRenderer.java:185) at org.primefaces.component.panel.PanelRenderer.encodeMarkup(PanelRenderer.java:108) at org.primefaces.component.panel.PanelRenderer.encodeEnd(PanelRenderer.java:55) at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763) at javax.faces.render.Renderer.encodeChildren(Renderer.java:168) at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401) at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190) at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) Caused by: java.lang.IllegalStateException at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:435) at com.sun.faces.context.ExternalContextImpl.redirect(ExternalContextImpl.java:576) at com.efacec.sg.he.plugme.admin.EditNewsBean.<init>(EditNewsBean.java:33) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at java.lang.Class.newInstance0(Class.java:355) at java.lang.Class.newInstance(Class.java:308) at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188) ... 63 more 15:07:00,342 INFO [context] Exception when handling error trying to reset the response. com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: com.efacec.sg.he.plugme.admin.EditNewsBean. at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:193) at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102) at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409) at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269) at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244) at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116) at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176) at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203) at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:61) at org.apache.el.parser.AstValue.getValue(AstValue.java:107) at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186) at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109) at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194) at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182) at javax.faces.component.UIOutput.getValue(UIOutput.java:169) at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164) at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:312) at com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(GridRenderer.java:185) at com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(GridRenderer.java:129) at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845) at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:59) at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:47) at org.primefaces.component.panel.PanelRenderer.encodeContent(PanelRenderer.java:185) at org.primefaces.component.panel.PanelRenderer.encodeMarkup(PanelRenderer.java:108) at org.primefaces.component.panel.PanelRenderer.encodeEnd(PanelRenderer.java:55) at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763) at javax.faces.render.Renderer.encodeChildren(Renderer.java:168) at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401) at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190) at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) Caused by: java.lang.IllegalStateException at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:435) at com.sun.faces.context.ExternalContextImpl.redirect(ExternalContextImpl.java:576) at com.efacec.sg.he.plugme.admin.EditNewsBean.<init>(EditNewsBean.java:33) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at java.lang.Class.newInstance0(Class.java:355) at java.lang.Class.newInstance(Class.java:308) at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188) ... 63 more 15:07:00,366 ERROR [[Faces Servlet]] Servlet.service() for servlet Faces Servlet threw exception java.lang.IllegalStateException at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:435) at com.sun.faces.context.ExternalContextImpl.redirect(ExternalContextImpl.java:576) at com.efacec.sg.he.plugme.admin.EditNewsBean.<init>(EditNewsBean.java:33) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at java.lang.Class.newInstance0(Class.java:355) at java.lang.Class.newInstance(Class.java:308) at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188) at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102) at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409) at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269) at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244) at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116) at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176) at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203) at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:61) at org.apache.el.parser.AstValue.getValue(AstValue.java:107) at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186) at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109) at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194) at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182) at javax.faces.component.UIOutput.getValue(UIOutput.java:169) at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164) at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:312) at com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(GridRenderer.java:185) at com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(GridRenderer.java:129) at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845) at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:59) at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:47) at org.primefaces.component.panel.PanelRenderer.encodeContent(PanelRenderer.java:185) at org.primefaces.component.panel.PanelRenderer.encodeMarkup(PanelRenderer.java:108) at org.primefaces.component.panel.PanelRenderer.encodeEnd(PanelRenderer.java:55) at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763) at javax.faces.render.Renderer.encodeChildren(Renderer.java:168) at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401) at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190) at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) 15:07:00,405 ERROR [[localhost]] Exception Processing ErrorPage[exceptionType=java.lang.Exception, location=/error.xhtml] java.lang.IllegalStateException: Cannot reset buffer after response has been committed at org.apache.catalina.connector.Response.resetBuffer(Response.java:684) at org.apache.catalina.connector.Response.resetBuffer(Response.java:705) at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:409) at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:270) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) A: com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: com.efacec.sg.he.plugme.admin.EditNewsBean. ... java.lang.IllegalStateException: Cannot reset buffer after response has been committed The bean is apparently been referenced pretty "late" in the view. A part of the view is already been sent (committed) to the response during render response phase. It's too late then to change the response into a redirect. The server cannot take the already sent bytes back from the client. The server will throw an IllegalStateException and the client will end up with a halfbaked response. You need to perform the redirect before any byte is been sent to the client in the response. You can achieve this with a <f:event type="preRenderView"> listener. Add this somewhere to the view (most self-documenting would be to put this in the top of the template client): <f:event type="preRenderView" listener="#{editNewsBean.init}" /> And move the constructor's code into that method. public void init() { // ... } Unrelated to the concrete problem, don't forget to add an else {} block for setEditNews(). You don't want that it is called when the condition is eligible for the redirect, right? You would otherwise possibly face a NullPointerException. Also, that toString() on getParameter() is completely unnecessary. Also, you should be gathering request parameters by <f:viewParam> or @ManagedProperty or at least ExternalContext#getRequestParameterMap(). You seem to have assigned HttpServletRequest as an instance variable of the bean which is a very bad idea. Finally, you're performing a redirect here, not a forward.
[ "stackoverflow", "0024652298.txt" ]
Q: How to reduce the time interval for didRangeBeacons method I am working on a project involving iBeacons. I am observing that the didRangeBeacons method is called in 1 second interval. Is there any way to reduce this time interval? My project requires low latency proximity detection and I was wondering how this could be achieved. A: No, you cannot reduce this interval on iOS because it is baked in to the CoreLocation APIs. You can do so on Android, or you could do something similar with lower-level CoreBluetooth APIs on iOS, but using CoreBluetooth is a bigger roll-your-own project than can be answered here. While I am unsure of your use case, you should consider that reducing the interval might not help. Beacons only send out advertisements at a certain frequency (typically 1-10Hz). If you are using a beacon transmitting at 10Hz, you could potentially get a detection in 1/10 of a second. But if you need a distance estimate, this fluctuates greatly with each packet, so you really need to average the measurements over many samples anyway. Also, consider that a CoreBluetooth-based solution would only be able to do faster ranging when the app is in the foreground. Background processes on iOS have a whole different set of delay challenges. Finally, any CoreBluetooth solution could not work with standard iBeacons because iOS sandboxes the ability to read iBeacon identifiers with anything other than CoreLocation. So you would need to build a custom beacon.
[ "salesforce.stackexchange", "0000167357.txt" ]
Q: Insert/Save CustomObject and account fields using visualforce page? For external users, we will be sending a link in the email to fill survey and when they click submit. A record should be created/saved into salesforce custom Object(Survey__c) This Survey object has a lookup field which is Account, this should also be saved. How do I achieve this? Below is my code: VisualForce Page <apex:page controller="myAudit"> <apex:form > <apex:pageblock > <apex:inputField value="{!account.name}"/> <apex:inputText id="Survey" value="{!txtSurvey}"/> <apex:commandButton action="{!save}" value="save"/> </apex:pageblock> </apex:form> </apex:page> Controller public class myAudit { public String account { get; set; } public String txtAuditQ { get; set; } public PageReference save() { //Add your custom logic to update specific fields here Survey__c aq = new Survey__c(); aq.Name = txtSurvey; aq.account__c = account; insert aq; return null; } } } A: According to your code aq.account__c = account; You are assigning Account which is string to the lookup field. Thats why it is not giving you AccountId after saving. Small changes are suggested. Declare Account as object instead of String public Account accountObj { get; set; } In the visualforce, for <apex:inputField> use Account.Id, which will give you Account Lookup. <apex:inputField value="{!accountObj.Id}"/> In the Controller make this change aq.account__c = accountObj.Id; Controller public class myAudit { public Account accountObj { get; set; } public String txtAuditQ { get; set; } public PageReference save() { //Add your custom logic to update specific fields here Survey__c aq = new Survey__c(); aq.Name = txtSurvey; aq.account__c = accountObj.Id; insert aq; return null; } } } Finally, since you are performing DML so use try-catch block as a matter of best practices.
[ "stackoverflow", "0013644098.txt" ]
Q: How can I know tesseract has been set up successfully I set up my tesseract 3.01 in visual studio 2008 according to http://code.google.com/p/tesseract-ocr/wiki/ReadMePre3 No errors report in compilication. Then a console command window saying clustering flash by, then disappear. If I have successfully installed it, where should I put tesseract examples? Is it Ok to put them under the vs2008 folder? Can anyone send me an example? A: After checking out the complete source from Tesseract SVN repositoty, open tesseract solution from vs2008 folder, select LIB-Release configuration, and build. The .exe output files can be found in vs2008\LIB_Release folder. You can move them to the parent folder of vs2008, where there are some sample images and tessdata, open a command prompt, and run your test from there. tesseract phototest.tif out
[ "unix.stackexchange", "0000173715.txt" ]
Q: Split the large files into sub files. How to do this process? I have a large file in my unix box with 2 Gb. The files contains the xml lines. I want to split the files into say 10 files say each file is now of 204 MB ( approx ) so that combining the 10 files should give me back the original file which is of 2Gb. Note that the content should be reproducible when I merge the 10 files with the original file. How one should do this in unix? A: There is a split command: ~$ split --help Usage: split [OPTION]... [INPUT [PREFIX]] Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is `x'. With no INPUT, or when INPUT is -, read standard input. ... -n, --number=CHUNKS generate CHUNKS output files. ... CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines l/K/N output Kth of N to stdout without splitting lines r/N like `l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout So you only have to do ~$ split -n10 -d myfile mySubFile_ That create 10 files with numerical suffixes (-d option) with suffixe mySubFile_ ~$ ls -1t mySubFile_00 mySubFile_01 mySubFile_02 mySubFile_03 mySubFile_04 mySubFile_05 mySubFile_06 mySubFile_07 mySubFile_08 mySubFile_09 that you can recombine with cat mySubFile_* > myfile
[ "stackoverflow", "0044314757.txt" ]
Q: HttpClient GetAsync Failure when ARM CPU is Selected While trying to call a Rest Service, I keep getting the following error when the CPU configuration is set to ARM An error occurred while sending the request. The text associated with this error code could not be found.The server name or address could not be resolved Switching to Any CPU or x86 for example, and the call succeeds. A sample of what the code might look like: System.Uri uri = new Uri("http://servername/__/__.svc/ID/123"); using (var client = new System.Net.Http.HttpClient()) { try { var response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { //handle success } else { //handle failure } } catch (HttpRequestException exc) { throw new HttpRequestException(); } } How to interpret this observation to solve the problem? Note: App Private Networks (Client & Server) under Capabilities in the Package.appxmanifest is enabled. Calling a service without checking this capability used to cause the same error. Update with StackTrace at System.Net.Http.HttpClientHandler.d__86.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Net.Http.HttpClient.d__58.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at ProjectName.Views.MainPage.d__4.MoveNext() A: Story short, using the server IP address instead of the host/server name, solved the problem. Otherwise, resolving the name might require editing the hosts file as described in here.
[ "stackoverflow", "0005599402.txt" ]
Q: How can I get devise to go to use one page as root if the user is logging in but another when they are logging out? I'm working on a Rails 3 application that uses devise for user authentication. I would like the user to only see the splash/signup page when they first visit the site but be sent to the login page if they log out or time out, as follows: Splash page Click on login link Login page Supply proper login credentials User's dashboard Click on logout link or user times out Login page (not splash page) A: Take a look in the devise wiki: How To: Change the redirect path after destroying a session i.e. signing out
[ "stackoverflow", "0007783275.txt" ]
Q: How to get friends in order of number of mutual friends? I am developing a Facebook application. I want to know how I can get friends in the order of number of mutual friends. Is it possible with FQL or any other method? A: Update I can't find a way to do it in one request using graph API but it can be done in Ruby by getting friends list then sending request for each friend using User context like this example Original answer Here is the FQL query to be used Which is working only for api versions < v2.1 SELECT uid, mutual_friend_count from user where uid in (SELECT uid2 FROM friend WHERE uid1=me()) ORDER BY mutual_friend_count desc you can try it in the explorer https://developers.facebook.com/tools/explorer?method=GET&path=fql%3Fq%3DSELECT%20uid%2C%20mutual_friend_count%2C%20friend_count%20from%20user%20where%20uid%20in%20%28SELECT%20uid2%20FROM%20friend%20WHERE%20uid1%3Dme%28%29%29%20ORDER%20BY%20mutual_friend_count%20desc
[ "stackoverflow", "0015260488.txt" ]
Q: Marionette.js appRouter not firing on app start I am currently integrating Marionette into an existing Backbone application. I have an existing Backbone router in place, but am trying to implement a Marionette.AppRouter to take its place. The problem is that on a "Hard Refresh" on the url that the new Marionette router should pick up, it does not fire. If I navigate to another page, then go back to the url that did not fire on a hard refresh, it fires correctly. I cannot figure out why it works after I have navigated to another page and back again. Here is my code sample: TestApp = new Backbone.Marionette.Application(); var testAppController = { testLoadPage: function(){ console.log('testLoadPage Fired'); //<---- DOES NOT FIRE ON HARD REFRESH } }; TestAppRouter = Backbone.Marionette.AppRouter.extend({ appRoutes: { "!/:var/page": "testLoadPage", "!/:var/page/*path": "testLoadPage" }, controller: testAppController, route: function(route, name, callback) { return Backbone.Router.prototype.route.call(this, route, name, function() { if (!callback) callback = this[name]; this.preRoute(); this.trigger.apply(this, ['beforeroute:' + name].concat(_.toArray(arguments))); callback.apply(this, arguments); }); }, preRoute: function() { app.showLoader(name, arguments); } }); TestApp.addRegions({ contentContainer: '#container' }); TestApp.addInitializer(function(options){ new TestAppRouter(); }); TestApp.start(); When I load the page: http://mysamplesite.com/#!/123/page directly, the Marionette router does not fire as it should. However, if I load the page: http://mysamplesite.com/#!/123 and then navigate to http://mysamplesite.com/#!/123/page, the Marionette router fires correctly. Any ideas? A: Did you call Backbone.history.start() after creating your router instance? If not, you need to do that. Routers won't run until this is called in your app, and you can't call this until at least one route has been instantiated. I usually do this: TestApp.on("initialize:after", function(){ if (Backbone.history){ Backbone.history.start(); } }); hth
[ "stackoverflow", "0033884982.txt" ]
Q: How to hide only the back bar button item title in iOS objective c I know to hide the back bar button item. But I want to hide only the title of the bar button i.e. the back button is like this: "< Back". I want only the arrow not the name i.e. "<". How do I remove the "Back" and retain only the back arrow. Thanks, A: You can achieved this easily from storyboard, go to your specific view of storyboard for whom you want to show blank back button title with arrow. Then make sure you added navigation item in your specific view: Then on the right panel you can find: You just need to give some empty space in the back button box: And you are done. Hope it will help you thanks.