INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to extract string separated by comma with PHP? I need extract a string separated by comma or comma and space. Example: <?php //regexp $regexp = "/(select\s+(?<name>[a-z0-9]+)\s+(?<values>[^\d]+[a-z0-9]+\s*(\s*,|\s*$)))/"; //text $text = "select this string1,string_2,string_3 ,string_4, string5,string_6"; //prepare $match = array(); preg_match( $regexp , $text , $match ); //print var_dump( $match); ?> I created this regexp: (?<values>[^\d]+[a-z0-9]+\s*(\s*,|\s*$)) But this does not work perfectly. Thanks!
I suggest you to use something like `~(?|select ([^\W_]+) | *([^\W,]+) *,?)`, if you want to check that you obtain only alphanumeric characters. Example: $subject = 'select this string1,string_2,string_3 ,string_4, string5,string_6'; $pattern = '~(?|select ([a-z][^\W_]*+) | *+([a-z][^\W,_]*+) *+,?)~i'; preg_match_all($pattern, $subject, $matches); if (isset($matches[1])) { $name = array_shift($matches[1]); $strings = $matches[1]; } Or another way: $pattern = '~select \K[a-z][^\W_]*+| *+\K[a-z][^\W,]*+(?= *,?)~'; preg_match_all($pattern, $subject, $matches); if (isset($matches[0])) { $name = array_shift($matches[0]); $strings = $matches[0]; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, regex, recursion, preg match, pcre" }
Observable.next() is not a function Hi I'm new on angular. I don't know why I can't set new value in my Observable My code : resultJob: Observable<any> = Observable.of("PENDING"); ngOnInit() { this.resultJob.subscribe(result => { result.next("SUCCESS") result.complete() }) } This code return `result.next is not a function`
There is no next() on Observable; only on Subject and BehaviorSubject, which extends Subject (and both extend Observable). What you need to do is: resultJob: Subject<string> = new BehaviorSubject<string>("PENDING"); BehaviorSubject in contrast to Subject gets initialized with a first value that gets pushed in the stream. It seems to be what you want to do. Also result is of type string, not of type Observable. You want to call next() on resultJob, not on result (the element inside the stream). But I don't understand why you do that in the Subscribtion. You will get circular calls this way: you push a new element in the stream and react on its detection by pushing another one and so forth...
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 5, "tags": "angular, rxjs, observable" }
How do I disable the command 'stop' from doing anything? When I'm working on a Minecraft server I type 'stop' to stop the server, and sometimes I don't pay enough attention to gnome terminal and I type 'stop' when the server is already stopped, instead I get unity-settings-daemon stop/killed, process 1998 unsurprisingly some settings seem to stop working, Firefox shuts down and it's just generally annoying that this command is so easy for me to mis-run. Is there any way I can disable it?
Not "disable", but "mask". Note that `stop` is `/sbin/stop`. Look at your `$PATH` (`echo $PATH | tr ":" "\n"`). Anything named `stop` in a directory in your `PATH` that is _earlier_ will be executed instead. If `~/bin` is earlier, you could create `~/bin/stop` containing: #!/bin/bash echo "To really run 'stop', type '/sbin/stop`" exit 0 or Define an alias in your `~/.bashrc`: alias stop="echo \"To really run 'stop', type '/sbin/stop`\""
stackexchange-askubuntu
{ "answer_score": 3, "question_score": 0, "tags": "command line, upstart" }
WPF UserControl Transition I have a Main Window which has a Grid. On Button Click Events, I switch the children of the Grid between multiple UserControls. When I switch between these user controls I want to create a transition, something like fade or slide in etc. How can I do this?
You can do this using Expression Blend, and either creating your own, or using pre-made visual transitions. FluidMoveBehaviour is a common one for animating the removal and addition of objects to a content control. There are also some 'pseudo-3d' animations such as flip, rotate etc... <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "c#, wpf" }
Bundling the Windows Mono runtime with an application Regarding my earlier question about the Point of Mono on Windows, let's say that I develop an app against the windows mono runtime so that it will also run on Linux, OSX, etc.. and to make it more complicated, I use GTK# so that I don't have to deal with WinForms. Is there then an easy way to bundle the Windows Mono runtimes with my Windows version of the application so that it can all be installed at once? Or, is there no point to this? Once I develop against the Windows Mono runtime, would it still run fine against the MS .NET runtime? (I assume I would still need GTK# installed though).
The short answer is Yes. The things you should take care about while programming are 1. Not to use platform API 2. Don't hardcode directory & file name separators, i.e. don't hardcode file paths, but use appropraite class to obtain path separator then concat the names. 3. Keep in mind that file names on *nx are case sensitve and on Windows are not. While programming don't refer to the same file as log.txt and Log.txt but keep it all small. Other then that, if you created GTK# application on *nx system, you will be able to run it on Windows if you installed GTK# assembly, and vice-versa. I did this myself, and it worked like expected. I had a problem to find specific assembly dll version of GTK# on Windows and that took me few hours.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 8, "tags": "windows, mono" }
Trimming BOLD_CLOCKLOG table I am doing some maintenance on a database for an application that uses the Bold for Delphi object persistence framework. This database has been been in production for several years and several of the tables have grown quite large. One of them is the `BOLD_CLOCKLOG` which has something to do with Bold's transaction management. I want to trim this table (it is up to 1.2GB, with entries from Jan 2006). Can anyone confirm the system does not need this old information?
Bold_ClockLog is an optional table, it's purpose is to store mapping between integer timestamps and corresponding DateTime values. This allows you to find out datetime of the last modification to any object. If you don't need this feature feel free to empty the table, it won't cause any problems. In addition to Bold_ClockLog, the Bold_XFiles is another optional table that tends to grow large. But unlike the Bold_ClockLog the Bold_XFiles can not be emptied. Both of these tables can be turned on/off in the model tag values.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "delphi, bold delphi" }
Independent iterations in Las Vegas algorithms In [Randomized Algorithms, Motwani and Raghavan] book, it is stated that the method of independent iterations to reduce the error probability in Monte Carlo algorithms (amplification according to Wikipedia) has its analogy in Las vegas algorithms. The authors then cited the following references: 1. Alt, Helmut, et al. "A method for obtaining randomized algorithms with small tail probabilities." Algorithmica 16.4 (1996): 543-547. 2. Luby, Michael, Alistair Sinclair, and David Zuckerman. "Optimal speedup of Las Vegas algorithms." Information Processing Letters 47.4 (1993): 173-180. These suggestions of the mentioned papers are a bet very generalized in my opinion. I am wondering - are there well-known algorithms that use the concepts introduced in the previous papers ?
Rapid restarts in SAT solving are one area where the sequence introduced in Luby,Sinclair,Zuckerman is used. See for example Section 2.1 in < for some references.
stackexchange-cstheory
{ "answer_score": 4, "question_score": 2, "tags": "ds.algorithms, reference request, randomized algorithms" }
How to set environment variable in task definition in AWS I am new to AWS Docker and I want to set an environment variable in task definition of ECS and then I want to read it from C# code from docker container. Firstly, is it possible? if yes, how to achieve it? Below is my task.json file { "family": "task-logging-poc", "containerDefinitions": [ { "image": "XYZ", "name": "logging-poc-1", "cpu": 1024, "memory": 1024, "essential": true, "mountPoints": [ { "sourceVolume": "log", "containerPath": "c:/data" } ] } ] }
like this: "environment" : [ { "name" : "string", "value" : "string" }, { "name" : "string", "value" : "string" } ] see this
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, amazon web services, docker, amazon ecs" }
Laravel Blade: How to get the parent URL Is there a way to retrieve the parent URL of the current URL in blade? For example, if I am at `/users/1` I want to get to `/users`. E.g.: <a href="{{ parent() }}">Back</a> I want it to be reusable for all resources, so I don't want `url('/users')`.
Here is my solution: @php $url = url()->current(); @endphp <a href="{{ substr($url,0,strrpos($url,'/')) }}">Back</a>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "laravel, url routing, laravel blade" }
Why is there a yellow bar over my Finder icon? I have a Mac running OS X El Capitan (10.11.3), and I just noticed this today: ![Weird Finder Icon]( I haven't installed anything new, and I have no reason to believe that there's a specific application responsible for this issue. I rebooted my Mac, cleared the NVRAM and ran CleanMyMac 3, but it's still there. Killing the dock or restarting `SystemUIServer` doesn't help. **Question:** Why is there a yellow bar over my Finder icon?
It's a corrupt icon cache. It can be fixed by running the following code from fabiofl: sudo find /private/var/folders/ -name com.apple.dock.iconcache -exec rm {} \;
stackexchange-apple
{ "answer_score": 0, "question_score": 1, "tags": "finder, dock, graphics, icon" }
Visual studio designer view not displaying correctly after upgrade to windows 10? So, I have a form in VS2010 I was working on in Windows 7 that looked like this : ![]( But when my IT department upgraded my pc, and look in the designer view it looks like this, AND the form is much smaller, everything seems to run into each other : ![]( At runtime, the image looks correct like the first image. I have made sure my display settings look correct, and my designer code has not changed between Monday (before upgrade) and Today (post upgrade). Has anyone run into a similar issue? If so, what was your resolution?
I have found the answer. If you go to control panel > display > 'Set a custom scaling level', you may notice that the custom scaling level is set to 125% or higher. I changed that back to 100%, and then updated, and it fixed my display completely. We are now back to normal.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, visual studio 2010, windows 10, windows 7 x64, windows forms designer" }
Clone several nodes I'm searching a module to clone several nodes automatically when i create a project node type. To explain better : When i create a new node of Project type for exemple, i need to clone some nodes and tie this nodes to my node project. I have tried node_clone but we should use a button to clone the node. For the moment i developped a small code to clone my node like this : $p1template=variable_get('myvar_p1'); $p1=node_load($p1template); unset($p1->nid); unset($p1->vid); $p1->title='Processus P1'.$projectid; $p1->field_px_projet['und'][0]['target_id']=$projectid; node_save($p1); But i had a second problem with the field_collection. when i cloned the nodes, the field_collection keep the same reference and when i modify a field collection, all the nodes cloned field_collection was modify... How can i fix this problem ? PS : Sorry for my english.. Thx
Node clone module has a hook for this, hook_clone_node_alter(&$node, $context). When you clone nodes programmatically, make sure you alter their state and values inside this function. function module_name_clone_alter(&$node, $context){ switch ($context['method']) { case 'prepopulate': // Change field values .... break; case 'save-edit': // Perform operations when saving the node. break; } }
stackexchange-drupal
{ "answer_score": 0, "question_score": 0, "tags": "nodes, entities" }
Auto Suggested Text Box in JSP Servlet I am creating one application in which i am using jsp/servlet.. I want to implement auto suggestion text box for user. The suggested data should come from database. can anyone help me that how should i implement it.I mean should i use javascript or write some function in jsp. Any help would be appropriated. Thanks.
You could use jqueryui autcomplete to handle the client javascript side. You will have to write something server side that returns some Json from your database. You could use xstream to provide the Json support from your java server. XStream started as an xml serialiser but now supports Json as part of its alternative output formats.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, javascript, jsp, textbox, autosuggest" }
Display form on the bottom right of screen? I'm creating an application that is based on displaying some notifications which the user should Accept or Refuse How can i show the request form on the right bottom of screen **not above taskbar** ? !enter image description here Code : notificationForm ntf = new notificationForm(); ntf.ShowDialog(); Any help would be highly appreciated
Try this: int x = Screen.PrimaryScreen.WorkingArea.Width - this.Width; int y = Screen.PrimaryScreen.WorkingArea.Height - this.Height; this.Location = new Point(x, y);
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 1, "tags": "c#, .net, notifications, taskbar" }
Google Analytics BigQuery Exit Not Matching Hit Number I'm currently working with GA's hit level data in BigQuery. I've noticed that hits.isExit is not always set to TRUE when the hits.hitNumber is not the highest in a given session. In fact the hit.isExit seems to be true several hits before the end of a session. Anyone know why this would be?
As stated in the comments by Martin and Pol, the reason is because only PAGE hits can be exit hits.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "google analytics, google bigquery" }
using ninject with a remoting server I have a class `Server` that implements interface `IServer` that is accessible using .net remoting (i have no chioce on the matter JICYAW). internally this server uses other classes to implement logic and data access. this `server` class has constructor injected dependencies that it needs to do its job. when a client calls in (per call) the remoting framework will instatiate a `Server` instance using a parameterless constructor and not (of course) using Ninject. how can i get Ninject to be the one in charge for new'ing up the class ? i have seen this similar SO question but this isnt relevant for Ninject. thanks for your help
You can create a service facade that will be called by the client. This facade will internally call your container to resolve the real service. For instance: public class ServiceFacade : IService { private readonly IService service; // default constructor public ServiceFacade() { this.service = YourContainer.Current.Resolve<IService>(); } void IService.ServiceOperation() { this.service.ServiceOperation(); } }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c#, .net, dependency injection, ninject, remoting" }
How to map a list of checkboxes options to a model first class? I have this list of options in my web form: !enter image description here And I want to work with model-first. But I'm very noob with MVC and Model-first, so I don't know how to better represent this in my model class. Should I make one attribuite for each item? Or should I make an array where each position is one option (maybe using `enums`)? public bool[] Comportamento { get; set; } // or public Comportamento[] Comportamento { get; set; } // or public bool Manso { get; set; } public bool Arisco { get; set; } ...
You should have a class `CompartamentoViewModel` that looks like this: public class CompartamentoViewModel { public int Id { get; set; } public string Description { get; set; } } Then, in your main view model: public class MyViewModel { // List of all objects for the view public List<CompartamentoViewModel> Compartamentos { get; set; } // List of ints to retrieve selected values public List<int> SelectedCompartamentos { get; set; } } In the view, use the description for the text and the ID for the value. In the post, populate `SelectedCompartamentos` with the list of selected IDs. Disclaimer: I have no idea how to pluralise "Compartamento."
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "asp.net mvc" }
How do you craft trapdoors in minecraft? Trapdoors are now available in Minecraft - what is the crafting recipe to make them?
A hatch, or trapdoor, is created by filling the bottom and middle rows of the crafting table with wooden planks, like so (image from the Minecraft Wiki): !enter image description here
stackexchange-gaming
{ "answer_score": 10, "question_score": 7, "tags": "minecraft java edition" }
Insert Multiple Values to Database using Single TextBox ASP.NET MVC I have one of the tables with the attributes: id, class name, student name. I want to enter data 1 class name with many student names with 2 textboxes. 1 Textbox is used for class names, 1 textbox for student names. For the student's name textbox, I enter names by separating them with "," each name. How to overcome this problem? Are there other ways to fix this problem? thanks. Model Classroom.cs public partial class Classroom { public int id { get; set; } public string class_name { get; set; } public string student_name { get; set; } }
You can do `YourStringName.split(",")` this will return you a String Array with your values you had seperated with your comma but it is very dirty. I would Prefer to use for each Student a singel button click that adds the student to a list of Classroom and add them together to database.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, asp.net, asp.net mvc, asp.net mvc 4" }
How to build a Set of unique Arrays? I want to add many arrays to a Javascript set, and ensure that only unique arrays are added to the set. However, when I try adding the same array multiple times, it is always added instead of rejected. The .has() method always returns false as well. How do I fix this? const mySet = new Set(); mySet.add([1, 2, 3]); mySet.add([4, 5]); mySet.add([1, 2, 3]); console.log(mySet); // Gives: Set(3) { [ 1, 2, 3 ], [ 4, 5 ], [ 1, 2, 3 ] } // I want: Set(2) { [ 1, 2, 3 ], [ 4, 5 ] } console.log(mySet.has([1, 2, 3])); // Gives: false // I want: true
I'd use a Map instead, indexed by the stringified version of the array: const map = new Map(); const addToMap = arr => map.set(JSON.stringify(arr), arr); addToMap([1, 2, 3]); addToMap([4, 5]); addToMap([1, 2, 3]); console.log([...map.values()]);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, arrays, set, unique" }
A question of opinion: Are you still using iframes? Do iframes still fit the mold of current web standards? The technology is old but I am seeing them resurface - especially with the new youtube embed code being iframes and facebook just allowing custom tabs to be iframes as well. My question is basically: Are the acceptable?
Have a look at this SO question: Are IFrames (HTML) obsolete? In short: They are part of the HTML 5 draft and will be sticking around. If used correctly, I think they are acceptable. :)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "html, iframe, web standards" }
Run local command from expect script I am trying to kill a local background process at a certain point in an `expect` script. Consider the sample script: #! /usr/bin/expect set killPID [lindex $argv 0]; set timeout 1 spawn ftp ftp.ftp.com expect "Name" send "Username\r" expect "Password:" send "xxxxxx\r" expect "ftp>" send_user "Killing local process id: $killPID\n" interact I run this script with the id of a local process that I want to kill as first argument. How can I kill the process just before the `interact` command?
To run a command on the local machine that requires no interaction, do: exec kill $killPID
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "linux, tcl, expect" }
How to prevent escape characters from changing the output of a randomly generated Python string? This code outputs a string of randomly generated characters. For example: V86Ijgh(!y7l0+x import string import random password = ''.join([random.choice(string.printable) for i in range(15)]) print(password) In the case that an escape character like \n appears V86Ijg\n!y7l0+x and creates the output: V86Ijg !y7l0+x because it initialized a new line rather than printing out: V86Ij\n(!y7l0+x like before. What's the best way at avoiding the intended output of an escape character such as creating a new line, tab, etc, from being interpreted? I have no choice over the input because it is **randomized**. I want to know how to output the string in its raw form **without removing characters** from the original string. I want the password to be displayed as it was generated.
You should encode your string with escape characters if you want it to keep the special characters escaped, i.e.: print(password.encode("unicode_escape").decode("utf-8")) # on Python 2.x: print(password.encode("string_escape")) Using `repr()` will add single quotes around your string.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, python 3.x, random, line breaks, password generator" }
Mongo Java query for and/or combination I need a Java driver mongo query for and/or combination - for ex - suppose I have a collection user have 3 field named a, b, c. Now I have to perform find query like - user.find({$and :[{"a":"text"},{$or :[{"b":"text"},{"c":"text"}]}]}) This mongo console query give correct result. How I apply this with JAVA mongo driver. Please help Thanks in advance
You can use following query DBCollection userCollection = db.getCollection("collection"); BasicDBObject orQuery = new BasicDBObject(); List<BasicDBObject> obj1 = new ArrayList<BasicDBObject>(); obj1.add(new BasicDBObject("a", "text")); obj1.add(new BasicDBObject("b", "text")); orQuery.put("$or", obj1); BasicDBObject andQuery = new BasicDBObject(); List<BasicDBObject> obj = new ArrayList<BasicDBObject>(); obj.add(new BasicDBObject("c", "text")); obj.add(orQuery); andQuery.put("$and", obj); System.out.println(andQuery.toString()); DBCursor cursor = userCollection.find(andQuery); while (cursor.hasNext()) { System.out.println(cursor.next()); }
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "java, mongodb" }
Is there a thread-safe TQueue in Delphi 2007? Is there a thread-safe TQueue in Delphi 2007? or the one defined in unit Contnrs is the thread-safe ?
No, Delphi 2007 does not have a thread-safe `TQueue`. You'll need to make use of a critical section when accessing it in order to use it with multiple threads. The one in `Contnrs` is not thread-safe.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "delphi, delphi 2007" }
Workingset/privateWorkingSet memory don't add up to memory usage in Task manager **Memory Issue** One of our server boxes shows 96% memory usage in task manager (137/140GB or so used). When I look in the "Processes" tab though (even with show processes from all users checked), the top processes combined only use 40GB or so combined at peak times. I've provided an image of top used processes below as well as an image of the performance panel showing the memory usage. _Note: CPU usage isn't usually at 99%, it spiked when I took that screenshot._ **My Question** What is the reason for this discrepancy, and how can I more accurately tell which processes are eating the other 100GB of memory? * * * !Task manager top memory usage processes To verify, here's an image of the performance pannel: !Performance Pannel
Sergmat is correct in his comment (thanks by the way); I actually found RAMMAP myself yesterday and used it and it revealed the problem. Our server runs a very heavily used SQL Server instance. RAMMAP reveals that there is a 105GB region of memory used for "AWE" Address Windowing Extensions - which are used to manipulate large regions of memory very quickly by things like RDBMS's (SQL Server). Apparently you can configure the maximum memory SQL Server would use, this being included; so that's the solution.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "windows, memory management, process, operating system, taskmanager" }
SSH forwarding from my laptop to a VM located on a remote server I have a remote server that hosts a VM that is running a web service on port 8000. I want to be able to access the web service from a web browser on my laptop knowing that: 1. From my laptop, I can reach the remote server by SSH 2. From the server, I can connect to the VM using SSH 3. The web service is not directly accessible from the server. 4. Laptop keys and server keys are different. If the web service was running directly on the server, I would do the following: ssh -L 8000:localhost:8000 user@server Which forwards anything I do on localhost:8000 to the remote service through SSH. How to do something similar for the VM's case ?
You can do SSH tunnels via multiple hops. I am not sure I understand your 4th point. My guess is that what you mean is that there is a SSH private key placed on the server which is allowed by public key on the VM. If that is _not_ the case, you can quite simply jump to it: ssh -J server.ip -L 8000:localhost:8000 vm.ip If it is the case, you need to do something like ssh -t user@server -L 8000:localhost:8000 ssh -t user@vm -L 8000:localhost:8000 So basically you just chain SSH commands and you can chain multiple commands, as long as you keep track of the tunneling.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "ssh, forwarding" }
Video in which a man follows a string all his life to end in the desert I am looking for the video where a young man stumbles upon a string (or cable) and begins to follow it, out of curiosity. He follows it a really long time as you can see him age and grow old. At the end he reaches a point where the string stops to go up in the sky, in the middle of the desert. He pulls it and a big rock attached to the string crashes him dead. This video is only a few minutes long and might be a commercial if I remember well. Also, is there some kind of mythological or hidden meaning?
This is most likely the short called "The String" (2007) directed by Naomi Wright and produced by Ginita Jimenez. !The String
stackexchange-movies
{ "answer_score": 6, "question_score": 11, "tags": "identify this tv show" }
Start new page with each section I would like to start each section on a new page. Is adding the following to my preamble this the preferred method, or a hack? \let\stdsection\section \renewcommand\section{\newpage\stdsection}
With an uptodate TeX distribution you can use \AddToHook{cmd/section/before}{\clearpage} Example: \documentclass{article} \AddToHook{cmd/section/before}{\clearpage} \begin{document} \tableofcontents Text \section{Title} Text \subsection{Title} Text \subsection{Title} Text \section{Title} Text \end{document}
stackexchange-tex
{ "answer_score": 8, "question_score": 93, "tags": "sectioning, page breaking, titlesec, sections paragraphs" }
Count with IF condition in MySQL query I have two tables, one is for news and the other one is for comments and I want to get the count of the comments whose status has been set as approved. SELECT ccc_news . *, count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, 0)) AS comments FROM ccc_news LEFT JOIN ccc_news_comments ON ccc_news_comments.news_id = ccc_news.news_id WHERE `ccc_news`.`category` = 'news_layer2' AND `ccc_news`.`status` = 'Active' GROUP BY ccc_news.news_id ORDER BY ccc_news.set_order ASC LIMIT 20 But the problem with this query is that the minimum value that is fetched for the comments column is 1 whether there is any comment existent corresponding to that news or not. Any help would be highly appreciable.
Use `sum()` in place of `count()` Try below: SELECT ccc_news . * , SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments FROM ccc_news LEFT JOIN ccc_news_comments ON ccc_news_comments.news_id = ccc_news.news_id WHERE `ccc_news`.`category` = 'news_layer2' AND `ccc_news`.`status` = 'Active' GROUP BY ccc_news.news_id ORDER BY ccc_news.set_order ASC LIMIT 20
stackexchange-stackoverflow
{ "answer_score": 340, "question_score": 157, "tags": "mysql, join, if statement, count" }
C++ variable type alike Builder TDateTime type I'm looking for variable type (in standard C++ libraries) that could easily substitute TDateTime. What I need is hour, minutes, seconds and miliseconds. Thanks for the attention
I think Boost almost qualifies as a standard C++ library these days, so I would recommend boost::date_time I've used this with BCB2010, if that's any help.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c++, c++builder, tdatetime" }
How to get a specific part of string with specific condition? I've following kind of string: ` I just want last part of the string i.e. `000000000000004` which changes every time. How can I get it using Java?
Use `lastIndexOf()`) String result= yourUrl.substring(yourUrl.lastIndexOf('/') + 1);
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "java" }
Populate Django Model Choice Field In __init__ or save? I want to set the choices for one of my fields based on the keyword arguments given to the model constructor. Does it make more sense to do this in the Model `__init__` method or the `save()` method?
That depends. Do you want it the dependent assignment to happen when you first create an instance of your model or do you want it to happen every time the model is saved? Putting it in an overridden `save` will give you a stronger guarantee that your dependent data won't get out of sync (so long as you don't use `update()` or drop down to raw SQL).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "django, model, save, init" }
Recommended free codecs to play DVD in Windows Media Player 11? None of the MPEG-2 codecs recommended on the WMP help page are available free. Without installing a codec pack, or (at this stage) installing another media player, are there any recommended free MPEG-2 codecs out there that will give me DVD playback in WMP 11? **Claification:** I'm looking for just the specific codecs that will do the job rather than an all encompassing codec pack which may have unforseen detrimental effects.
I came accross the **GPL MPEG-1/2 DirectShow Decoder Filter** which gives DVD playback in WMP. The only possible problem was a warning from the Windows XP Video Decoder Checkup Utility that it does not support synchronization - not a problem for me.
stackexchange-superuser
{ "answer_score": 1, "question_score": 4, "tags": "windows xp, dvd, windows media player, codec" }
Adding class to clicked element I'm trying to add a class to a clicked element. There are multiple elements with unique IDs so I "don't know" what the ID of the element is. Can I use a modified version of the below code to achieve this? Jquery: $(document).ready(function () { $(this).on('click', function () { $(this).addClass('widget-selected'); }); }); **EDIT:** A markup can be like this: <h1 id="textHolder1" contenteditable="true">Text to edit</h1>
I would try with this.. $(document).ready(function () { //this will attach the class to every target $(document).on('click', function (event) { $target = $(event.target); $target.addClass('widget-selected'); }); }) or if you want to check a certain `id` use ... if(event.target.id === "idname") { ... } ...
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 6, "tags": "jquery, addclass" }
Who bitcoin get the transaction fee? part2 I know this question asked before, but the answers give still make no sense to me. The most common answer is "the transaction fee goes to the miner" I'm in a small mining community and nobody ever received a fee. So I'm curious who is are the people and companies who really receive the fees, because this seems to be real real big business.
Transaction fees go to the entity that created the block. The transaction fee is paid out as part of the coin generation transaction along with the block subsidy. This means that the entity that created the block receives both the block subsidy and the transaction fees simultaneously. Currently, the entities that create blocks are mining pools, not individual miners (although individual miners could create a block, it just an extremely long time). The mining pool will then take what was paid out in the block and distribute it to the miners participating in the pool according to whatever internal rules that they follow. This means that miners will be paid less Bitcoin at a time than if they solo mined, but will be paid more consistently. This payout may include transaction fees, but it really all depends on the pool operator to determine how much each participating miner gets paid.
stackexchange-bitcoin
{ "answer_score": 2, "question_score": 0, "tags": "transaction fees" }
Highcharts change label text for a single series In my stacked bar highchart you will see that I have set my last series to the color grey. Is there any way to set the text color to black where the series background color is grey? plotOptions: { series: { stacking: 'percent', }, bar: { stacking: 'percent', dataLabels: { enabled: true, format: '{y}%', style: { color: '#ffffff' //This is where i set the color to white } } } } <
You can set color for each series separately, see: < series: [{ name: 'Poor', color: '#E9E9E9', data: [12, 23, 13, 18, 7, 19, 9], dataLabels: { style: { color: '#000000' } } }, { name: 'Satisfactory', color: '#629AC0', data: [42, 45, 35, 57, 29, 61, 26] }, { name: 'Excellent', color: '#006FBC', data: [46, 32, 52, 25, 64, 20, 65] }]
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "javascript, jquery, css, highcharts" }
mean value theorem to prove: $\ln(x^2 +1)\leqslant x^2$ I need to use the mean value theorem to prove: $\ln(x^2 +1)\leqslant x^2$ i am not very familiar with using this to prove things so i am not sure how to approach this problem.
Consider the function $f(x) = \ln (x+1)$. On the interval $[0,x]$, one can find some $\xi $ so that $$ \frac{ f(x) - f(0) }{x-0} = f'(\xi) = \frac{1}{1+\xi} $$ Thus, $$ \frac{ \ln (x+1) }{x} = \frac{1}{1 + \xi} \leq 1 \implies \ln(x+1) \leq x $$ Now, replacing $x$ with $x^2$ we have $$ \ln ( x^2 + 1 ) \leq x^2 $$
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "real analysis" }
Is it possible to exclude a bone from automatic keyframing? I have a bone I use as a switch but I don't want it to keyframe while in automatic keyframing mode, in my case in visual LocRot. Is there a way to disable keyframes for this bone to eliminate it from automatic keying?
Since automatic keyframing inserts keyframes for all the objects/bones in your 3d view, the easiest way is to take the bones you don't want keyframed and remove them from the 3d view. You can do that by hiding them, or add them to a bone layer that you hide when not animating that switch.
stackexchange-blender
{ "answer_score": 0, "question_score": 3, "tags": "animation, bones, keyframes" }
How to create automated tabs in html/php I could not find a good tutorial for how to generate tabs in html page. I would like to create a function that automatically generates a tab from database information. I was thinking something along these lines. 1. Get categories from DB. 2. IF(!EMPTY(gategory)) { create a new tab, named after the category. } Could somebody please link me to a good tutorial or maybe give an example. Thank you.
Well, you know PHP is a server-side technology and there's no way for creating tabs in the client-side without JavaScript help! In that case, check jQuery UI / Tabs: * < You'll need to initialize your script by forming some JSON and iterating an array of tabs information so you should have enough for creating the whole markup that jQuery UI tabs needs in order to get initialized.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, html" }
Definitions for sections, subsections and subsubsections (+chapter?) I want to change the commands of the article/ book class and want to know how sections, especially in the article class but also in the book class, are defined. I think it is something like this?: \newcommand\subsection{\@startsection{subsection}{2}{\z@}% {-3.25ex\@plus -1ex \@minus -.2ex}% {1.5ex \@plus .2ex}% {\normalfont\large\bfseries}} I want to alter them a little bit and add some commands using `\renewcommand` in a class (.cls) I'm currently writing. Where can I find the other section definitions? Can someone provide a link or the code in an answer?
I found the whole article.cls file here (where the sections is defined): < I do not use a downloaded version of LaTeX, only online (Overleaf) so the command `kpsewhere article.cls` is no use because the file is not stored on my computer.
stackexchange-tex
{ "answer_score": 0, "question_score": 0, "tags": "macros, document classes, article, documentclass writing, definition" }
BotData custome properties values becomes null in Bot framework, what can be wrong? I am working on MS Bot, now stuck at one point, I have two questions 1) How can I get conversation count in MessageController Post method? 2) The values of userData as mentioned in below code becomes null, when bot came back to messagecontroller for further conversation. My bot flow is as below. The MessageController class invokes (Chain.From(() => new BotManager()) --> in BotManager() all the intents are listed--> From Intents i jump to specific form e.g. SampleForm in which i have formbuilder. StateClient sc = activity.GetStateClient(); BotData userData = sc.BotState.GetUserData(activity.ChannelId, activity.From.Id); UserDetails usr = new UserDetails(); usr.EmailId = "[email protected]"; userData.SetProperty<string>("EmailId", usr.EmailId); sc.BotState.SetUserData(activity.ChannelId, activity.From.Id, userData);
In the RootDialog (which implement) the IDialog, you can (and could be a good practice to) use the `UserData`(more info) property for the IDialogContext object to store information for the user across the conversation. In the code below, I try to retrive the ConversationCount key, then increment exists or not. And then I set againt the result value (which internally store the value in the BotState). context.UserData.TryGetValue("ConversationCount", out int count = 0); //Increment the message received from the user. count++; //Increment when the bot send a message to the user. count++; context.UserData.SetValue("ConversationCount", count); You can do the same with the Email property.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "botframework, formbuilder, formflow" }
JavaFX combo box start value? I was curious if there is a way to set a start value for a combo box so that it does not start at the topmost value. For example, I have a combo box called cbCurrentWeight with values ranging from 10 all the way to 999. I don't want 99% of users to have to scroll 100-200 numbers so they can select their weight. I would like for the combo box to start at 100 with the option to go higher or lower from there. I do not want to set a default value for this combo box either. Would I be better off just using a TextField and adding parameters to ensure users are entering a valid number?
I decided to simply change the value to a minimum of 50lbs. The spinner option was great though, and I got it to work. I just prefer the view of the ComboBox.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "javafx, combobox" }
What does intent.putExtra do? i just started learning android development and a bit confused about what intent.putExtra does. Can somebody please explain this? Thanks
When you start a new Intent, you may want to pass some information to it. putExtra is how you so that. For instance if you made an intent to display account details, you might pass it the account id that is to be displayed. Basically any information you put in the extra bundle can be read later by the intent you've given it to.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "java, android, mobile, operating system" }
Unity 3d - CLOTH Object I cannot find the cloth object in CreateObject > 3d in my unity 3d personal edition. Theres no cloth object everywhere.. how can i fix this![enter image description here](
`Add Component` -> Search for `Cloth` or `Interactive Cloth` < ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "unity3d" }
Arithmetic progressions. "Consider an 4 term arithmetic sequence. The difference is 4, and the product of all four terms is 585. Write the progression". My way of finding the progression seems like it will take too long, but here it is, anyway: $$a_1\cdot a_2\cdot a_3\cdot a_4=585$$ $$a_1\cdot (a_1+4)\cdot (a_1+8)\cdot (a_1+12)=585$$ and after some operations $$a^4 +4a^3+196a^2+384a-585=0 $$ Is there a faster, less frustrating way of solving this? Thanks in advance/
The faster way of doing this would be to let your product be $(a - 6)(a-2)(a+2)(a+6) = 585$. This then expands to $(a^2 - 4)(a^2 - 36) = 585$, which substituting $b = a^2$ yields a quadratic which can be more easily factored. > You end up getting $a^2 = 49$ as the only positive root, so you have $a = 7$ and your sequence is: $1, 5, 9, 13$.
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "sequences and series" }
Updating a form generated by a wizard based on a class I'm following the tutorial here. I created my data class and added a name property using the wizard. I then created a zen form using the wizard, during which I selected the data class created above. Everything worked great. However, I went back and added an additional property, `longName` to my data class. Now, since it's over 300 lines of generated code I am assuming there is some way to regenerate it based on the updated class but I cannot figure out how. I did end up copying the line below from the `XData Contents` section and modifying the values. It seems to work well but my question remains, **is there some way to regenerate the form based on the updated class?** <text id="Name" label="Name *" title="Enter a value" size="50" dataBinding="Name" height="23" />
Can you point to exact part of tutorial? Is it Zen Form Wizard? If so just regenerate the form class (you don't need to delete it beforehand). UPD. As you use Zen Form Wizard, you can call it programmatically via: `do ##class(%ZEN.Template.ZENFormWizard).CreatePage(dataClassName, appName, pkgName, newClassName, formName, cssNames, clsComment)`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "intersystems cache, intersystems, objectscript, intersystems cache studio, intersystems cache zen" }
How do we know that automorphisms on polynomials have a polynomial like form? Let $F$ be a field and $\sigma:F[x]\to F[x]$ be automorphism, $\sigma(a) = a$ for all $a\in F$. I'm supposed to show that $\sigma(f(x)) = f(ax+b)$ for some $a\not = 0$ and $b$ in $F$. Now I've got a solution that my professor gave me that seems to assume that the automorphism must have the form $\sigma(f(x)) = f(p(x))$ for some $p(x)\in F[x]$. So my question is how does $\sigma$ being an automorphism on $F[x]$ and $\sigma(a) = a$ for all $a\in F$ give us that $\sigma(f(x) = f(p(x))$ for some $p(x)\in F[x]$, why can't there be some weirder looking automorphism? I've looked at [Automorphisms of $F[x]$]( however the only solution seems to make the same assumption that my professor makes.
Let $\sigma(x) = p(x)$. If $f(x) = \sum_{i=0}^n a_i x^i$, then using the fact that $\sigma$ is a ring homomorphism, $$\sigma(f(x)) = \sigma \left( \sum_{i=0}^n a_i x^i \right) = \sum_{i=0}^n \sigma(a_i) \sigma(x)^i = \sum_{i=0}^n a_i p(x)^i = f(p(x)).$$ More generally, if $A$ is any $F$-algebra, then every $F$-algebra homomorphism $F[x] \to A$ takes the form $f(x) \mapsto f(a)$ for some $a \in A$.
stackexchange-math
{ "answer_score": 2, "question_score": 5, "tags": "abstract algebra, polynomial rings" }
Disable directory listings in all but one folder, using htaccess? Right now, I'm using `Options -Indexes` to hide access to all directory listings on a website of mine. What I've discovered however is that I need directory access to a particular folder: `../Resource/Other/` Is there any way of applying a logical NOT rule to htaccess to allow access to certain folders, while disabling directory access by default? Or do I have to approach it from the other angle and enable directory listings globally and then selectively disable them folder by folder?
Create a htaccess file with `Options +Indexes` in the folder you want to list. Be sure to remove any index files too.
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 7, "tags": ".htaccess" }
MySQL get 5 users and order by their count of views from pivot table I have table users (id, name) and follow pivot table (follower_id, user_id). How can I get top 5 users with most views? Edit: ## Users id | name 1 | John 2 | Bob 3 | Max 4 | Greg ## Follow follower_id | user_id 1 | 3 2 | 3 4 | 3 3 | 1 3 | 2 4 | 2 So the most followers has user by id 3 (Max), then 2 (Bob), then 1 (John). How can I write that query?
Try: SELECT A.* FROM USERS A INNER JOIN (SELECT user_id, COUNT(*) FOLLOW_COUNT FROM FOLLOW GROUP BY user_id ORDER BY COUNT(*) DESC LIMIT 5) B ON A.user_id=B.user_id;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "mysql" }
Can email signatures in Outlook be hosted externally? My company have 10 or so sales reps that all need our email signature that is frequently updated - it contains things like our exhibition dates, any new products logo's we take on etc, so it's a big pain to have to go through the process of explaining how they can update their signatures every time - some even require me to do it on Teamviewer, so it's becoming quite a lengthy process. Is it possible to host HTML/plaintext (both, ideally!) signatures elsewhere to be embedded in Outlook signatures? I could have sworn I'd seen the feature in Outlook before but can't find it in the latest version.
As Outlook will allow you to have HTML pages as signatures a simple solution might be to have local pages with an embedded frame (eg below the person's name) which points to an external webpage which you could update with all of the changing information.
stackexchange-superuser
{ "answer_score": 3, "question_score": 3, "tags": "microsoft outlook, hosting, email signature" }
How to increase the size of first character in a chapter (Drop-Caps) I would like to know how I can increase the size of the first alphabet of first paragraph of a chapter using (Xe/La/?)tex. Please look at the image shown below. !Image related to question 1. What is such an effect called? How do I achieve it using Latex? 2. Are there any special fonts to be used for this purpose that contain ornamental/decorative alphabet faces? Or can it be achieved by some manipulation of existing alphabet glyphs? 3. I am not a designer. I know this site is focused on Tex and not typography but I'd appreciate any pointers to popular typeface combinations for this purpose with popular text faces. E.g. If I am using Adobe Garamond Pro as my text face, what would be a suitable type to use for such a first-alphabet-decoration? 4. And finally _(this question may tantamount to heresy here)_ : Is there a way to do this in Microsoft Word / OpenOffice?
These are called dropcaps or lettrine (from the French). The best package to use is `lettrine` which is available from ctan. Use as: \documentclass{article} \usepackage{lettrine} \begin{document} \lettrine{A}{gain find} more words her... \end{document} Here is the output: ![Screenshot]( They are very difficult to handle typographically, unless the whole page design has been developed with dropcaps incorporated. The modern trend is to use a sans serif font rather than a serified for the dropcap. Can Microsoft do it? It can, but not recommended to be used for typesetting books.
stackexchange-tex
{ "answer_score": 22, "question_score": 20, "tags": "paragraphs, lettrine, drop cap" }
Replace printed statements in Python 2.7 How to replace printed statements in Python 2.7, for example: for i in range(100): print i,"% Completed" #Result Must Be: >>> 1 % Completed The 1 must be **replaced** by 2 and so on. But not in different line or append on same line. I tried searching about it, found solution such as from __future__ import print_function print("i: "+str(i),end="\r") But they result in appended print statements. Is there any correction in my `print_function` or is there a different solution?
Do you want something like this: >>> import sys, time >>> for i in range(100): ... time.sleep(0.1) ... sys.stdout.write('%d %% Completed \r' % (i,)) ... sys.stdout.flush()
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "python, python 2.7" }
Server migration: sync directory We are currently migrating our servers over to a new platform and I need to keep 2 directories over 15Gb each in sync while testing/migrating services over to our new platform. I have thought of using rsync to keep them uptodate however this would take a long time and only be uptodate at the time of running and I need this to be in realtime or as close to as possible! If anyone could help would be greatly appreciated!! Notes: Our current system is running ubuntu and our new one is running centos 5.5
You could do this with a cronjob that ran `rsync -av --delete /directory testing:/directory` at a certain interval, say every hour. However, this would needlessly run sometime when there were no changes, and it if there were a lot of changes immediately after a run i tcould be nearly an hour until they were synced. A better solution might be to use lsyncd. > Lsyncd watches a local directory trees event monitor interface (inotify). It aggregates and combines events for a few seconds and then spawns one (or more) process(es) to synchronize the changes. By default this is rsync. Lsyncd is thus a light-weight live mirror solution that is comparatively easy to install not requiring new filesystems or blockdevices and does not hamper local filesystem performance.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "linux, ubuntu, centos, filesystems" }
Regular expression in Visual Studio for renaming logging method parameter strings? In Visual Studio, I'm very curious to know the regular expression to replace: MyLog.LogFatal("Error E20111205-1147. Custom error.\n"); with this: MyLog.LogFatal("{0}Error E20111205-1147. Custom error.\n",TPrefix(this)); It has to work for any error number, i.e. E12345678-1234. **Update** I should have clarified my question: I want to alter my C# source code, within Visual Studio, using the "Find..Find and Replace..Quick Replace" (Ctrl-H) command. There is about 1,000 instances of this message in my C# source code tree, and it would take too long to edit it manually.
**EDIT: Updated solution, complete Regex is** Starting with: MyLog.LogFatal("Error E20111205-1147. Custom error.\n"); Find Expression: // Matches MyLog.LogFatal(" {any text with 0-9, a-z, A-Z, space, -, . character // and terminated by \n"} "); // Hence, the captured expression from your example is // Error E20111205-1147. Custom error.\n" MyLog.LogFatal\(\"{[0-9a-zA-Z -\\\.]+\\n\"}\); Replace Expression: // Replaces MyLog.LogFatal("{0} {your captured expression}, TPrefix(this)); MyLog.LogFatal(\"{0}\1, TPrefix(this)); You Get: MyLog.LogFatal("{0}Error E20111205-1147. Custom error.\n", TPrefix(this)); For an introduction to VS2010 Regex Find and replace, please see this blog post.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c#, regex, visual studio" }
how can I bind an event to the clear x button icon in internet explorer (see pic) I've found that the little x icon in IE 9 and lower does not bind to any of my jquery events like it does in IE 10 (and better browsers like chrome). This is the x icon I'm talking about: !enter image description here Is there a way I can manually bind this little x icon? I've seen lots of posts on how to hide the x button using css like this: <style type="text/css"> ::-ms-clear { display: none; } </style> but I actually wont to bind a click event to this thing. can it be done?
It's not possible to bind to pseudo elements. You can however create a div and position it absolutely over top of it and then bind to that. That should stop the user from clicking the actual x.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 5, "tags": "jquery, internet explorer, button, bind" }
Get array size for GROUP_CONCAT() - MySQL I am running a query where I used `GROUP_CONCAT()` and now I want to know the length of this array. I used `LENGTH()`, however, this shows the number of characters in the row. Should I even use `GROUP_CONCAT()` in the first place? The results I am expecting: Id | GROUP_CONACT() | LENGTH ---|---|--- 1 | A, B | 2 2 | C, D | 2 3 | E, F, G | 3 4 | A, D | 2 5 | A, B, D, E, G | 5
I think what you are trying to achieve is counting the number of occurrence of ','+1: Use ROUND ( ( LENGTH(concated)-LENGTH(REPLACE(concated, ",", "")))/LENGTH(",")+1 ) AS COUNT Replace concated to your GROUP_CONCAT
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, sql, arrays" }
Which of these functions has the fastest asymptotic growth: $n^{1/3}\log_2(n)$ or $\frac{1}{4}(\log_2(n))^4$? I can't seem to figure out which of the following functions has the fastest asymptotic growth: $n^{1/3}\log_2(n)$ or $\frac{1}{4}(\log_2(n))^4$? Can anyone show me with a proof?
$n^a$ where $a\gt 0$ is always asmptotically faster in growth than $\log_2^b{(n)}$ where $b\gt 0$. The factor of $\log_2{(n)}$ multiplied in just makes the function even faster in growth. A proof comes from taking the limit of the ratio of the two functions: $$\lim_{n\to\infty} \frac{n^a}{\ln^b{(n)}}$$ Now application of L'Hôpital's rule $b$ times changes the limit to $$\lim_{n\to\infty} \frac{a^bn^a}{b!}=\infty$$ Hence the function $n^a$ grows infinitely faster than $\ln^b{(n)}$ for any $a\in\mathbb{R}$ and $b\in\mathbb{N}$. As $$\log_2{(n)}=\frac{\ln{(n)}}{\ln{(2)}}$$ One can extend this result to solve the above problem.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "asymptotics" }
Pidgin not present in 12.10 repositories, how do i get one? I want to install Pidgin on my 12.10 clean install system. When I go to the `Software Center` and try to install the client I get an error saying:- `Not found` `There isn’t a software package called “pidgin” in your current software sources.` Any ideas which repositories i need to import to get this done. * * * ERROR:- Failed to fetch 404 Not Found [IP: 91.189.92.156 80] Failed to fetch 404 Not Found [IP: 91.189.92.156 80]
`pidgin` is in the universe repository. Make sure you have the option to download and install packages from universe enabled. Open software-center. Go to Edit menu --> Open software sources and check _Universe_ option. !software-sources-gtk After checking the option, run the following commands to install `pidgin`. sudo apt-get update sudo apt-get install pidgin
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 0, "tags": "repository, pidgin" }
How to disable this shadow? the shadow is allways to the right and I dont know why it is there.![enter image description here](
It looks like you need to recalculate the normals: select all in _Edit_ mode and `ctrl` `N`
stackexchange-blender
{ "answer_score": 0, "question_score": 0, "tags": "mesh, light, shaders, shadows" }
How do I access validates_format_of in Activerecord::Validator? I'm trying to use validates_format_of getting a nomethod error. I think it's because I'm using "class [nameofclass] < ActiveRecord::Validator" and Validator lacks this method. I need to include something or use another inherit and I don't know how to do this. codesource: <
`validates_format_of` does not work this way , it is meant to create hooks on the database record and run validations before the database record is saved. It does not work as a method on an instance of a class. What you could do is instead use the regular expression you created and add that to your conditional: validation_regex = %r{\.(png|jpg|jpeg)$}i if record.image_url.present? unless is_whitelisted?(record.image_url) || validation_regex.match(record.image_url?) record.errors[:image_url] = 'Invalid image url. Image provider not found in provider whitelist.' end end
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, validation" }
variables between if, else conditon i want to use a variable between two blocks of if/else condition. if(isset($_GET['aaa'])) { code to be executed; $example='a string or codes(calculating)'; } else //if(isset($_GET['bbb'])) { code to be executed; } how can i use $example in else clause? explain that for example at the first time the if clause is true and $example is calculated and for the second loading, else is true and now i want to use $example. i declare $example as static variable but it doesn't work. thanks for your help :)
You can use a session variable for this: Add a session_start(); on the very beginning of your PHP script. Your code could look like this then: if(!isset($_SESSION['example']) { $_SESSION['example'] = some default value; } if(isset($_GET['aaa'])) { code to be executed; $_SESSION['example'] ='a string or codes(calculating)'; } else { code to be executed; use $_SESSION['example'] here } The `$_SESSION['example']` can get a value everywhere you want and you can read it after page refreshes as well. If you need more samples and explanations about $_SESSION, you can check out this site: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php" }
i don't know why these 2 codes have different outputs in python this is for a tic tac toe game for my project but I still don't under stand the difference between my code and my mentor's code correct code: def player_input(): marker = '' while not (marker == 'X' or marker == 'O'): marker = input('Player 1: Do you want to be X or O? ').upper() if marker == 'X': return ('X', 'O') else: return ('O', 'X') my code: def player_input(): player1 = "" while player1 != "X" or player1 !="O": player1 = input("choose x or o : ").upper() if player1 == "X": return ("X","O") else: return ("O", "X")
It's because your condition should have `and` and not `or`. As per de morgans law: ~(p or q) => ~p and ~q So your code should be as follows: def player_input(): player1 = "" while player1 != "X" and player1 !="O": player1 = input("choose x or o : ").upper() if player1 == "X": return ("X","O") else: return ("O", "X")
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python 3.x" }
How to display blocks as a toggle? I am displaying a list of Views blocks on the user page. I want to create a menu/list of links on the sidebar of the page, and when I click the link "Block 1" it shows only the "Block 1". When I click "Block 2" it shows the block 2 and so on... All the other blocks must be hidden. I could create several pages with the views and could link to those pages, but the thing is: I need to be in the user page, because the views have filters related to the user URL. So it has to be all in the same page. What is the best way to do this? Please see the picture explaining how I want the page. ![enter image description here](
The Quick Tabs module may meet your needs. > The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes and other quicktabs. You can create a block on your site containing multiple tabs with corresponding content... Once created, the Quick Tabs blocks show up in your block listing, ready to be configured and enabled like other blocks. You would create a Quick Tabs instance (Admin > Structure > Quicktabs) with the views blocks you want to display. You are able to configure URL arguments to pass to the block's contextual filters. ![enter image description here]( Then display the block of the Quick Tabs instance on the user page. There are various tab styles offered by the module or you can style the tabs with your own CSS.
stackexchange-drupal
{ "answer_score": 2, "question_score": 3, "tags": "7, users, blocks" }
I cannot use insert and select at the same time using mysql database connection .C++ I would like to know how do I copy column from one table to another another table using mysql database connection? My code is like this: string insert_query = "insert into customer_info (Customer Name, Price) Select name,price from medicine_tb where id = '"+storeid[j]+"'"; const char* qu = insert_query.c_str(); qstate = mysql_query(conn, qu); But it is NOT working!
Please use insert into customer_info (`Customer Name`, Price)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c++, mysql, database" }
When exporting a document as a pdf file in Word 2010, what's the difference between standard and minimum size publishing? I've tried both with one of my documents and they look exactly the same in Adobe Reader, but one is 300 KB larger. Is there any advantage to standard publishing?
I believe the minimum size option uses higher JPEG compression on images in the document to reduce file size at the cost of image quality. The change should be subtle but noticeable if you look closely.
stackexchange-superuser
{ "answer_score": 3, "question_score": 0, "tags": "microsoft word, pdf, adobe reader, microsoft word 2010" }
Google oAuth redirect_uri_mismatch error in chrome I am trying to set google login to my website and it works in firefox without error but in chrome its giving me this error > Error: redirect_uri_mismatch > > The redirect URI in the request: < did not match a registered redirect URI Any idea? # EDIT I have cross checked and notice that if I am already logged in to google account on that browser than it is giving an error but without logged in to google it is working. This is strange.
I found the solution and it was the url issue set in API
stackexchange-stackoverflow
{ "answer_score": -6, "question_score": 0, "tags": "oauth 2.0" }
Notepad++ How do I add a comma at a specific column position? I have pretty large ASCII file (1.7mil rows) that I need to insert commas into at specific column positions. I am doing this because I am trying to convert the file to csv so I can import it into mysql. Unless there is a better approach (no doubt), what I am trying to do is insert comma at the specific column positions where I know fields end. This is not a job for column mode as dragging through 1.7mil rows would be insane. I have tried this solution - How do I add a character at a specific postion in a string? but it did not work. Does anyone have a suggestion? Thanks!
To insert after the 4th character on each line: Find: ^(.{4}) Replace: \1, (Ticking _Regular Expression_ in the find/replace dialog)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "mysql, csv, notepad++, ascii" }
Do Facebook CPC ads charge per click, or per like, or both? I'm about to create a Facebook campaign that points to our Facebook fan page, with the CPC option. I want to know what counts as a "click". I already read the docs (quickly to be honest), but i didn't get the answer. Do they charge for the click which redirects to the fan page, or when the user clicks the like at the bottom of the ad, or both ?
You will be charged for both types of click if you use CPC pricing.
stackexchange-webmasters
{ "answer_score": 1, "question_score": 1, "tags": "facebook, advertising" }
What causes this pattern? What causes the pattern seen on the image (it is a still from a video)? This doesn't seem to be a Moiré. It seems to be largely related to the camera or the filter (the pattern is fixed and aligned with the camera). The image was taken through an optical bandpass filter. ![Image](
Nm filter? Do you mean a [some number of] nanometer bandpass filter? If so, that's probably what is causing the pattern. <
stackexchange-photo
{ "answer_score": -1, "question_score": 0, "tags": "filters, digital, zoom, optics, polarizer" }
Do the regulations allow DME from an expired IFR-certified GPS with an out of date database to be used for this ILS approach under an IFR plan? Since we cannot fly an RNAV approach with out of date GPS database, the approach in question is KCRE ILS 23. Whether it was asking for V2F or the full approach starting from ASHES (which is 18.5 DME to CRE VOR). Are intersections "moved" all that often? Is there a way to verify if this happened recently? As of this writing, the approach plate has been last amended June 22, 2017. ![enter image description here]( <
The approach plate specifies that "DME" is required for this approach (see the upper left of the approach plate). The FAA Instrument Flying Handbook (page 9-27) specifies that the GPS database must be "current" if the GPS is to be substituted for DME. > _**GPS Substitution for ADF or DME**_ > Using GPS as a substitute for ADF or DME is subject to the following restrictions: > > 1. This equipment must be installed in accordance with appropriate airworthiness installation requirements and operated within the provisions of the applicable POH/ AFM or supplement. > 2. The required integrity for these operations must be provided by at least en route RAIM or equivalent. > 3. WPs, fixes, intersections, and facility locations to be used for these operations must be retrieved from the GPS airborne database. **The database must be current.** If the required positions cannot be retrieved from the airborne database, the substitution of GPS for ADF and/ or DME is not authorized >
stackexchange-aviation
{ "answer_score": 4, "question_score": 2, "tags": "faa regulations, approach, gnss, precision approach" }
how to redirect with session_start on top of page php i am checking the user login and password on a separate page on top of which i have session_start(); Now if the user gives wrong credentials then i want him to go back but redirect is not working it gives error headers already sent and that is because of session_start() . what could be the best way of doing it. thanks.
First check if there is not any space before session_start or you can also do this on start before session_start write "ob_start();" and on the page end write "ob_flush();" This will help
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "php, session" }
Proof that $\binom{2\phi(r)}{\phi(r)+1} \geq 2^{\phi(r)}$ I try to prove the following $$\binom{2\phi(r)}{\phi(r)+1} \geq 2^{\phi(r)}$$ with $r \geq 3$ and $r \in \mathbb{P}$. Do I have to make in induction over $r$ or any better ideas? Any help is appreciated.
Let $x_n=2^{-n}{2n\choose n+1}$. Then $x_{n+1}=x_n\frac{(2n+1)(n+1)}{n(n+2)}\gt x_n$ for every $n\geqslant1$ and $x_2=1$, hence $x_n\geqslant1$ for every $n\geqslant2$. Since $\varphi(r)\geqslant2$ for every integer $r\geqslant3$, the estimate above implies that the desired inequality holds for every (not necessarily prime) integer $r\geqslant3$.
stackexchange-math
{ "answer_score": 10, "question_score": 1, "tags": "inequality, binomial coefficients, totient function" }
Easiest way to format rtf/unicode/utf-8 in a RichTextBox? I'm currently beating my head against a wall trying to figure this out. But long story short, I'd like to convert a string between 2 UTF-8 '\u0002' to bold formating. This is for an IRC client that I'm working on so I've been running into these quite a bit. I've treid regex and found that matching on the rtf as ((\'02) works to catch it, but I'm not sure how to match the last character and change it to \bclear or whatever the rtf formating close is. I can't exactly paste the text I'm trying to parse because the characters get filtered out of the post. But when looking at the char value its an int of 2. Here's an attempt to paste the offending text: > [02:34] test test
You could use either rtb.Rtf = Regex.Replace(rtb.Rtf, @"\\'02\s*(.*?)\s*\\'02", @"\b $1 \b0"); or rtb.Rtf = Regex.Replace(rtb.Rtf, @"\\'02\s*(.*?)\s*\\'02", @"\'02 \b $1 \b0 \'02"); depending on whether you want to keep the \u0002s in there. The \b and \b0 turn the bold on and off in RTF.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, winforms, utf 8, richtextbox, rtf" }
vim - how do I cut some lines of file-1 to file-2 in 1 step? When I need to cut some lines from one file to another file, I always do the following steps: * Select the lines in file-1 * `:w >> file-2` * Re-select the lines * `d` This is super annoying if you need to do it for like 10 times. So, is there anyway I can write the selection to another file and delete the selection in the same time? Edit: maybe using `gvd` to reselect and delete is a faster option.
You could make it a one liner using a range: 2,3w >> b | 2,3d And if you want to keep doing this with visual selection, you can select the lines and then use `'<` and `'>` for the range: '<,'>w >> b | '<,'> d **Edit** To address the questions in comments: * If the file you're trying to write doesn't exist you can use `w!` to force the command * The `|` character is used to chain commands (not unlike `&&` in bash), you can read about it at `:h :bar`: *:bar* *:\bar* '|' can be used to separate commands, so you can give multiple commands in one line. If you want to use '|' in an argument, precede it with '\'.
stackexchange-vi
{ "answer_score": 3, "question_score": 2, "tags": "paste, selection" }
Has Zero-G Football game play ever been defined, or is it just a open ended plot device in the show? Dave Lister names his kids after his favorite Zero Gravity Football player, Jim Bexley Speed, who plays _Roof Attack_ on the London Jets Zero Gravity Football squad. Lister has several posters on the wall in his quarters. Has Zero-G Football game play ever been defined, or is it just a detail in the background scenery? I'd like to know where it was played, and what the positions were. A source quoting the rules would be _smeggin'_ great, but I haven't been able to find one.
As pointed out by @Hassleinbooks, the game is extensively described in the official Red Dwarf Smegazine - Vol. 1 #8. You can see in the panels below that the rules are essentially nonsensical, featuring a five-dimensional ball, a toroidal playing field, played over _three_ quarters and involving the extensive use of bazookoids, **megaton nuclear weapons** (!) and something called a " _Putsley_ ". !enter image description here !enter image description here
stackexchange-scifi
{ "answer_score": 12, "question_score": 11, "tags": "red dwarf" }
real & predicted values in kfold I'd like a piece of advise! I use kfold cross validation to split my dataset and evaluate the model for a classification problem. I need to know if there is a way to **print out the real values** as well as **the corresponded predicted values of each fold,** so i can see what the model predicts in each iteration of kfold. I'll try to implement this in a small dataset , in order to figure out how it works and then put it in the actual code. I searched this site and found out another question similar to mine, but it wasn't really helpful I should probably put those values in an array and use the functions "for" to make a loop and "cross_val_predict" to get the predictions. Can somebody help please?
I think this should give you what you want. You don't need to explicitly go through the indices because `cross_val_predict` gives you the predicted value for all points when they are in the validation set (it automatically handles the k-fold split). from sklearn.svm import SVC from sklearn.model_selection import KFold, cross_val_predict X = #features y = #labels classifier = SVC(kernel='linear',random_state=0) classifier.fit(X, y) kfold = KFold(n_splits=10) y_pred = cross_val_predict(classifier, X, y, cv=kfold) for i in range(len(y)): print('Predicted value = ' + str(y_pred[i])) print('Real value = ' + str(y[i]))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, machine learning, classification" }
Convert Visual Studio 7.1 project to Visual Studio 9 project? I have an Asp.Net project in Visual Studio 7.1 , Now when I open it in Visual Studio 2008 , I can't access to project files : ![image]( (source: picfront.org) How can I open the project with VS2008 or VS2010 ?
Open the sln file with a simple text editor (make backup) and search for your project that did not find, and correct the directory path. You have probably a line like that... you need to fix the dir, saved it and open it again. Project("{XXXX-XXXXX-XXXX}") = "PECeShopSame", "Dir1\PECeShopSame\PECeShopSame.csproj", "{XXXX-XXXXX-XXXX}"
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "asp.net, visual studio 2008, visual studio 2005" }
How to represent real world in jmeter while jmeter waits the previous response to send a new request? when i want to send 10 requests (all the same request) in one second while running a stress test, but jmeter waits the previous response, what should i do if the response time is nearly 2 seconds. in real world ten users may hit the same page at the same time, but in jmeter how to do this? Does the jmeter have this ability or not?
Just add 10 threads in the Thread Group: ![enter image description here]( If you want to ensure that the request start at exactly the same moment additionally add a Synchronizing Timer and set the number of simulated users to group by to 10 ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jmeter" }
IIS Worker Process using a LOT of memory? I have one website on my server, and my IIS Worker Process is using 4GB RAM consistently. What should I be checking? c:\windows\system32\inetsrv\w3wp.exe
I would check the CLR Tuning Section in the document Gulzar mentioned. As the other posters pointed out, any object that implements `IDispose` should have `Dispose()` called on it when it's finished with, preferably using the `using` construct. Fire up `perfmon.exe` and add these counters: > * Process\Private Bytes > * .NET CLR Memory# Bytes in all Heaps > * Process\Working Set > * .NET CLR Memory\Large Object Heap size > > > An increase in Private Bytes while the number of Bytes in all Heaps counter remains the same indicates unmanaged memory consumption. > > An increase in both counters indicates managed memory consumption
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 18, "tags": "asp.net, iis, memory, worker process" }
Save two TextRanges together with some strings into one file, and then load this later, whats the best/easiest approach? I have two TextRanges from two different RichTextBoxes, and four strings from regular textboxes. I would like to save all this information in one file, and then be able to load it later. Whats the best approach? I've been reading some about it, and it seems that reading all into one memorystream and then save it to a file is one way to do it. And then parse this content later. Anyone that want to share some experience, and simple code?
For a simple approach consider creating a class with string properties for each of your textbox texts. You could then set the properties when you want to save your text, use XML serialization to save the class to an XML formatted file, and then read it back at a later time. The advantage of this approach is that you will not need to hande low-level file handling or parsing yourself. Searching for C# and XML Serialization will yield plenty of code examples.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#" }
camelCase to kebab-case I have a kebabize function which converts camelCase to kebab-case. I am sharing my code. Can it be more optimized? I know this problem can be solved using regex. But, I want to do it without using regex. const kebabize = str => { let subs = [] let char = '' let j = 0 for( let i = 0; i < str.length; i++ ) { char = str[i] if(str[i] === char.toUpperCase()) { subs.push(str.slice(j, i)) j = i } if(i == str.length - 1) { subs.push(str.slice(j, str.length)) } } return subs.map(el => (el.charAt(0).toLowerCase() + el.substr(1, el.length))).join('-') } kebabize('myNameIsStack')
const kebabize = str => { return str.split('').map((letter, idx) => { return letter.toUpperCase() === letter ? `${idx !== 0 ? '-' : ''}${letter.toLowerCase()}` : letter; }).join(''); } console.log(kebabize('myNameIsStack')); console.log(kebabize('MyNameIsStack')); You can just check every letter is if upperCase or not and replace it.
stackexchange-stackoverflow
{ "answer_score": 30, "question_score": 24, "tags": "javascript, ecmascript 6" }
Problem with referencing to a newenvironment The reference I'm using below doesn't work. I think I'm missing something in the definition of `myclaim`. Any ideas? \documentclass{llncs} \usepackage{amsmath} \newcounter{claimcounter} \numberwithin{claimcounter}{theorem} \newenvironment{myclaim}{\stepcounter{claimcounter}{\par\noindent{\bf Claim \theclaimcounter:}}}{\par} \begin{document} Refering to Claim \ref{first-claim} \begin{theorem} aa \end{theorem} \begin{myclaim} \label{first-claim} bb \end{myclaim} \end{document}
Replace `\stepcounter` with `\refstepcounter` \-- this command _"[i]ncrease[s] a counter by one, also setting the value used by`\label`"_ (source2e, chapter 21). \documentclass{article} \usepackage{amsmath} \newtheorem{theorem}{Theorem} \newcounter{claimcounter} \numberwithin{claimcounter}{theorem} \newenvironment{myclaim}{\refstepcounter{claimcounter}{\par\noindent{\bf Claim \theclaimcounter:}}}{\par} \begin{document} Refering to Claim \ref{first-claim} \begin{theorem} aa \end{theorem} \begin{myclaim} \label{first-claim} bb \end{myclaim} \end{document}
stackexchange-tex
{ "answer_score": 5, "question_score": 4, "tags": "cross referencing, environments" }
How do i remove a value in array ? $abc = array( 1 ,2, 3, 4, 5 934, ......); Now i want to remove particular value from the array without any loop since my array can contain n number of values. Note : Value will not be repeated.
You can use this <?php $key = array_search(5, $abc); if($key!==false) unset($abc[$key]); ?>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "php, arrays" }
What is the "&^" operator in golang? I can't really google the name AND NOT and get any useful results, what exactly is this operator, and how could I do this in a language like C? I checked the specification, and there is nothing helpful in there but a list that says it's `&^` (AND NOT).
The C equivalent of the Go expression `x &^ y` is just `x & ~y`. That is literally "`x` AND (bitwise NOT of `y`)". In the arithmetic operators section of the spec describes `&^` as a "bit clear" operation, which gives an idea of what you'd want to use it for. As two separate operations, `~y` will convert each one bit to a zero, which will then clear the corresponding bit in `x`. Each zero bit will be converted to a one, which will preserve the corresponding bit in `x`. So if you think of `x | y` as a way to turn on certain bits of `x` based on a mask constant `y`, then `x &^ y` is doing the opposite and turns those same bits off.
stackexchange-stackoverflow
{ "answer_score": 56, "question_score": 29, "tags": "go, bit manipulation" }
Why does stack overflow occur if we do not declare our buffer as a global variable in C? Just read somewhere that, > when large buffers are used they must be made global variables otherwise stack overflow occurs. But i am unable to get why it would happen? (This is for C language compilers Turbo C on windows).
Typically, the executable file header, and OS loader, place a lower limit on the maximum stack size than they do on the global/static data. Your linker is responsible for assembling the executable header and may be instructed to set a greater, (or smaller), maximum stack size for the executable image, so you could instruct the linker to raise that limit to accommodate your big buffer. If you need a large buffer and don't want to increase the maximum stack, you could dynamically-allocate the buffer space at runtime. The last option you should consider is using statics/globals. Such code/data is not reeentrant and so not thread-safe:(
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c, stack overflow, turbo c" }
MongoDB start sharding When I want to move a single mongodb server into a sharded cluster, I know that I need 3 config servers. Since we have evertything on one single EXSi server I just want to ask if it is the preferred way is really to setup 3 small config server VM's and two additional VM's for the mongod servers. Does this make sense since the the OS on the config server alone will consume 300MB ram (or so)? Is it a good idea to use one VM and three docker containers for the config servers instead? And should I install the mongos router(s) on the two data nodes or on the server where the config servers are living? Let me sum up the question how many VM's do I realy need as a minimum for a sharded mongo cluster? Or is Ubuntu Snappy Core an option?
If you are setting up a **lab environment** you can save on resources usage as much as you like. The idea of using containers/docker sounds reasonable for a **lab environment** (and even for a prod one provided you distribute containers among different physical hosts). The minimum number of `mongod` processes for a sharded environment is 9. 3 for the configuration replica set, and 3 for each of the (minimum of) 2 replicasets in the shard. "Distributed" means it can be run in different machines, but it's not compulsory. You could be running all the 9 mongod processes on a single physical host using different ports ... As for the `mongos` router processes they should run as close to the client apps as possible; i.e. put one `mongos` on each VM with an application that uses mongo. Closing remark. Please note the emphasys on **lab environment**. If you are building something other than a learning environment using a single ESXi node I'd say you need to examine your assumptions.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "mongodb" }
Switching views with segmented controller iphone I present a UIViewcontroller modally. On this screen I want a UIToolbar at the bottom with a segmented controller with 2 options. What is the correct way of doing this, I want the toolbar and segmented controller to be visible on both uiviewcontroller that the user can toggle between. One approach would be to add a toolbar and segmented controller to both viewcontrollers but this would duplicate the code, and probaly is not correct way of doing it. Any help much appriciated.
I have done this before by having a main view, and two subviews (for lack of a better term). Basically, the main view will hold the segmented controller, and whatever other UI components you want. Then, based on the selected option of the segmented controller, add the appropriate subview to the main view. Notice, you may need to resize you subviews to fit the space properly. Fairly straightforward to implement and functions quite well. Hope that helps...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "iphone" }
How to position a div at the top of another div The first div is the `'#icon-selection-menu'` bar, it's idle position is _absolute_ with `top:0px` and `left:0px`. So it appears at he top left corner inside the content div. Deep in the content div children I got other divs which are actually kind of '.emoticon-button'. Their position is relative inside their parent. On such button click I'd like to position the first div just above the button, adjusting it's bottom border to the button's top border. How can I get _top_ and _left_ values to set `$('#icon-selection-menu').top` and `$('#icon-selection-menu').left` ?
jQuery1 provides **`.offset()`** to get the position of any element relative to the document. Since `#icon-selection-menu` is already positioned relative to the document, you can use this: var destination = $('.emoticon-button').offset(); $('#icon-selection-menu').css({top: destination.top, left: destination.left}); `$('#icon-selection-menu')` will be placed at the top-left corner of `$('.emoticon-button')`. (1) jQuery assumed due to the use of `$` in the question.
stackexchange-stackoverflow
{ "answer_score": 26, "question_score": 14, "tags": "javascript, jquery, css, dom, position" }
How I find limit of $P_n$ > Let $a_1=1$ and $a_n=n(a_{n-1}+1)$ for $n=2,3,\dots$. Define $$P_n=\left(1+\frac{1}{a_1}\right)\left(1+\frac{1}{a_2}\right)\dots\left(1+\frac{1}{a_n}\right)$$Find $$\lim_{n \to \infty}P_n$$ Trial: $$1+\frac{1}{a_n}=1+\frac{1}{n(a_{n-1}+1)}\;.$$ But I can't simplyfy.Please help.
$a_{n+1}=(n+1)(a_n+1)=(n+1)a_n+(n+1)$, and so on, you can get that $$a_{n+1}=(n+1)!\left(1+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\cdots+\frac{1}{n!}\right).$$ If that,$$P_n=1+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\cdots+\frac{1}{n!},$$ So $$\lim P_n=e.$$
stackexchange-math
{ "answer_score": 6, "question_score": 5, "tags": "sequences and series" }
Python unit test is not running I am trying to define a test method. Currently I am not receiving any errors, but the test is not actually running. The test is trying to make sure that only the first word in a string that is in list_first_words is being returned. import unittest class TestSong(unittest.TestCase): def first_words_list(self): self.assertEqual(Song().firstwords(["hello world"]),["hello"]) if __name__ == "__main__": unittest.main() Code that is being tested: def firstwords(self,large_song_list): all_first_words = [] # Create an empty list for track in large_song_list: first_word = track.trackName.partition(' ')[0] all_first_words.append(first_word) return all_first_words
You need to rename the test method to `test_first_words_list`. Tests are discovered by _unittest_ only when they start with the word `test`. See "Organizing Test Code" in the documentation for more details.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "python, function, unit testing" }
Change scheduler function code in kernel and recompile it I want count number of scheduler function call in FreeBSD. FreeBSD use from ULE scheduler and I want to add a few lines in top of this function to logging it and then compile and install new kernel. For example, I want to add these lines to scheduler function: FILE *fp; char* str = "string"; int x = 10; fp=fopen("/tmp/mylog.log", "w"); if(fp == NULL) exit(-1); fprintf(fp, "A new call of freebsd scheduler function "); fclose(fp); Where is the scheduler function source code? And where is the exact place that I should copy this code? And what change are necessary for recompiling kernel?
The scheduler, located in sys/kern/sched_ule.c and rebuildable by doing "make buildkernel installkernel" in the top of the source tree, is part of the kernel. That means the code above, which uses stdio, cannot work. What could work would be to use existing facilities, such as Asynchronous Logging Queues (man 4 alq). The easiest way of doing it would be to use DTrace, as that doesn't require rebuilding the kernel.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "kernel, scheduler, freebsd" }
Can "比" go without a subject? Take a look at this sentence. > **** For some reason I translate this sentence as "Compared to A, B is more ...", though this doesn't make any sense to me. Although I found this sentence in a song (which I think could be incorrect), I'm curious if this is a correct and valid sentence. Is this a correct sentence? If it is correct, what nouns are being referred to? Any help would be greatly appreciated.
[ **** (object) (adjective)] = [ more (adjective), **compare to** (object)] * [][] * is the object phrase * is the adjective phrase **The subject is omitted** in this sentence, but it is there. You have to have a subject to compare to an object: " **Subject** ' (omitted) **** [] **** []" The subject can be a noun, or another **phrase**
stackexchange-chinese
{ "answer_score": 1, "question_score": 0, "tags": "grammar, comparison" }
Amazon EC2 permissions and a simple web server I just started experiment with EC2 tonight, and got a server running locally. I know it works locally because when I curl < it outputs hello. I want to access this from the outside world. I modified my permissions in my security group to allow 8080 access, and then typed in "curl < into my local terminal. I got the response "curl: (7) couldn't connect to host". Do I need to do something differently? (Obviously yes, but what?)
You allowed access on 8080, but in your localhost example, it's running on port 80.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "amazon ec2, webserver" }
Generate samples of size n and apply function in R? I have the following code to generate my samples of size n, then want to perform an optimise function on the samples. I should get 1000 results from the optimise function but only get 1? Is there a way to perform the optimise function across the rows of 'x' f2d <- function(n){ x <- replicate(1000, rpois(n, 10)) optimise( f = function(theta){ sum(dpois(x, theta, log = TRUE)) }, interval = c(0,50), maximum = TRUE ) }
The function must be applied to each sample, so define an auxiliary function, `fun`, to be applied to each column. Then, call the function in an `apply` loop. f2d <- function(n){ fun <- function(y){ optimise( function(theta){ sum(dpois(y, theta, log = TRUE)) }, interval = c(0,50), maximum = TRUE ) } # apply the function to each poisson sample x <- replicate(1000, rpois(n, 10)) apply(x, 2, fun) } set.seed(2021) res <- f2d(10) res <- do.call(rbind, res) head(res) # maximum objective #[1,] 9.499999 -26.3231 #[2,] 11.8 -25.62272 #[3,] 9.799998 -31.49774 #[4,] 10.4 -25.40647 #[5,] 10.4 -31.57375 #[6,] 9.899997 -27.67275
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "r, function, optimization, random, statistics" }
How to save a file in /usr/local/lib/cnet? How can I save a file in `/usr/local/lib/cnet`? I'm trying to save a GIF image in the CNET resource folder to use for a simulation. It says permission denied, and when I try to `chmod` the folder it gives me the error "not permitted". Any ideas?
Seems like you need more rights to achieve this. To be able to `chmod`, try becoming root before doing the call: sudo chmod <YOUR_CHMOD> /usr/local/lib/cnet
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "linux, ubuntu, command line, terminal" }
Dell Latitude won’t turn on, but num/caps/scroll lock lights are on A colleague has a Dell Latitude E 6500. He spilled hot water on the keyboard/trackpad area. He took the battery out quickly (without turning the laptop off first). After drying it out for 10 minutes, he put the battery back in and tried turning it back on. The num lock, caps lock and scroll lock lights flashed for a while, and are now on permanently. There is no other response from the laptop: no sound, nothing on the screen. Any idea if the laptop is quickly salvageable?
Is the laptop on a network, can you ping it from another machine? Do you hear the fan turning?
stackexchange-superuser
{ "answer_score": 1, "question_score": 2, "tags": "dell latitude" }
How can I name an aggregate column in spark scala sql instead of default given one? In my homework I must create a cube out of two tables. Everything gets fine using scala, expect from the part where I create an aggregation using the following query : val borrowersAggregation = spark.sql("""SELECT borrowersTable.gender,borrowersTable.department,COUNT(loansTable.bid) FROM borrowersTable,loansTable WHERE borrowersTable.bid = loansTable.bid GROUP BY borrowersTable.gender,borrowersTable.department WITH CUBE""") borrowersAggregation.show(); borrowersAggregation.createOrReplaceTempView("cube") The new column is named count(bid) but I want a different name. Can I somehow rename it inside the body of the query or should I write down an extra line of code ? Thanks !
You can put column aliases using `AS` spark.sql(""" SELECT borrowersTable.gender, borrowersTable.department, COUNT(loansTable.bid) AS count_bid FROM borrowersTable,loansTable WHERE borrowersTable.bid = loansTable.bid GROUP BY borrowersTable.gender,borrowersTable.department WITH CUBE """)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "sql, scala, apache spark, apache spark sql" }
Flash/ActionScript - Use .mp3 file in library in a movieclip I've imported a mp3 file into the library and made an actionscript class, but i can't access is in a movieclip. EDIT: I'm using Adobe AIR, because i want to compile it as an Android Application
set `AS Linkage` for your sound (in library panel) !enter image description here then paste this code in your movieClip (first keyframe) var snd:Snd=new Snd(); snd.play(); hope it helps
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "flash, actionscript, mp3" }
Sort an array containing a lot of dates quickly I have a huge array which contains dates. The date has the following form: `tt.mm.yyyy`. I know how to sort the array with `Sort-Object`, but the sorting takes a lot of time. I found another way of sorting arrays, but it doesn't work as expected. My former code to sort the array was like this. $data | Sort-Object { [System.DateTime]::ParseExact($_, "dd.MM.yyyy", $null) } But as I siad before: this way of sorting is too slow. The `Sort()` method from `System.Array` seems to be much faster. [Array]::Sort([array]$array) This code sorts an array containing strings much faster than `Sort-Object`. Is there a way how I can change the above sorting method like the `Sort-Object` method?
The .NET method will work for dates if you make sure that the array is of type DateTime. Meaning you should use [DateTime[]]$dateArray instead of [Array]$dateArray when you create it. Then you can use [Array]::Sort($dateArray) to perform the sort it self...
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "powershell" }