INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Understanding of HTTP GET request I am initiating and doing a basic penetration testing course and have come across one doubt. For example in this URL: ` I get that I am requesting the `index.php` file in the server and I am specifying that I want to view page 1 as a value of the parameter. But in this other URL: ` I am having trouble understanding this request because I am requesting `get.php` (which is already a file) and the parameter `file` is accesing a different file `/etc/passwd`. My question is what does the `get.php` file contain in this case or is it a function? because it seems to me that it is function retrieving the `/etc/passwd`, but I know that it is not a function, so I am kind of confused about what the `get.php` means. got a picture describing it from the course: ![enter image description here](
> I am requesting get.php(which is already a file) HTTP is not about requesting files, but about requesting resources specified by the URL. These resources might be a static file returned by the web server but they might also be created dynamically based on the URL. In this specific case you are not requesting the contents of the file get.php to be returned, but you request the program get.php to be executed. And `file=/etc/passwd` is processed by this program - how exactly depends on the program. Based on your description the program will likely take it as a parameter `file` with the value `/etc/passwd`, open the file and return it as response. If this succeeds, this is known as a Local File Inclusion vulnerability (LFI).
stackexchange-security
{ "answer_score": 45, "question_score": 4, "tags": "http" }
Not able to select any other column except the first 1 in pandas dataframe Searched alot on the internet to understand the issue. Tried most of it but in vain. I am reading a tsv file which is tab delimited. import pandas as pd df = pd.read_csv('abc.tsv',delimiter="\t", engine="python", encoding="UTF-8") When I print the columns, I am getting this: Index(['date', '​time', '​user_id', '​url', '​IP'], dtype='object') When trying to access the dataframe, I am able to select only the first column by name while the rest gives KeyError: print(df.loc[:, "time"]) KeyError: 'the label [time] is not in the [columns]' Upgraded pandas also: Successfully installed numpy-1.14.0 pandas-0.22.0 python-dateutil-2.6.1 pytz-2017.3 six-1.11.0 Any help would be highly appreciated EDIT: I can access all the columns with iloc print(df.iloc[:, 1])
Comments to answer: If return: print (df.columns.tolist()) ['date', '\u200btime', '\u200buser_id', '\u200burl', '\u200bIP'] then use `strip` for remove trailing whitespaces: df.columns = df.columns.str.strip() In this particular case, it was : `df.columns = df.columns.str.strip("\u200b")`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, pandas" }
Arithmatic conversion and store binary of a number I read this article: The Patriot Missile Failure I have one question: in above article it said that: > It turns out that the cause was an inaccurate calculation of the time since boot due to computer arithmetic errors. Specifically, the time in tenths of second as measured by the system's internal clock was multiplied by 1/10 to produce the time in seconds. Why it should multiply by `1/10` not `10`? if we have 0.1 second and it multiply by 1/10 then it equals to 0.01! Have a good time
The system is counting the number of tenths of seconds that have passed. One tenth of a second is $1$, two tenths of a second is $2$, three tenths of a second is $3$, etc. To convert that number to seconds you multiply by $1/10$.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "arithmetic, binary, decimal expansion, fixed points" }
iphone - Xcode 3.2.3 error regarding deployment target I have an application that is supporting iOS 2.0. The Base SDK is set to iPhone Device 4 and the iPhone OS Deployment Target is set to iPhone OS 2.0 My intention is to build it compatible with iPhone 3/3GS and 4 and iPod touch 2nd generation This settings I have compile file, but when I upload it to iTunes Connect I see this error **The binary you uploaded was invalid. Applications built for more than one architecture require a iPhone OS Deployment Target of 3.0 or later.** How do I solve that? thanks ==== _just a note: my Xcode 3.2.3 allows me compiling for 2.x because I copied the necessary files from older Xcodes to this newest one_
Change the Deployment Target to 3.0, Apple doesn't support iOS 2 anymore. If you want the app to be compatible with the 2nd gen iPod touch, that isn't a problem, as this device is perfectly capable of running iOS 3 and 4.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "iphone, ipad" }
Custom timerjob uses different value then what query is set to Part of my timerjob does DateTime week = DateTime.Now.AddDays(-7); SPQuery mQuery = new SPQuery(); mQuery.Query = "<Where><Gt><FieldRef Name='myDay' /><Value Type='DateTime' IncludeTimeValue='False'>" + week.Date.ToString() + "</Value></Gt></Where>"; " But it always has fieldref='created' and includetime=true no matter what I do. Edit: I have also tried to change the query completely but anything I put just returns null I thought maybe it was some sort of SharePoint cache issue but I have retracted, deleted, resetISS, & deployed to find no difference. My Solution: I uninstalled the assembly from the GAC ( Drive\windows\assembly\ ) then I retracted my solution, resetiss, restart-service SPTimerV4, restarted the machine. Build & deploy. Things worked again
Seems like timer job is not getting deployed correctly, Delete the custom timer job: how to delete sharepoint timer job using powershell Then deploy it again with your changes and see if that updates...
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 1, "tags": "custom timer job" }
How to set default sort column in extjs4 grid and change date format? 1- **How do I set the column to be sorted when the grid is created?** then upon reloading the grid, it automatically utilize that sort to appropriately display the records.(without me clicing on it) Can this be done on the grid itself so it is independent of the underlying data store? 2- **how do i change Date format displaying in a grid column?** my data render a date like this `/Date(1316020760837+0000)/` i tried using `renderer: Ext.util.Format.dateRenderer('m/d/Y'),// format: 'm d Y'` but it gives me `NaN/NaN/NaN` any help would be appreciated. thank you
solved: 1. i used `sortOnLoad` with `sorters` var myStore = new Ext.data.JsonStore({ fields: ['Item1', 'Item2', 'Item3', 'Item4'] , data: [] , sortOnLoad: true , sorters: { property: 'Item1', direction : 'DESC' } }); 2. in my c# code i used `item.DateEnd.ToString("MMM dd, yyyy")`. see this or this for standard and custom format or better in extjs4 ,you should specify the _dateFormat_ so Ext can parse it properly and you'll ensure it gets read ok. {name: 'Item1' , type : 'date',dateFormat :'MS'} u can see this for available format strings.
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 6, "tags": "datetime, sorting, grid, extjs4" }
Set background color of a control? (WinAPI) How can I set the backcolor of a control (equivilant of control.backcolor in .Net). I tried setBKColor with no luck. ex: TabHwnd = createWindowEx(NULL,WC_TAB.... then how could I set the back color of TabHwnd? Thanks
Windows will generate a message when it's painting the background of a control, and it is up to your program to respond to the message appropriately. * WM_CTLCOLORBTN.aspx) * WM_CTLCOLOREDIT.aspx) * WM_CTLCOLORDLG.aspx) * WM_CTLCOLORLISTBOX.aspx) * WM_CTLCOLORSCROLLBAR.aspx) * WM_CTLCOLORSTATIC.aspx)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c++, c, winapi" }
Object array dynamic I have the following line in my code: object[] inputs = new object[] {"input1", "input2", "input3", "input4"}; I would like to know how (without knowing how many elements will be in the array) add dynamically using a loop like this: object[] inputs; foreach (string key in Request.Form.Keys) { inputs[0] = key; } How could I do this? Thanks in advance. Best Regards.
Could you just not use: List<object> list = new List<object>(); list.Add(key);
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 4, "tags": "c#, arrays" }
Disable or Hide Save/Print Preview Dialog popups I'm working with an ActiveX control placed on a winform. I'd when the user tries to save or print, it will always show a dialog box first; I'd like to either immediately close the dialog box or keep it from displaying in the first place. The control in question does not raise any events that would let me know what button they pushed, so I can't really cancel it out by looking for an "on_print" notification.
I ended up just sending escape via SendKey() whenever WM_ENTERIDLE was processed and that did the job. Dirty hack, but it worked.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, .net, winforms, winforms interop" }
SharePoint Search Center (People Search) ## problem I create few sites collection and one search center when I search for people result shows nothing.I have no clue where i am doing wrong. ## image 1 ![enter image description here]( ## image 2 ![enter image description here](
You probably don't have User Profile Service configured properly for this. Here's how to check: SharePoint 2013 People Search Result Empty If you need full instructions, you can read this tutorial: How to Configure People Search in SharePoint 2013 Let me know if you need help or have more questions.
stackexchange-sharepoint
{ "answer_score": 2, "question_score": 0, "tags": "sharepoint search, search center" }
How to install SWIG on Linux centos I want to install SWIG on My linux server to test some stuff. How can install that
You have a few options. The easiest is to check for a binary package in the CentOS repository. sudo yum install swig Alternatively, you can download SWIG from < untar it, ./configure, make, sudo make install and you're done. Of course, finding the proper dependencies may be a little difficult, but with a little bit of Google-fu, you'll find what you need.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 8, "tags": "swig" }
Swf manipulation and decompression I've been reading into swf files and how they work, and I've been searching around for good decompression libraries. However I can't seem to find any, so my question is this. Does anyone know of any well-documented swf-specific libraries that are up to date, or could I use zlib to code a decompiler myself (swfs use zlib streams) Thanks in advance, adil
Adobe have made the specification for the SWF file format (up to v10) available on their website, so if you want to code a decompiler yourself you can use that as a basis for it.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "flash, decompiler" }
Finding special characters in name How do I find files that have ~ * and other special characters in the name? e.g. find . -name "*\*" should match "any characters" and then `*`, but it matches nothing; how can I get the command to correctly match the files?
Implementations of `find` vary, but they should all handle character classes in wildcards (POSIX.2, section 3.13): find . -name '*[~*]*' If newline is among your "special" characters, you may need to work out how to get your shell to pass it to find. In Bash, you can use find . -name $'*[\t \n]*' to show files containing whitespace, for example. A simpler method, if supported, is to use a character class: find . -name '*[[:space:]]*'
stackexchange-unix
{ "answer_score": 6, "question_score": 4, "tags": "find, regular expression" }
JQuery mobile use 36x36 icons How I can use the 36x36 icons instead of 18x18? I can't find anything where it is explained or an example. I just want to use bigger icons!! Thank you very much!
Taken from the OP's revisions to the question: * * * The problem was that I am using a jQuery mobile icon pack and I had to modify the css file in order to adjust the position of each icon.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "jquery, jquery mobile" }
Exception between threads. How many std::exception_ptr and synchronization I need? I am a bit confused, but my question is simple. I have a bunch of threads, I want to centralize error handling by treating all exceptions in the main thread after sent by other threads. 1. Do I use a shared `exception_ptr` global and use `std::current_exception()` in every `catch` clause in every thread? Or do I need to have different `excpetion_ptr` objects for different threads? I would like to keep all exceptions. 2. once the `current_exception` is assigned to an `exc_ptr` variable, when I access the `exc_ptr` from the main thread, do I need to synchronize the read from the main thread?
You want to propagate to the main thread only those exceptions that are not handled by the subordinate thread. This means you only need to use `exception_ptr` at the very top level handler of the subordinate thread. I think the easiest approach is to have a global _container_ (e.g. a producer/consumer queue) of `exception_ptr`s. Each top-level thread exception handler pushes its exception to the queue and exits. The main handler pulls exceptions from the queue and rethrows. Of course you need a proper synchronisation for the queue. Once you pull an `exceoption_ptr` off the queue you don't need to synchronize it, because the thread that has created it won't touch it any more. It should also be possible to have a single global `exception_ptr` (equivalent to a queue of capacity 1, and synchronised in much the same way).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "c++, multithreading, c++11, exception" }
node / mongoose: getting to request-context in mongoose middleware I'm using mongoose (on node) and I'm trying to add some additional fields to a model on save by using Mongoose middleware. I'm taking the often-used case of wanting to add a lastmodifiedsince-date. However, I also want to automatically add the name/profilelink of the user which has done the save. schema.pre('save', function (next) { this.lasteditby=req.user.name; //how to get to 'req'? this.lasteditdate = new Date(); next() }) I'm using passport - < \- which results in req.user being present, `req` of course being the http-request. Thanks **EDIT** I've defined `pre` on an embedded schema, while I'm calling `save` on that parent of the embedded instance. The solution posted below (passing arg as the first param of save) works on the non-embedded case, but not on mine.
You can pass data to your `Model.save()` call which will then be passed to your middleware. // in your route/controller var item = new Item(); item.save(req, function() { /*a callback is required when passing args*/ }); // in your model item.pre('save', function (next, req, callback) { console.log(req); next(callback); }); Unfortunately this doesn't work on embedded schemas today (see < One work around was to attach the property to the parent and then access it within the embedded document: a = new newModel; a._saveArg = 'hack'; embedded.pre('save', function (next) { console.log(this.parent._saveArg); next(); }) If you really need this feature, I would recommend you re-open the issue that I linked to above.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 7, "tags": "node.js, mongoose" }
Go template function It noticed a weird thing with Go templates when I try to use `Funcs` and `FuncMap`. The following code works as expected: buffer := bytes.NewBufferString("") funcMap := template.FuncMap{ "label": strings.Title, } t, _ := template.New("alex").Funcs(funcMap).Parse("{{label \"alex\"}}") t.Execute(buffer, "") return string(buffer.Bytes()) //=> "Alex" But when I try to put the template in a file, it does not work (`Execute()` says: `"alex" is an incomplete or empty template`): t, _ := template.New("alex").Funcs(funcMap).ParseFiles("template.html") With template.html: {{label \"alex\"}} Any idea why ? Is this a bug ? Are there simpler ways to use methods/functions in templates ?
ParseFiles could probably use better documentation. A template object can have multiple templates in it and each one has a name. If you look at the implementation of ParseFiles, you see that it uses the _filename_ as the template name inside of the template object. So, name your file the same as the template object, (probably not generally practical) or else use ExecuteTemplate instead of just Execute.
stackexchange-stackoverflow
{ "answer_score": 34, "question_score": 31, "tags": "go, go templates" }
Why is my function representation not reverse-copying data? I have this function representation of `fwrite` that write bytes backwards. However.. it doesn't really copy them backwards which appears to be really strange. size_t fwrite_backward ( const void * ptr, size_t size, size_t count, FILE * stream ) { int i, chr; for(i = count * size; i != 0; i--) { if( fputc(*(unsigned char*)ptr + (count * size) - i, stream) != EOF ) chr++; } return chr; } It is supposed to behave exactly like `fwrite` with two differences: * It copies data backwards * It doesn't set `ferror` What i might be doing wrong?
The implementation below seems to work. It also corrects some minor design flaws of your version: * Your code writes out all _bytes_ backwards, but you should write all _items_ backwards with the bytes in the items themselves in the original order. (After all, what's the distinction between `size` and `count` for?) The code below works with items of any size. * Yor code returns the number of bytes written. But `fwrite` returns the number of items written. * The loop ends early on unsuccessful writes. So: size_t fwrite_rev(const void *ptr, size_t size, size_t count, FILE *stream) { const unsigned char *p = ptr; size_t written = 0; while (count--) { if (fwrite(p + size * count, size, 1, stream) < 1) break; written++; } return written; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c, io, fwrite" }
How to get IWpfTextView from command Visual Studio Extension 2017 I need to show popup use TextViewAdornment, it's require IWpfTextView. There is old code to that: private IWpfTextView GetWpfTextView(IVsTextView vTextView) { IWpfTextView view = null; IVsUserData userData = vTextView as IVsUserData; if (null != userData) { IWpfTextViewHost viewHost; object holder; Guid guidViewHost = DefGuidList.guidIWpfTextViewHost; userData.GetData(ref guidViewHost, out holder); viewHost = (IWpfTextViewHost)holder; view = viewHost.TextView; } return view; } but when go to Visual studio 2017 Extension DefGuidList.guidIWpfTextViewHost is missing. So I cannot get IWpfTextView anymore. Please help me. Thank you everyone.
After Sergey Vlasov answer I found a solution: private IWpfTextView GetWpfView() { var textManager = (IVsTextManager)ServiceProvider.GetService(typeof(SVsTextManager)); var componentModel = (IComponentModel)this.ServiceProvider.GetService(typeof(SComponentModel)); var editor = componentModel.GetService<IVsEditorAdaptersFactoryService>(); textManager.GetActiveView(1, null, out IVsTextView textViewCurrent); return editor.GetWpfTextView(textViewCurrent); } You must add some reference manual by Add Reference -> Assemblies -> Extensions. Then choose: Microsoft.VisualStudio.ComponentModelHost Microsoft.VisualStudio.Editor
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "c#, visual studio 2017, visual studio extensions" }
Using WHM, is there a way to batch make and download backups? I've got 10 accounts on one server. I want to make a full cpanel backup of each one and download them all to my external hard drive. I do this manually, individually, which takes about an hour. On a system using WHM (on a RedHat server), is there a way to batch make and download cpanel backups?
I think if you have shell access then you can write shell script to backup all the accounts and put in one safe directory , from where you can download all of them
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "backup, redhat" }
Capitalize names in python Is there a way to enter a sentence str and capitalize all the names in it? test_str = 'bitcoin is not dead and ethereum is cool' I wish to convert it to test_str = 'Bitcoin is not dead and Ethereum is cool' Is this possible? My first thought is to use the re module to locate the name then modify it but then realized the names don't seem to have a specific pattern.
If you have a list of words you want to capitalize you can do it as follows: names = ['bitcoin', 'ethereum'] test_str = 'bitcoin is not dead and ethereum is cool' output_str = ' '.join([word.capitalize() if word in names else word for word in test_str.split()]) >>> 'Bitcoin is not dead and Ethereum is cool'
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -3, "tags": "python, regex, python 3.x" }
Dllmain function is not being called I searched here but none of these questions helped me so yeah I'll explain: My Dllmain function is not being called when it attaches to a process (rundll32.exe) in visual studio project settings I changed it to attach to rundll32.exe it was supposed to show a messagebox on attach but it just doesn't do it. My code: // dllmain.cpp : Defines the entry point for the DLL application. #include "pch.h" BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: MessageBox(NULL,L"ThumbsUp",L"Attached",MB_ICONINFORMATION); case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } Thanks
If you use rundll32.exe as the loader program, you must call it using an entry point, like this: ![enter image description here]( In this case, DllMain has been called, but you'll get a messagebox error like : Error in D:\blah\blahblah.dll Missing entry: x That's normal, it's because you don't have exported any externally callable function from your .dll. "x" is here just a placeholder to force rundll32 to load the .dll. If you really want to use rundll32, then read this: How does RunDll32 work?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "c++, winapi, dll, messagebox, dllmain" }
Modify and validate a grails domain object without saving it How do I use the GORM .get to retrieve an object o, modify some fields, and call o.validate() to find errors without Hibernate saving the object to the DB. discard by itself does not prevent the save. Neither does clazz.withTransaction { status -> row.validate(flush:false) row.discard() status.setRollbackOnly() } This post recommend using a command object but this code will apply to many different domain object. There must be a simple way (some parameter passed to validate?) to give Hibernate the do not save instruction. Do I need to create a new instance every time?
If you use `read()` instead of `get()` to retrieve the object it won't be auto-saved during a flush (e.g. at the end of a transaction or a web request). It's not truly read-only, since you can call `save()` and it will persist - it's just not going to auto-save when dirty.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 7, "tags": "grails, validation, domain object" }
¿Como calcular el máximo de una sumatoria en SQL Server 2008? Quiero obtener el máximo valor de la sumatoria de los cargos **(Freight)** que pertenecen a cada empleado pero **SQl** no me deja usar una funcion de agregación sobre otra por ejemplo **MAX(SUM(o.Freight))** Mi pregunta es como puedo hacerlo: **Este es mi código:** USE Northwind SELECT e.LastName+' '+e.FirstName as Nombre, SUM(o.Freight) as Cargo FROM dbo.Employees e INNER JOIN dbo.Orders o ON e.EmployeeID = o.EmployeeID GROUP BY e.LastName+' '+e.FirstName
Puedes hacerlo con una subquery: SELECT MAX(Cargo) FROM (SELECT e.LastName+' '+e.FirstName as Nombre, SUM(o.Freight) as Cargo FROM dbo.Employees e INNER JOIN dbo.Orders o ON e.EmployeeID = o.EmployeeID GROUP BY e.LastName+' '+e.FirstName) AS Sumas
stackexchange-es_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql server" }
Apply class conditionally to specific item in a list Vue.js 3.0 I'd like to disable specific link in automatically rendered list in Vue.js conditionally, here is what I have at the moment: <ul> <li class="nav-item" :key="id" v-for="(item, id) in listOfItems"> <a class="nav-link" :id="item.id">{{ item.name }}</a> </li> </ul> Basically in some conditions I'd like to disable one of the links from the `listOfItems` and get it back active if this condition is not applicable anymore. If I bind conditional class it applies to each item in the list: `:class="[someCondition = 'something' ? 'disabled' : '']"` How to specify in this condition which item exactly should be disabled if the condition is true?
You could put an additional property on any items you want checked that way: listOfItems: [ { id: 1, name: 'name1', checkme: true }, { id: 2, name: 'name2', checkme: false }, ] Then, using object binding syntax and `===` since you're doing a comparison: :class="{ disabled: item.checkme && someCondition === 'something' }"
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "javascript, css, vue.js, conditional statements, vuejs3" }
Converting from Task<(string,object)> to Task<string> Is it possible to convert from `Task<(string,object)>` to `Task<string>`? I have a method that receive `Task<string>` as argument, but from another method returning type I am getting `Task<(string,object)>`.
`ContinueWith` converts a `Task<T>` to `Task<U>`, using the given `Func<Task<T>, U>`: Task<(string, object)> tupleTask = MethodThatReturnsTupleTask(); Task<string> stringTask = tupleTask.ContinueWith(tuple => tuple.Result.Item1); MethodThatAcceptsStringTask(stringTask);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, task parallel library" }
How to parse and split strings? Can I get the number after the comma and put into a variable, and only two before the comma and put into another variable on Android? I'm trying to do something like that... I have the number 12,3456789 I want to get "12" and put into a variable A. Then I want to get "34" and put into a variable B, there is a way to do that?
Try this: String all="12,3456789"; String[] temp=all.split(","); String a=temp[0]; //12 String b=temp[1]; //3456789 **Edit:** if you want to get 2 no's after **,** than use `b.substring(0, 2)` like : String c=b.substring(0, 2);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java" }
What can I do to make sure that I have the energy to work on my game while working full-time? I work as a software engineer 40+ hours a week and I find that between balancing my personal life and family responsibilities that I have literally no energy to work on game development. What can I do to make more time for my hobby without burning myself out in front of the computer? I am sure there must be someone here successfully developing a game while working as a programmer on the side.
When I worked as a software engineering intern the past three summers, I also wanted to work on my own projects, but also spend time with friends/family. Not quite the pressure of family responsibility that you face, but still a time sink. The only way I could make things sort of work was identifying nights that were completely dedicated to one thing over the other. If I was supposed to spend the evening with my family I wouldn't even boot my computer. Other times, I had to ask my family not to disturb me and turn off my phone so I wouldn't get distracted. Even while working, take a break every 20-30 minutes to walk around and get your eyes off the screen. The pomodoro technique has proven handy when I've had to juggle several projects at once.
stackexchange-gamedev
{ "answer_score": 59, "question_score": 87, "tags": "software engineering, motivation" }
Can I use a JSON array as a small database? I'm retreiving a JSON string and parsing it with jQuery with $.getJSON. After I get the data in a variable, can I add or remove rows? An example: { "one": [{ "sid": "1", "name": "NAME 1" }, { "sid": "2", "name": "NAME 2" }], "two": [{ "sid": "3", "name": "NAME 3" }] } Can I delete sid 1 from "one" and place it in "two"? How about sorting by sid? I'm using jQuery.
sure, you can do any of that, they are regular objects and arrays. You can sort arrays, remove their members, add members to other arrays, etc. I wouldn't use jquery stuff, just use basic array tools, such as splice and push and pop. splice() can do most anything: < Sorting is easy as well, just use sort() on the arrray.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, jquery, json" }
python : when a number is reversed with zero as ending. Does not display zero in output when a number is reversed with zero as ending. Zero is not printed in the output. ex: 11120 but output=2111. Please find the attached image code: code i have written for reverse of the number enter image description here
original_int = 21110 forward_str = str(original_int) reverse_str = '' for char in forward_str: reverse_str = char + reverse_str print(reverse_str) Result is 01112 (a string)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "python" }
VMWare to Azure - multiple VMDK files, how to handle? this might seem like a remarkably simple question, but I want to be sure before I proceed and I was struggling to find any information regarding this. I am currently in the process of transferring an existing VMWare environment to Windows Azure. I have been given three different VMDK files, one for each hard drive of a server, and am aware that I need to convert these to VHD for image upload in Azure. My question is whether I need to make these VMDK files into one VHD image or if I can upload multiple VHD images and work with them in the portal. I have seen that it is possible to convert multiple VMDK files into a solitary VMDK file, but I am unsure if this would be appropriate. This is my first exposure to this work, so apologies if this seems like pure basics!
Not sure about VMWare-specifics but if these VMDK files can be broken down into 1 system disk + multiple data disks, then you can upload all of them into Azure once converted into VHDs.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "azure, cloud, virtual machine, vmware, vhd" }
Chrome extension: Inject HTML in the DOM popup page from the background page I'm stuck now, in a background page, I would like use the .html() jQuery method on the popup.html DOM from background.html. I found something with var x = chrome.extension.getViews({type:"popup"}); What I have to do with x? The popup may be closed.
x will be an array of the windows you asked for, which in this case is the popup so should only be one. Something like this should get you going.... var x = chrome.extension.getViews({type:"popup"}); if (x.length>0){ $(x[0].document.body).html('I had chicken for lunch!'); } <
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "google chrome extension" }
Online Preprocessor for C++ **I have:** 1. C++ code with lots of complicated MACROS (#define bla bla ...) 2. And the usage (instantiation) of those MACROS **I need:** A tool (online for example) that will simply do the instantiation of the MACROS (or the system of macros) and show the resultant code. **Example:** _Input:_ #define AAA(a,b) if ((a) > (b)) AAA(1, f1(10)) _Output:_ if ((1) > (f1(10)))
The `gcc` option would be -E and then your filename. With the MSVC `cl.exe` the solution is also /E.
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 21, "tags": "c++, c preprocessor" }
Hashes vs Arrays In Ruby (Am I using them right?) I am essentially building a calendar. Each day is either considered an on day or an off day. It can't be both. I take the users input and generate a calendar for the next 365 days out using what is basically a test condition. I believe I should use a hash for this using the date as a key. I read that as long as I use ruby 1.9 the hashes stay in order and I can iterate through them like an array if I so choose. I believe I will iterate through them when I display the calendar. Is this the correct way of thinking about it?
Ruby has a set class, which you could use to store "on" dates. Since sets internally are implemented as hashes, lookups are fast. Example (more or less a slighly tidied up IRB session): require 'set' require 'date' on_days = Set.new on_days << Date.today + 1 on_days << Date.today + 7 def on_day?(on_days, date_to_check) on_days.include? date_to_check end >> on_day?(on_days, Date.today) #=> false >> on_day?(on_days, Date.today+1) #=> true In a real program you'd probably wrap this up in a class, with `on_days` as an instance variable instead of passing it around, but the principle should be the same.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ruby, arrays, architecture, hash" }
Python 3 ~ How to obtain same result using CSV module I have this in my code: with file: csv = csv.reader(file,delimiter=",") df = pd.read_csv(argv[1]) data = df.loc[:, df.columns != 'name'].to_numpy().tolist() data.insert(0, df["name"].tolist()) and it `output` result is this when i run `print(data)`: [['Alice', 'Bob', 'Charlie'], [2, 8, 3], [4, 1, 5], [3, 2, 5]] I would love to know how i can obtain this same result using CSV module or for loops content: name,AGATC,AATG,TATC Alice,2,8,3 Bob,4,1,5 Charlie,3,2,5
import csv with open('file.csv', newline='') as csvfile: csvreader = csv.reader(csvfile) next(csvreader) # skip headers names = [] data = [] for row in csvreader: names.append(row[0]) data.append(list(map(int, row[1:]))) print([names] + data) Prints: [['Alice', 'Bob', 'Charlie'], [2, 8, 3], [4, 1, 5], [3, 2, 5]] * * * EDIT: import csv with open('file.csv', newline='') as csvfile: csvreader = csv.reader(csvfile) next(csvreader) # skip headers names = [] data = [] for row in csvreader: names.append(row[0]) data.append(list(map(int, row[1:]))) all_data = [names] + data print(all_data[0]) print(all_data[1]) Prints: ['Alice', 'Bob', 'Charlie'] [2, 8, 3]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python 3.x, list, csv, file" }
How do I add a transition to this rollover? How do I add a transition to this rollover? Here is my css so far: .img-container { width: 401px; height: 267px; position: relative; } .img-container:hover .square-icon { display: block; } .square-icon { opacity: .5; position:absolute; bottom:0; left:0; width:100%; height:100%; background: url(images/zoom-icon.png) center center no-repeat; background-color: #FF3860; cursor:pointer; display:none; } And here is the html: <div class="img-container"> <img alt="lorem" width="401" height="267" src="images/450-300-13.png"> <div class="square-icon"></div> </div> I know I need to add: transition: opacity .25s ease-in-out; -moz-transition: opacity .25s ease-in-out; -webkit-transition: opacity .25s ease-in-out; But I'm not sure where to add it?
You need to set the two states (normal and hover) of .square-icon to have different levels of opacity and then you can transition on opacity. See my jsBin demo here .img-container:hover .square-icon { opacity: 1; } .square-icon { position:absolute; bottom:0; left:0; width:100%; height:100%; background: url(images/zoom-icon.png) center center no-repeat; background-color: #FF3860; cursor:pointer; opacity: 0; transition: display 2s ease-in-out; -moz-transition: opacity 2s ease-in-out; -webkit-transition: opacity 2s ease-in-out; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "css" }
Simple Facebook connection with my web site In one of my web page I need to show the username , well this is a public chat page. My requirement is if that user is logined in facebook then need to show his name and profile pic other wise prompt for entering new username ? Any facebook plugin available for this ? Please help Thanks
< Part of the example they show: FB.api('/me', function(user) { if (user) { var image = document.getElementById('image'); image.src = ' + user.id + '/picture'; var name = document.getElementById('name'); name.innerHTML = user.name } }); I believe the only way you can get this info is by having Facebook login.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, facebook, user interface, x facebook platform" }
How to make output visible while running the code from VS? I can see the output window with logging information only when I stop/exit the application. How to make it visible while running the code from VS?
Open Output window before or while running the application ( _View -> Output_ or _ALT+2_ ).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "visual studio, logging, window, trace" }
How to convert a python list to pandas Dataframe in python I have this `python` `list` and I need to convert it into `pandas` `dataframe`. This is how my list looks like: thisdict = {} thisdict["Column1"] = 1 thisdict["Column2"] = 2 thisdict # this print {'Column1': 1, 'Column2': 2} And I need to convert this to `pandas` dataframe. I tried: df = pd.DataFrame(thisdict) and I got the error as below: > ValueError: If using all scalar values, you must pass an index Can someone please help me?
You are supposed to assign the column as lists in your code. Try replacing lines 2 and 3 with : thisdict["Column1"] = [1] thisdict["Column2"] = [2] Complete code : thisdict = {} thisdict["Column1"] = [1] thisdict["Column2"] = [2] df = pd.DataFrame(thisdict) Output : Column1 Column2 0 1 2
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, pandas, dataframe" }
How can I protect my fingers while using a band saw? I intend on using a band saw to cut out large meeples (the wooden pieces from the board game Carcassonne) from a 2x4 board. I'm worried about cutting my fingers. !enter image description here What tool can I use to help keep my fingers out of harm's way? I've noticed push sticks, but the only ones I can find are push sticks that help you re-saw boards with a band saw. Is there a similar tool to help protect your fingers as you guide the board to cut out shapes?
Create a jig to hold the pieces in position for the various cuts. The jig will allow to maintain a safe distance from the blade and if designed well will give you a secure grip on the piece being cut. Also try to design your cuts for mass production. For example cut the gap between the legs and around the heads while all the pieces are still one long piece of wood. Then cut the gaps under the arms and free each piece from the strip at the same time. You may want to consider leaving 4-6 inches of uncut wood at each end of the strip to give you something to hold on to while cutting the last piece on the strip. When freeing pieces from the strip start in the middle and work each half of the strip to your 4-6" handle. I've included an image of the cuts I would plan, and a simple diagram of a jig to hold the piece while cutting. !Meeple Jig Diagram
stackexchange-diy
{ "answer_score": 19, "question_score": 16, "tags": "woodworking, safety, bandsaw" }
How to implement "Contact Us" view with a default Email destination address I am trying to build up a Contact Us View in one iOS project, What I am trying to do is: Put a `Text View`in a view controller, which will capture and save users' writing. If users press send button, the view controller will send the Email or message to customer service. How to implement this or any SDK recommended? Thanks in advance.
**MFMailComposeViewController** is fully dedicated for this. it has built in what you are trying to make. So don't write code to take this hassle. Let Apple do it for you. :) ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ios, swift, email, networking" }
Do uniformly continuous functions map complete sets to complete sets? Let $f: (M, d) \rightarrow (N, \rho)$ be uniformly continuous. Prove or disprove that if M is complete, then $f(M)$ is complete. **If I am asking a previously posted question, please accept my apologies and tell me to bugger off. I saw a similar problem but the solution was dealing with a Bi-Lipschitz function or some such business.** I believe this statement to be true and here is a rough sketch of my reasoning: Since $f$ is uniformly continuous, then $f$ maps Cauchy to Cauchy. Let $(x_n)$ be a Cauchy sequence in $M$. Since $M$ is complete, $x_n \rightarrow x \in M$. Again, because of $f$'s uniform continuity, we now have $(f(x_n))$ is Cauchy in $N$ and $f(x_n) \rightarrow f(x) \in N$. Thus $N$ is complete. By the way, I am studying for an exam. This is certainly not homework. I gladly accept your criticisms. Thank you in advance for your help.
Take $f:\mathbb R\longrightarrow \mathbb R $, $f(x)=\arctan x$. Then $$f(\mathbb R)=(-\frac\pi2,\frac\pi2)$$ and $f'(x)=\dfrac{1}{1+x^2}\leq 1$ which implies that $f$ is uniformly continuous. However, $\mathbb R$ is complete, while $f(\mathbb R)=(-\frac\pi2,\frac\pi2)$ is not complete
stackexchange-math
{ "answer_score": 4, "question_score": 12, "tags": "real analysis, cauchy sequences" }
How to connect vb.net to wamp server? Do you know of any way on how to connect wampserver or phpmyadmin localhost to vb.net. I mean adding, searching, deleting, updating, listing of data from the localhost database via vb.net?
Huge tutorial about VB.net and MySQL: < Smaller tutorial about VB.net and MySQL: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "vb.net, database connection, wampserver" }
superset algorithm using stl giving duplicate subsets I am trying to find superset of a given vector. I do this by recursion. Going iteratively I remove a value and then call the function with new set. I get all sets but they are repeated. Eg for 5 elements, there should 32 to 31 subsets, while I get about 206 subsets. This is my code using namespace std; int iter = 1; void display(vector<int> &v) { cout<<"case#"<<iter++<<": "; vector<int>::iterator i; for(i=v.begin();i!=v.end();i++) cout<<*i<<" "; cout<<endl; } void gen( vector<int> &v) { if(v.size()==0) return; display(v); vector<int>::iterator j,i; for(i=v.begin();i!=v.end();i++) { vector<int> t(v); j = find(t.begin(),t.end(),*i); t.erase(j); gen(t); } }
You don't have to pass v as argument everytime. Just make it global. And try every combination to find all subset. Complexity : 2^N vector<int>v; int iter = 1; int take[20]; void display() { cout<<"Case#"<<iter++<<": "; int n=v.size(); for(int i=0;i<n;i++) { if(take[i]) cout<<v[i]<<" "; } cout<<endl; } void gen(int x) { if(x==v.size()) { display(); return; } int i,j,n=v.size(); take[x]=1; gen(x+1); take[x]=0; gen(x+1); } int main() { int i,j,n; cin>>n; for(i=0;i<n;i++) { cin>>j; v.push_back(j); } gen(0); return 0; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "c++, recursion, vector, stl algorithm" }
Old refrigerator risks I just acquired a double door Amana refrigerator. I'm not sure when it was manufactured but from the design and the dates on referenced patent numbers on the back, it seems to be from the late 70s/early 80s. It seems to be working although it's giving off some cool air from the bottom. Is it safe to use it?
Safe? Yes. Economically wise? No. Refrigerators older than let's say the mid to late 90s are woefully inefficient, and use quite a lot of electricity compared to ones made in the last 15 years or so. Buying a newer fridge (even one 10 years old) will often pay for itself in just a few years in the amount of electricity saved. So if you're planning on using the fridge for more than a few years, it's likely wise to not run it and find something newer. Utilities in the US (and possibly even other countries) will often even give you a rebate on disposing of an old fridge like this.
stackexchange-diy
{ "answer_score": 4, "question_score": -1, "tags": "refrigerator, old house" }
How do I make a command give the first mention a role with the ID "973182673306660885" I have tried the below but i get the error: "msg.mentions.users.first.addRole is not a function" let BotBanRole = msg.guild.roles.cache.find(r => r.id === "973182673306660885"); const FMT = msg.mentions.users.first(); if (msg.content.startsWith('$BotBan')) { if (FMT === undefined) { msg.reply('Did not detect user') return; // Do not proceed, there is no user. } const FM = FMT.username; // Do stuff with the username msg.mentions.users.first.addRole(BotBanRole); msg.reply('Bot Banned ' + FM.tag) }
You were pretty close, give this a try. const BotBanRole = msg.guild.roles.cache.find(r => r.id === "973182673306660885"); const FMT = msg.mentions.members.first(); if (msg.content.startsWith('$BotBan')) { if (!FMT) { msg.reply('Did not detect user') return; } else { FMT.roles.add(BotBanRole); msg.reply(`Bot Banned ${FMT.user.username}`) } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, node.js, discord.js" }
Haskell arbitrary typeclass instance return type From the Haskell Book chapter on Monoids, I am writing quickcheck tests for semigroupAssoc :: (Eq m, S.Semigroup m) => m -> m -> m -> Bool semigroupAssoc a b c = (a S.<> (b S.<> c)) == ((a S.<> b) S.<> c) type IdentAssoc = Identity String -> Identity String -> Identity String -> Bool , invoking with quickCheck (semigroupAssoc :: IdentAssoc) Here is the arbitrary typeclass instance instance (Arbitrary a) => Arbitrary (Identity a) where arbitrary = do a <- Test.QuickCheck.arbitrary return (Identity a) My question is that in my arbitrary instance, I can return either (Identity a) or just a. (Identity a) is correct, but just a gives no compiler error and causes an infinite loop when run. Why is this?
Type inference changes the `arbitrary` call to point at the _same_ instance we are defining right now, causing an infinite loop. instance (Arbitrary a) => Arbitrary (Identity a) where arbitrary = do x <- Test.QuickCheck.arbitrary -- this calls arbitrary @ a return (Identity x) instance (Arbitrary a) => Arbitrary (Identity a) where arbitrary = do x <- Test.QuickCheck.arbitrary -- this calls arbitrary @ (Identity a) return x Every time we call a class method, the compiler infers which instance to call. In the former case, the compiler infers `x :: a` (only this type makes the code type check!), hence it calls `arbitrary @ a`. In the latter case, the compiler infers `x :: Identity a` (only this type makes the code type check!), hence it calls `arbitrary @ (Identity a)`, causing the infinite loop.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "haskell, quickcheck" }
Using System/User Variables as Parameters in an OLE DB Source Query I have got a SQL command like the following : SELECT * FROM temp1 a inner join (SELECT ID from temp2 where ID = ?) b on a.ID = b.ID WHERE a.ID = ? I know the query has incorrect logic. But my question is How will I set Variables as parameters here in the place of "?". If I exclude the joined part, it will work.
Edit the OLE DB Source. On the Connections Manager tab, click the Parameters... button. The Parameters dialog will display the parameters in the sequence they appear in the SQL statement. The sequence is determined by reading the SQL statement from left-to-right, top-to-bottom. To make an assignment to a parameter, select the variable from the Variables column.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ssis" }
How to recognize numbers in a string using JS? If we have a string, say '1, 2, 3, 4' '1, 2, 3 GO!' 'ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!' then how do I recognize that its has numbers and return true? I need it because while using, if(input == input.toUpperCase()) if a number is entered this condition returns true, so need to add an elegant way to stop the numbers from passing this condition. Edit1: The string is indeed comma separated, I already have googled ways that recognize non comma separated strings as numbers. Edit2: Added more examples of what I need to pass.
Regular expressions are appropriate for this: var str = "(1, 2, 3, 4)"; var containsNumber = /\d/.test(str); // true Here, `\d` is a regular expression that will match if your string contains a digit anywhere. * * * Ok, looks like you need to look for lowercase letters... If there's any lowercase letter it shouldn't be considered _yelling_. var str = "(1, 2, 3, 4)"; var containsLowercaseLetters = /[a-z]/.test(str); // false This will only work for latin letters though. In your case, it may be simpler to just state: var isYelling = (input == input.toUpperCase()) && (input != input.toLowerCase());
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript" }
How can I define the function body in a .h file? Sometimes I define bodies of small global functions in .h files (static inline). It works. Now I have larger global function. I need to to define it in .h file. I do not want it to be static inline. I tried the following trick with "dummy template": template <typename Tunused> int myfunction(...) { ... } to achieve this -- to define global function in .h file. Compiler complains "cannot deduce template argument for 'unused'". Do you guys understand what I an trying to do ? How can I trick the compiler ? I think I need to unsert some dummy usage of template arg into the function so that compiler can deduce it. Can anyone help ?
Honestly, I don't recommend putting large non-template function's definition in .h file unless there is definite reason that you can't put the definition in .cpp file. If you have to put the definition in .h, the following code might help: // .h template< int Unused > int myfunction_() { // definition } namespace { int (&myfunction)() = myfunction_<0>; } // .cpp int main() { myfunction(); } If you could show the reason that you have to put the definition in .h, better suggestions may be posted. **Edit:** Rewrote the code in the light of Bo Persson's pointing out.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, templates, visual c++, header files" }
Can anyone recommend *freeware* to reduce motion blur by deconvolution? Can anyone please recommend free (preferably also portable i.e. no need to install) software for Windows XP or later to improve image quality of large (12 megapixel) terrestrial (not astronomical) photos, by deconvolution to reduce motion blur (preferably automatically)? I've tried Unshake 1.5 by M.D. Cahill but the result seems worse than the original (looks oversharpened) and it crashes on 12 megapixel images.
In case this is useful to anyone else, I found that Image Analyzer 1.33 from MeeSoft is a freeware claiming to do "Deconvolution for out-of-focus and motion blur compensation".
stackexchange-photo
{ "answer_score": 9, "question_score": 18, "tags": "software, image quality, motion blur, deconvolution" }
How can I tell if Windows is running SMB? Due the vulnerability in Windows SMB Server (MS17-010), how can I tell if it is running? I am using Windows XP. None of the services I have running has the word "SMB" in the title or description. What is the name of the service that implements SMB Server?
Answer to this question: (1) There is no service that runs the SMB server. It is a native system process that runs in the NT kernel. (2) If the kernel is running SMB, it can be detected by giving the command `netstat -an` to display all network listeners. If port 445 is listening, then it means the SMB server is running.
stackexchange-security
{ "answer_score": 4, "question_score": 3, "tags": "windows, vulnerability, windows xp" }
Snowflake Web UI - How to Export Query Results I am using Snowflake's Web UI interface. I am running the following query: select top 100 * from table_1; When I click on the `COPY` button, it gives me everything into 1 giant line so it looks like this: col_1 col_2 col_3 1 steve 2021-04-12 21:13:65 Can the Web UI output the results so the headers are on 1 row and the actual data below that instead of 1 giant line?
Figured it out, don't use the copy button, use the actual download button right next to it. If life has taught me anything, it's ask a question and after you've wasted a minimum of 10 minutes of someone else's time, the answer will magically appear.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, snowflake cloud data platform, snowflake webui" }
php system command with output and return code I am looking for something in php that would given output (raw) of a system command in a variable along with the return code. * `exec` does this, but the output is in array and hence the data returned is not proper(as `\n` comes in new index). * `system` outputs the data in the output stream and not in a variable. * `shell_exec` does not give the return value but gives raw data.
Sounds like you're looking for output buffering: ob_start(); system($command, $returnCode); $output = ob_get_clean(); This should preserve all white-space characters at the end of each output line (`exec` as you wrote destroys these, so `implode` would not be an option). Alternatively, you can open a process and aquire the pipes (standard output, STDOUT) and read the output out of these. But it's more complicated (but gives you more options). See `proc_open`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "php, shell exec" }
How to sum all values with index greater than X? Let's say I have this series: >>> s = pd.Series({1:10,2:5,3:8,4:12,5:7,6:3}) >>> s 1 10 2 5 3 8 4 12 5 7 6 3 I want to sum all the values for which the index is greater than X. So if e.g. X = 3, I want to get this: >>> X = 3 >>> s.some_magic(X) 1 10 2 5 3 8 >3 22 I managed to do it in this rather clumsy way: lt = s[s.index.values <= 3] gt = s[s.index.values > 3] gt_s = pd.Series({'>3':sum(gt)}) lt.append(gt_s) and got the desired result, but I believe there should be an easier and more elegant way... or is there?
s.groupby(np.where(s.index > 3, '>3', s.index)).sum() Or, s.groupby(s.index.to_series().mask(s.index > 3, '>3')).sum() Out: 1 10 2 5 3 8 >3 22 dtype: int64
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "python, pandas" }
How did they prepare an image for printing before Adobe? How were images even prepared for printing before Adobe? What was the printing process? I really seem to be missing what they were doing between the Gutenberg press and the Adobe software when it comes to images...
The goal is to get images and text onto something that can carry ink and apply it to paper. For many years that has meant an offset printing plate. Even today, just because the image is digital, it still needs to get onto an offset printing plate, which still must be done photographically, either by passing light through a piece of film to expose the plate, or focusing light under electronic control, somewhat like using a digital projector ("direct to plate") to expose the light-sensitive emulsion on the plate. Look up "offset printing" and "lithography" and you will learn about these technologies. It's vitally important for graphic designers to understand the printing process or they can't possibly be effective and efficient.
stackexchange-graphicdesign
{ "answer_score": 1, "question_score": 3, "tags": "print design, print production, prepress" }
Generating Laguerre polynomials using gamma functions An exercise given by my complex analysis assistant goes as follows: > For $n \in \mathbb{N}$ and $x>0$ we define $$P_n(x) = \frac{1}{2\pi i} \oint_\Sigma \frac{\Gamma(t-n)}{\Gamma(t+1)^2}x^tdt$$ where $\Sigma$ is a closed contour in the $t$-plane that encircles the points $0,1, \dots, n$ once in the positive region. Now, we have to prove some things like that $P_n(x)$ is a polynomial of degree $n$, which is no problem. However, the assistant claims that $P_n(x)$ "is known as a Laguerre polynomial". However, calculating $P_n(x)$ for certain $n$ and comparing to values of the Laguerre polynomials $L_n(x)$ on the internet, I find that $$(-1)^n \cdot n! \cdot P_n(x) = L_n(x)$$ Could my assistant have made a typo which explains this missing factor; or could he mean that $P_n(x)$ have similar properties as the Laguerre polynomials, perhaps?
All you need to do is to multiply the integral representation by $(-1)^n n!$, so you will have the right integral representation $$ P_n(x) = \frac{(-1)^nn!}{2\pi i} \oint_\Sigma \frac{\Gamma(t-n)}{\Gamma(t+1)^2}x^tdt. $$ For instance, $$ P_5(x) = 1-5\,x+5\,{x}^{2}-\frac{5}{3}\,{x}^{3}+{\frac {5}{24}}\,{x}^{4}-{\frac {1}{120 }}\,{x}^{5},$$ which agrees with the Laguerre polynomial $L_5(x)$.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "complex analysis, polynomials, gamma function, contour integration, residue calculus" }
How should I view でより and でのより? My basic understanding of to compare things or ending letters, is failing me when there's a or in front of it. As I write this, I'm wondering, can read as "with, more", "in, more"? > **** > accept more responsibilities for less money > > **** > provide the area with a better Internet connection > > **** > to work longer hours for less money > > **** > together we can create a better world. * * * is really tripping me up. I'm not understanding how this functions at all. > **** > In Japanese, a typical way to write [America] with kanji is . [?] > > **** > It has long been suspected that longer working hours result in more accidents in the work place.
, when preceding an adjective as in your examples, means "more" or "-er": > more [numerous] > > more pleasant, smoother > > longer > > better > > more common, more typical As such, and should not be considered together. and go with the preceding word, and goes with the succeeding word.
stackexchange-japanese
{ "answer_score": 11, "question_score": 10, "tags": "particles, particle で, particle の, formal nouns, particle より" }
Is there any way to avoid "Debug Assertion Failed" Window in C++? This is the window that I want to prevent from showing when executing: ![enter image description here]( I know it is a bad practice but I am currently working on a code that collects all these exceptions and displays them in a different way, it would simply need the "Ignore" option to be executed automatically since the code is programmed so that right after I finished collecting the exception and can be processed
You _should_ be able to #define NDEBUG which ought to suppress this. Secondarily, try undefining _DEBUG as parts of the Windows API use that. * * * That said, I wouldn't do this: assertions are really there as a last resort and therefore are meant to help the programmer. If you want to handle an assertion in a different way then handle the situation that leads to it "by hand" before the assertion happens. Reference: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c++, exception, visual c++, runtime error, assert" }
On Error Resume next not working VBA I am using the Ctrl+F simulation using Macros for find a particular number from a sheet, I have added the On error resume next code in case it fails to find the value but the error handling is not working , I am getting the following message. ![enter image description here]( Here is the code: Sheets("Not filled").Activate On Error Resume Next Cells.Find(what:=refnumber, After:=ActiveCell, LookIn:=xlFormulas, _ lookat:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False).Activate
You are still trying to `.Activate` the (NOT) found cell. Dim fnd As Range, refnumber As Long refnumber = 123 With Sheets("Not filled") .Activate On Error Resume Next Set fnd = .Cells.Find(what:=refnumber, After:=ActiveCell, LookIn:=xlFormulas, _ lookat:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) On Error GoTo 0 If Not fnd Is Nothing Then fnd.Select Else MsgBox "Not found :(" End If End With This attempts to `Set` a Range object to the found location. If nothing was located, the `fnd` var is nothing.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "vba, excel" }
BeginForm html helper doesn't work with file upload I have a strongly typed view, a model and a simple post method. Model has one property: public HttpPostedFileBase File { get; set; } View looks as follows: <form method="post" enctype="multipart/form-data"> <input type="submit" name="Put" value="Excel" /> </form> And an action is [HttpPost] public virtual ActionResult Method(ModelVM model) { ... } What I've just shown works. But when I change explicit form declaration to the following code: @using (Html.BeginForm(MVC.SomeController.Actions.ActionNames.Method, MVC.SomeController.Name)) Then the action method don't bind the file to the model. Does anybody know why?
Because you haven't added `enctype` attribute to the form: @using (Html.BeginForm(MVC.SomeController.Actions.ActionNames.Method, MVC.SomeController.Name, FormMethod.Post, new { enctype = "multipart/form-data" })) { ... }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net mvc, file upload" }
SPARQL select RDF:ID I am trying to select the rdf:ID of an object with sparql (inside Protege) and I cant seem to get the rdf:ID. Has anyone seen this problem. The SPARQL query i am using is: `Select * where (?element rdf:id ?id)` The following also does not work: `Select * where (?element rdfs:label ?id)` Took a suggestion, but still this is no go: `Select * where (?element rdfs:about ?id)` But this does: `Select * where (?element rdfs:comment ?id)` All I get is "No Matches". So I can select the comment but not thelabel...ideas? UPDATE:: After some more research, selecting the following: `Select ?subject ?property ?object where (?subject ?property ?object)` Does not come up with any of the RDFS properties. Am I missing something major? (I can slect it with rdfs:comment, but that does not show up either...
If you're looking for the URI of all RDF subjects, you would run: `SELECT ?subject WHERE { ?subject ?predicate ?object }` Note that you need curly braces and not parentheses. Also note that case matters in RDF, so be very careful about the spelling and capitalization of your URIs (and prefixes/local names). To dajobe's point regarding entailments (inferred triples), `rdfs:label` is an OWL annotation property and will be ignored by inferencers unless you include your own rules and/or OWL constructs. In other words, if you're just starting out with RDF, I would be surprised if a reasoner inferred triples with `rdfs:label` as a predicate.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "rdf, sparql" }
adjust the size of boxplot so that label become clear I am plotting the box plot graph but the x-axis labels are overlapping to each other and graph is looking messy. I want to increase the width of graph so that labels become clear, but am unsure what methods to use. My code looks like: df2=Restaurant.boxplot(by ='Item', column =['Profit'], grid = True) df2.plot(kind='box', figsize=(20,15)) plt.savefig('finalBoxPlot.png', bbox_inches='tight') plt.show() And the resulting graph looks like this
If you are OK just rotating the labels instead of adjusting plot size you would accomplish this with: labels = ax.get_xticklabels() plt.setp(labels, rotation=90, horizontalalignment='center') Where `ax` was defined earlier in my code as ax = fig.add_subplot(1, 3, 1) # whatever shape But I'm not sure if this would work without plotting to an `ax`. You could always run fig = plt.figure(figsize=(15, 15)) # this is how I adjust figure sizes too ax = fig.add_subplot(1, 1, 1) To create a single `ax` on your plot, making the above method viable, and then you would plot your information with `ax.plot()` instead of `plt.plot()` for instance. I am not sure how applicable this is with `pandas` dataframes though, since I haven't really worked with them.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python" }
Not able to append arrays into a list So I want to run this code to find a random element of a list containing numpy arrays with a certain condition The conditions are that is for every element of arr1 not equal to arr2 it will append the element of that index of `er` and append it to `lst`: import numpy as np import random arr1 = np.array([1,2,3,4]) arr2 = np.array([1,2,6,3]) arr = (arr1 == arr2) er = np.array([[1,2],[-6,7],[4,7],[6,2]]) lst = [] for i in arr: if i == False: lst.append(er[i]) print(random.choice(lst)) But I don't know why its returning a empty list.Please help
arr is a boolean array, so in for loop i is True/False values (not an index) for i in arr: Change for i in arr: if i == False: lst.append(er[i]) To: for i, v in enumerate(arr): # retrieving index and value if v == False: # test value lst.append(er[i]) # use i to index into er
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "python, arrays, numpy" }
what is the advantage of using classes instead of directly use GUI controls values i have a scenario of user management form. The user have following textboxes (`txt_fname`, `txt_lname`, `txt_email`, ..etc) and some other information. Why some programmers are using a class to hold the user information and then save this class to database? There is the possibility to save the information directly from reading the values from the controls (textboxes) and send them to DB. Why using a class first ? i would like to ask what is the advantage of using class in such situations. Like : `users`, `Products`
It is good approach to seperate layers/components/classes, that does not have strong connection (Loose Coupling). The reason is that if you need change view or reuse user, you are not limited by the strong connection of "view" and "model" class. For example, if you want to take the user and use him in another application, you just take that class and you are done. If you are "strong-connected" to view, there is no easy way.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "c#, winforms, visual studio 2010, oop, webforms" }
Is the following sentence grammatically incorrect? If so why? > No, impossible. Could someone I barely knew, know so much about me? Is this sentence gramatically incorrect? If so, what would be the correct version? (While maintaining more or less the same structure?)
With one minor correction, I can imagine reading something similar in a contemporary novel, or hearing something similar in a movie or television show. The context would be a teenage girl or young woman talking to herself about the weird situation she has found herself in. > No, impossible. How could someone I barely knew, know so much about me? The first example "sentence" is not a complete sentence. It is short for something like "No, this situation had to be impossible." The example question is a complete question. It is short for either "How could someone I barely knew know so much about me?" or "Was it possible for someone I barely knew to know so much about me?" The complete example is short for something like: > No, this situation was impossible. > Was it possible for someone I barely knew to know so much about me? > Of course not.
stackexchange-ell
{ "answer_score": 2, "question_score": 0, "tags": "ellipsis" }
Why the imaginary half circles is this plot? I plotted the square roots of the Oppermann boundaries and got this: !enter image description here Why the imaginary half circles?
It's enough consider the case of $\sqrt{k^2-k}$, since the second is just the $k\mapsto -k$ reflection of the first. Writing $\sqrt{k^2-k}=x+I y$ and squaring both sides gives $x^2-y^2+(2xy)i=k^2-k.$ Since the plot is for real $k$, we can match the real and imaginary parts of the two sides and conclude that $x^2-y^2=k^2-k$ and $xy=0$. The latter requires that at least one of $x,y$ must vanish for any given $k$ (which is apparent in your graphs above.) If $x=0$, then $y^2=k-k^2$; but $y^2$ can't be negative, so $k$ must satisfy $k-k^2\geq 0$ aka $0\leq k \leq 1$. This is the domain of interest, so this expression for $y$ is what we want. But we can complete the square to rewrite this equality as $y^2+(k-\frac{1}{2})^2=\frac{1}{4}$, which we may recognize as the equation of a circle of radius $1/2$ centered at $(k,y)=(1/2,0)$. Since only the positive root is taken, the plot is indeed a semicircle.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "elementary number theory, experimental mathematics" }
how get value of JSON object within Json ..? Please Help "_attachments": { "kiran.jpg": { "content_type": "image/jpeg", "revpos": 6, "digest": "md5-mEsoX4ljN1iJlF2bX1Lw2g==", "length": 4601, "stub": true } } I want to value of content_type and length. how to get that. friends i dont know the value of kiran.jpg, its come random image name form database
Use object.keys to loop over the keys in the _attachments object to find the name of each record. var data = { "_attachments": { "kiran.jpg": { "content_type": "image/jpeg", "revpos": 6, "digest": "md5-mEsoX4ljN1iJlF2bX1Lw2g==", "length": 4601, "stub": true }, "otherPerson.jpg" : { "content_type": "image/jpeg", "revpos": 8, "digest": "md5-mE4ljdfhgfh1iJlF2bX1Lw2g==", "length": 1337, "stub": false } } }; Object.keys(data._attachments).forEach(function( name ) { var contentType = data._attachments[name].content_type; console.log(contentType); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -4, "tags": "javascript, jquery, json, couchdb" }
Fetch custom size Facebook profile picture I would like to retrieve a Facebook user's profile picture, but at a custom size (e.g.: 40px x 40px). Is this possible, or only the default values (normal, square, small and large) are fetchable?
~~Only those three values are valid from the API. For a 40x40 image though, you can easily resize the 50x50 (`square`) image.~~ ~~Perthis blog post it's now possible to get custom profile picture sizes:~~ The blog post was deleted, but it's still possible to get a custom profile picture size using the following parameters:
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 3, "tags": "facebook, facebook graph api" }
Skyrim freezing while trying to enter Haemar's Shame For the past hour I've been trying to enter Haemar's Shame so I could complete a Companions Request but it freezes everytime. I'm running Ps3 and have removed old save files. I don't have any idea what the deal is. I have about 120 hours logged and my save file is 13mb. Any ideas?
The game crashes in Haemar's Shrine if you've already completed "A Daedra's Best Friend". Bethesda have announced a fix for this issue in the Skyrim 1.4 patch.
stackexchange-gaming
{ "answer_score": 3, "question_score": 3, "tags": "the elder scrolls v skyrim, ps3" }
Rails redirect_to subdomain of account using simple syntax I'm a Rails noob and I'm sure this is fairly straightforward but I'm not sure how to do it, so I'm going to ask for help. Here's my situation. I have a Rails 3 app. The app follows the subdomain as account key pattern like Basecamp does. What I would like to do is redirect to the subdomain using this syntax (let's say the current account is `@account`). `redirect_to @account` Currently, (as it should), this redirects to `/accounts/(@account.id)`. What I would like to do is make it redirect to `(@account.subdomain).myapp.com`. Is there any way to do this?
You can use: redirect_to "
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "ruby on rails, ruby" }
How to typecast a HashMap to a WeakHashMap? I have a method like this :- public Map<String,String> loadProperties() Exception{ Map <String,String> params = new HashMap<String,String>(); . . . return params; } The above method returns me a Map of (key , value) from the DB. I need to TypeCast loadProperties() to a WeakHashMap. Below I have another class called Service. I tried the typecasting in its constructor but it is giving me ClassCastException. "java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.WeakHashMap" Below is the Service class:- private Service() throws Exception { configPropertiesCache = dao.loadProperties(); configPropertiesCache = (WeakHashMap<String, String>) dao.loadProperties(); I am curious to know why its not working ?
It doesn't work because a `HashMap` simply is not a `WeakHashMap`. Type casting does not do any kind of magical conversion from one type to another type. The only thing that a type cast means is that you tell the compiler that you want it to treat one type of object as if it is another type of object - but a check will still be done at runtime to check if the object you're casting really is what you cast it to, and if the check fails you get a `ClassCastException`. Either create the map as a `WeakHashMap` in your `loadProperties()` method, or if you cannot modify that method, copy it into a `WeakHashMap`: configPropertiesCache = new WeakHashMap<>(dao.loadProperties());
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 0, "tags": "java" }
Incorrect versions of files in downloadable GitHub zip I am creating an installer for my application that relies on downloading my GitHub repository as a zip file. However, I noticed that GitHub is not packaging the correct version of several files into the zip. When I download this file from the file tree, I get the correct version (506 KB). However, when I download the repository, the file has a different size (514 KB). This issue is causing my installation to fail. What should I do?
The problem was that in my `.gitattributes` file, I had the line `* eol=crlf`. This was marking all my files as text files and changing their line endings, which was corrupting my binary files. To fix the problem, I excluded my binary files from being marked as text files by adding the following lines to my `.gitattributes` file. *.dll -text *.exe -text I then removed and re-added the affected binary files. Thanks to GitHub support for helping me to figure this out!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "git, github, version control, installation" }
Why is my virtual machine's screen resolution so small? I just started using Hyper-V, which comes with windows 8. I created a VM with windows 7. It works fine, even if a bit slow, but I can't get the screen resolution higher than 1152 by 768 even though the root windows goes up to 1680 by 1050. I have installed the integration tools in the vm, do I need something else, display drivers maybe ?
I found this answer via reddit, by user 6306 : hyper-v has limited resolution when you access the console view, it's a professional virtualisation application and doesn't need fancy consumer features. The console view is effectively "sitting in front of the machine" view, most administration is done through remote desktop. The best thing to do is download the excellent remote desktop metro app and rdp to your machine for full screen goodness. (enable remote access on the VM System Properties>Remote Tab)
stackexchange-superuser
{ "answer_score": 6, "question_score": 5, "tags": "virtualization, hyper v" }
How to evaluate $\int_C y^2 \,dx + 2xy\,dy$? I am asked to evaluate the integral $\int_C y^2 ~dx + 2 x y~ dy$ where $c$ is the curve $(t^8,\sin^7(\frac{\pi t}{2}))$, where $0\leq t\leq 1$. My attempt so far is: $dx = 8t^7 dt$ and $dy = \frac{7\pi}{2}\cos(\frac{\pi t}{2})\, dt$ So $\int_C y^2 \,dx + 2xy\,dy = \int_0^1 (8t^7\sin^{14}(\frac{\pi t}{2}) + 2t^8\sin^7(\frac{\pi t}{2}) ) \,dt$ But this seems to be a very difficult integral to solve, so I'm pretty sure my working is incorrect.
$y^2dx+2xydy=d (xy^2).$ Then the integral does not depend on the path. The initial point is $x_0=0^8=0, y_0=\sin^7 0=0$ and the end point is $x_1=1^8=1,y_1=\sin^7\frac{\pi}{2}=1$. The integral is equal to $1 \times 1^2 - 0 \times 0^2=1$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "calculus, integration, multivariable calculus, definite integrals" }
A weird org.hibernate.DuplicateMappingException which happen only if my web app is deployed to tomcat on CentOS I am creating a java web app running on Spring framework, Tomcat, Hibernate(but, only JPA API). I've written some code that connects to database with named queries that are externalized into xml files like: this web app is working fine on my local tomcat on OS X. but it is not working on CentOS machine. when it is deployed on CentOS, initialization of Spring context fails due to: Caused by: org.hibernate.DuplicateMappingException: Duplicate query mapping ProductReview.getProductReviewNamedParameter From my knowledge, DuplicateMappingException should happen when the `ProductReview.getProductReviewNamedParameter` named query is defined two or more times. but I defined exactly once and this app working fine on my local machine. Has anyone experienced a similar problem like me? Any answers, your experiences, or insights would be awesome!
You are using classpath*:jpql-mapper/**/*.xml classpath* searches the whole classpath for all occurrences of this file pattern. So if you accidentally have your named queries twice in the classpath, this would explain the exception. So as a first step remove the '*' after classpath, so it looks like : classpath:jpql-mapper/**/*.xml The way the classpath is built and also the jars contained (tomcats own jars, versions), may be different in the two environments. This may lead to different behaviour, as you experienced.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, spring, hibernate, tomcat, jpa" }
Console.ReadKey is processing the last item before quitting I have a tiny command line utility which reads user input and adds all input to a list. When the `Esc` key is pressed, the program is quit. However, upon pressing the `Esc` key, even the Escape key is being added to list and then the program quits. How can I prevent the `Esc` key from being added to the list? Code: ConsoleKeyInfo cki; List<string> stuffs = new List<string>(); Console.WriteLine("Press Escape (Esc) to quit the program."); do { cki = Console.ReadKey(); stuffs.Add(cki.Key.ToString()); Console.WriteLine(); } while(cki.Key != ConsoleKey.Escape); Console.WriteLine("You have entered the following data:"); foreach(string stuff in stuffs) Console.WriteLine(stuff);
Change the loop so that you check the value prior to adding it to your list. For example, this loops the same, but breaks when Escape is pressed: while(true) { cki = Console.ReadKey(); if (cki.Key == ConsoleKey.Escape) break; stuffs.Add(cki.Key.ToString()); Console.WriteLine(); }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "c#, console application" }
A method for propagating labels to unlabelled data I have a large set of data and a small subset is labelled as being in class 'A' and the rest is unlabelled. I know that some of the unlabelled data should also be labelled 'A'. In order to label some more of the data my idea is to do the following: 1. Build a classifier on the whole data set separating the class 'A from the unlabelled data. 2. Run the classifier on the unlabelled data. 3. Add the unlabelled items classified as being in class 'A' to class 'A'. 4. Repeat. There are lots of parts that are unclear and/or problematic such as when to stop and how exactly to set the thresholds for when to accept something as being in class 'A'. Is a method like this known already in the literature so that I can gain some ideas for how to do it properly?
Learning from positive and unlabeled data is often referred to as PU learning. what you describe is a common approach to these kinds of problems, though I personally dislike such iterative approaches because they are highly sensitive to false positives (if you have any). You might want to check out two of my papers and references therein for an up-to-date overview on current research for these problems: * A Robust Ensemble Approach to Learn From Positive and Unlabeled Data Using SVM Base Models < (published in Neurocomputing) * Assessing binary classifiers using only positive and unlabeled data: < The first paper describes a state-of-the-art method to learn classifiers and the second is the only approach that allows you to estimate any performance metric based on contingency tables from test sets without known negatives (you read that right). Both papers also provide a good overview of the existing literature on this subject.
stackexchange-stats
{ "answer_score": 6, "question_score": 6, "tags": "machine learning, classification, missing data, semi supervised learning" }
Querying Mobile Push Demographics Table I'm attempting to query our mobile push demographics table that's tied to the contact record to pull some Application Version data and I'm struggling in Query Studio. The name of the table is MobilePush Demographics. I've attempted FROM: [MobilePush Demographics], __[MobilePush Demographics], ent.[MobilePush Demographics], ent._[MobilePush Demographics]
The proper name for the Mobile PushDemographics data view is `_PushAddress`. There's an answer made by @Daniel that lists all default fields and their datatype here, but be aware that you your data extension field names can't begin with an underscore, so when you query this data view, you need to rename them using an alias, for example: Select _ContactID as ContactID From _PushAddress If you have any custom attributes added to MobilePush Demographics, their names in this data view will not be proceeded by an underscore, so using an alias won't be needed.
stackexchange-salesforce
{ "answer_score": 4, "question_score": 1, "tags": "marketing cloud, sql, mobilepush, data views, data designer" }
get categories from a limited query i have the following query: select company_title,address,zipcode.zipcode,city,region,category from test.companies left join test.address on companies.address_id = address.address_id left join test.zipcode on companies.zipcode_id = zipcode.zipcode left join test.categories on companies.category_id = categories.category_id where company_title like '%gge%' limit 10; as you see, each company has a category. i was wondering if i can get a list of the categories (from the total results, not the limited one) just as CALC FOUND ROWS does?
Nope, you are asking for a totaly different set of data here, you can only do another query or process this with your application code by preloading all data and counting the distincts in memory. If your dataset is big, then i'd recommend using a second query, mysql can support 1 more query easy, but working with 100 000 rows to count the distinct and preload everything is usually not the wiser choice :)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql" }
~たい次第 expression meaning What does the grammar expression ~{} mean For example:
I think is being used as a formal and polite way to mention the circumstances or reason for the desire expressed by . > **** > > " **So** I eagerly await your invitation." You could also say, > **** > **** with basically the same meaning, just a little less polite and formal.
stackexchange-japanese
{ "answer_score": 1, "question_score": 2, "tags": "grammar" }
Algebra question :) How is: $\dfrac{140 \cdot \tan 24.5^\circ}{\dfrac{1 - \tan 24.5^\circ}{\tan 31.8^\circ}}$ the same as: $\dfrac{140 \cdot \tan 24.5^\circ \tan 31.8^\circ}{\tan 31.8^\circ - \tan 24.5^\circ}$ Thank you!
# Hint: Multiply numerator and big denominator by $\dfrac{\tan 31.8^\circ}{\tan 31.8^\circ}$ You know what happens? > It cancels out in the denominator
stackexchange-math
{ "answer_score": 1, "question_score": -3, "tags": "trigonometry" }
Is hooks the same as theme functions drupal and what triggers what? I pretty much understand Drupal API hooks so no need to explain about that. I am interesting in theme hooks and theme functions. It is impossible to get the full picture hope you can?
The more and more I read theme functions are pretty much functions that are triggered by Drupal by the hook implementation. theme functions has following naming convention: mytheme_theme hook name; theme functions should not be called directly but has to be invorked by the theme() a specific function with two parameters 'hookname' and $vars either string or an Array. If you have a preprocess function - lets call it mytheme_preprocess_theme hook name It will be called before mytheme_theme hook name - behind the scene all preprocess functions are called before theme functions. If verified by a developer @ Drupal's support forum.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "drupal 7, theming" }
find 2nd highest salary in sql There are two tables, `Employee` and `Salary`. * The `Employee` table has columns `EmpID`, `EmpName` of employees * The `Salary` table contains `EmpID`, `Payment` I want to retrieve employee details whose payment is 2nd highest. Please give me solution
Use this query SELECT MIN(s.Payment), e.EmpName, e.EmpID FROM dbo.Employee e INNER JOIN Salary s ON e.EmpID = s.EmpID WHERE e.EmpID IN (SELECT TOP 2 EmpID FROM dbo.Salary ORDER BY Payment DESC)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -5, "tags": "sql server" }
Is it possible to pass iframe query strings through parent URL? I have a webpage with an iframe. What I want to be able to do is have the query string from the iframe pass through the parent url. For example: Parent URL: `mysite.com/iframe-page` iframe URL: `iframe.com` When a link is clicked on in the iframe the iframe url changes to `"iframe.com/?filter=google"` I would like it set up so that the parent url could start as mysite.com/iframe-page then when the link in the iframe is clicked the url changes to `mysite.com/iframe-page?filter=google` Is this something that is possible to do?
Links in the `IFRAME` can target the parent <a href="mysite.com/iframe-page?filter=google" target="_parent">Google</a> Once the parent page loads, it can set the `IFRAME`'s URL based on it's own query string. window.onload = function() { document.getElementById('myIframe').src = 'iframe.com' + location.search };
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, php, jquery, wordpress, iframe" }
Enqueueing scripts and styles multiple CPTS I am trying to load several scripts and stylesheets into a plugin I am creating. I want to load scripts into multiple CPTs within admin. I have got this far: function fhaac_admin_enqueue_scripts(){ global $pagenow, $typenow; if ( ($pagenow == 'post.php' || $pagenow == 'post-new.php') && $typenow == 'fhaac' ){} } The scripts are being loaded into the fhaac, but nothing else. I am not sure how to add multiple CPTs. I tried adding them in an array, but it didn't work. Help would be greatly appreciated. Cheers
There is a built-in function that you can use, instead of globals. The `get_current_screen()` function allows you to get the information associated with the current page. One of its return values is `post_type`. So you can check against an array of post types to see if anyone matches. function fhaac_admin_enqueue_scripts(){ $screen = get_current_screen(); if ( in_array( $screen->post_type, array('fhaac','blabla')) && $screen->base == 'post' ) { // Do something } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, wp enqueue script, wp enqueue style" }
Change all url titles - Remove illegal characters I've just noticed that a client has created a large number of entries with illegal characters in the url titles. This is causing all osrts of problems with entries displaying incorrectly. Is there a quick and dirty way to mass change all of the entry titles to remove the illegal characters (commas, periods, apostrophe's etc)?
You can run the update query directly to replace these special characters like: UPDATE exp_channel_titles set url_title = REPLACE(url_title, '+', ' ') WHERE channel_id=1 AND status='open' AND site_id=1 The above sql will replace + character with space of all the entries having channel_id as 1 and status as 'open'. You need to run the query for each character which you would like to remove/replace. I would suggest you take a backup to avoid any accident. I hope it would help you.
stackexchange-expressionengine
{ "answer_score": 1, "question_score": 0, "tags": "url title" }
Use jQuery to Read Text then Change I am using a CMS that generates some code for me. I am having the CMS auto-generate the date a page was last updated. (Note: This page contains information that is time sensitive and it is beneficial for the end user to see when the page was last updated.) The system generates the following time stamp: `24-May-2013 11:54 AM`, however, I would prefer the date to look like so: `May 24, 2013` (to follow the US Standard way of writing time) and drop the time completely. The code looks like so: <p>Last Updated: <span class="time">24-May-2013 11:54 AM</span></p> I believe this would be possible using jQuery but I do not know how to do this. Any recommendations on how to use jQuery to do this would be welcome!
$(".time").each(function() { var $this = $(this), // regex to retrieve day, month and year stamp = /([0-9]{1,2})-([a-z]*)-([0-9]{4})/i.exec($this.text()) $this.html(stamp[2] + " " + stamp[1] + ", " + stamp[3]); }); See the jsfiddle for demo: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, jquery" }
Definition of Tor functor in an arbitrary abelian category Let $\mathcal{C}$ be an abelian category. We define $\text{Ext}_\mathcal{C}^n(A,B)$ for objects $A$ and $B$ via $n$-extensions of $A$ by $B$ as described here, with $\text{Ext}_{\mathcal{C}}^0(A,B):=\text{Hom}_{\mathcal{C}}(A,B).$ This coincides with the definition of $\text{Ext}$ in terms of resolutions if $\mathcal{C}$ has enough projectives or enough injectives. Is there a corresponding definition for $\text{Tor}_\mathcal{C}^n(A,B)$? $\text{Ext}$ starts with the abelian group of morphisms $A\to B$, whereas Tor starts with the tensor product $A\otimes B$. Yet there is no tensor product in an arbitrary abelian category, so I don't see how Tor can work in this abstract setting. What am I missing?
You don't miss anything. It is not possible to define $\mathrm{Tor}^n$ in an arbitrary abelian category. You need an abelian $\otimes$-category with enough projectives.
stackexchange-math
{ "answer_score": 4, "question_score": 1, "tags": "category theory, homological algebra, tensor products, abelian categories" }
Where to download the Elsevier journal latex template? Please, I feel lost I am trying to dowsnload the LaTeX template of this journal `Robotics and Computer-Integrated Manufacturing` template (`Elsevier`)? I do not find any information about the template in their web site: Elsevier.com I am using ubuntu, I have tried to use this template: els-cas-tem­plate els-cas-tem­plate But I do not have the right format of robotics-and-computer-integrated-manufacturing which as I understand and I am not sure must look like the style of this paper Safety and efficiency management in LGV operated warehouses
You can start with your first given link in your question. Then you will find `search` (red circle marked with 1): ![enter image description here]( Then search for `latex template` (see red circle marked with 2) and click on the sign in red cirle marked with 3. After that you get a new content and the first result seems to be what you are searching for (red circle marked with 4) ... Seems you can use the class on ctan, but please read the instructions ... ![second page](
stackexchange-tex
{ "answer_score": 5, "question_score": 4, "tags": "templates, ubuntu, elsarticle" }
URL Hack - Prepopulate custom field of a custom object not working I have a question regarding prepopulating a custom field (Id : 00H280000073992) in a custom object (ContactDetail). I used the URL hack tip, but doesn't work for me. It works when I change the URL and remove the prefix CF : The custom field gets populated. However, the button syntax doesn't recognize the Id without the prefix CF, and I got this `Error: Syntax error. Missing field name`. For example : {!URLFOR($Action.ContactDetail.New, null, [00H280000073992='test'])} On the other hand, when I prefix with CF, the syntax is correct, the field is not populated. For example : {!URLFOR($Action.ContactDetail.New, null, [CF00H280000073992='test'])} Can you help me ?
I found a solution : {!URLFOR($Action.ContactDetail__c.New, null, ["00H280000073992"='test'])}
stackexchange-salesforce
{ "answer_score": 1, "question_score": 1, "tags": "apex" }
jQuery UI dialog - wait until close animation is completed On my website I have two jQuery UI dialogs. One dialog just shows gif image (working animation). I call it before doing AJAX request. After AJAX request is done, I need to close that first dialog, and show second. I do it like this: $("#dialog-working").dialog("close"); $("#dialog").dialog("open"); but this obviously isn't working. When I do this, both dialogs are visible for some time. Because of that, I am searching for a way to open second dialog only after first dialog is close (after his animation has completed). Can you help me ? Thanks !
Your questin is not very clear. To do something after the dialog closes: $('#dialog').bind('dialogclose', function(){ //Do something });
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "jquery, jquery ui, jquery dialog" }
Mysql Join non matching tables with one to many relationship I am trying to get all results from table 1 (Reports) and join the other two tables onto it (users) and (workorders) Reports has keys relating to Users and Workorders but they are stored in csv values. I am trying to peform something similar to this psuedo code `SELECT * FROM reports LEFT JOIN users ON reports = (WHERE users.userID IN (reports.users)) LEFT JOIN workorders ON reports = (WHERE workorder.status IN (reports.filters) AND reports.reportid = 10 ` reports.users and reports.filters look like "1,2,3,4,5,6"
If I understand correctly (meaning that `reports.users` and `reports.filters` are strings of comma-delimited values), you need the `FIND_IN_SET` function for this: SELECT * from reports LEFT JOIN users ON FIND_IN_SET(users.userID, reports.users) LEFT JOIN workorders ON FIND_IN_SET(workorder.status, reports.filters) AND reports.reportid = 10
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, mysql, join" }
Android Hebrew RTL String With Numeric Value Flipped I would like to display a String with my app name and it's current version. The app name is in hebrew, for some when I combine hebrew text with numeric value, the numeric value is flipped. versionTextView.setText("אפליקציה גרסה "+this.getResources().getString(R.string.app_version)); for example: app version is 1.0, being display as 0.1 on emulator.
Sounds like a bug in the Android bidi algorithm. Try adding left-to-right marks around the numbers: versionTextView.setText("אפליקציה גרסה " + "\u200e" + this.getResources().getString(R.string.app_version) + "\u200e" ); (If this works, you may be able to eliminate the second one.)
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 7, "tags": "java, android, hebrew, right to left" }
Exit whenever a warning is thrown I'm getting divide by zero (and other, similar) `Warning`s in my code --- these "shouldn't" [1] be happening --- but they're hard to track down because no backtrace is provided. **Is there a way to make python raise an`Error` and throw a backtrace any time a `Warning` occurs?** In a perfect world I'd be looking for something I can set in the beginning like: DEBUG = True ... sys.DemandPerfection(DEBUG) # Exit on all Warnings ... [1]: In terms of my _desired_ results
Yes, just pass the command line option `-W error` to Python interpreter or set `PYTHONWARNINGS` to `error`. But I think the solution you want is import warnings warnings.simplefilter('error') which should also work for IPython (you may want to put it into startup directory for convenience).
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "python, error handling, warnings" }
Change timezone text to Amsterdam this may sound silly. But in the backend we have timezone set under configuration/general = W.Europe/Berlin. This is the same timezone as Amsterdam. Amsterdam is where our webstore is located. When I post a blog or update it is timestamped with x.y.z time @ W.Europe/Berlin .... would like it to be W.Europe/Amsterdam. Could I just look the string up in core config or another table and change it there? Or would I be breaking a lot of stuff? (I can image time is in the very core of a system) Or can I add a timezone? Many thanks
This string is, as far as I know, used for setting the PHP timezone as well. Since you want to change how data is displayed I'd suggest "translating" it in the presentation layer, the PHTML files. This way it can't have any impact on the rest of the code.
stackexchange-magento
{ "answer_score": 1, "question_score": 1, "tags": "configuration" }
Objective - C: Combine multiple string arrays I have multiple NSString Arrays that I would like to combine into a single array based on user preferences. The arrays are created: static const NSString *string1[] = {...}; static const NSString *string2[] = {...}; static NSMutableString *string3[] = { }; String3 is the holding array where all of the user's choices are added. There are 8 different strings that could be toggled on or off, so a fair number of possible combinations. I've tried a number of things with no success. For example: *string3=[string3 arrayByAddingObjectsInArray:string 2]; That gives warnings: `Instance method '-arrayByAddingObjectsInArry:' not found (return type defaults to 'id')` and `Receiver type 'NSMutableString **' is not 'id' or interface pointer, consider casting it to 'id'` Thanks for your help.
Your basic problem is that you're confusing two different things called "arrays." What you have there are C arrays — they're not objects, so you can't send messages (such as `arrayByAddingObjectsInArray:`) to them. What you _want_ is an NSArray. Declare them all as `NSArray *strings1, *strings2, *strings3`, and then write some method to initialize them like so: + (id)createArrays { strings1 = [[NSArray alloc] initWithObjects:@"Something", @"Something else", nil]; strings2 = [[NSArray alloc] initWithObjects:@"Yet another thing", nil]; strings3 = [[strings1 arrayByAddingObjectsFromArray:strings2] retain]; } You'll want to make sure you manage your memory correctly here or you'll leak like crazy. It's usually better to have objects belong to some class, so you can use setters than manage memory for you, rather than store them in global or static variables.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "objective c, ios, arrays, string" }
Kotlin: Java can't resolve Kotlin Symbol? I have a Kotlin Code just like the below, `SingleKotlin.instance` can be called by the other Kotlin files class SingleKotlin private constructor(){ companion object { val instance by lazy { SingleKotlin() } } } However, when I try to call `SingleKotlin.instance` from java, it shows can't resolve symbol 'instance' I don't understand why, anybody can explian and how can I solve this problem?
Just add @JvmStatic annotation above field (as said in this documentation < So, your code should be like this: class SingleKotlin private constructor(){ companion object { @JvmStatic val instance by lazy { SingleKotlin() } } } And now you can call it like SingleKotlin.instance
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 7, "tags": "java, kotlin, single instance" }
DBContext Added/Attached Event? EF 4.1 RC. I want to run some code after an entity has been added/attached to the DBContext. Is there an event for this (I can't find one). Basically I want to check if the added/attached entity is of a certain interface and if it is, do some stuff with it. Thanks!
Unfortunatelly there are no such events available and there are no extension points to add such events. That is in my opition one of the biggest EF failure. The extensibility = zero. The only thing you can do is override `SaveChanges` and before executing `base.SaveChanges` use `ChangeTracker` to get all attached and added entities of your type and execute your logic. But it is not the same as triggering an event when attaching or adding an entity to the context.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 9, "tags": "entity framework, ef code first, entity framework 4.1" }
Network Ports on server state "media state authentication failed" I have a server running Windows Server 2008 Enterprise in a 2k3 domain. Only two Ethernet ports are active with static IP addresses assigned to each. Even though the interfaces are issuing that error, I still have full LAN and WAN access. I do not have any errors logged in the Event Logs. Any help would be greatly appreciated from this new Server Fault user.
Thanks for the help guys. Apparently the network drivers Dell provided for the R710 needed to be installed without a network cable plugged into them. For some reason the driver installs, restarts the port, and then finishes the installation. So, unless in the split second you disabled the port, it attempted to allocate an IP from DHCP and then canceled. Thereby botching the driver install. The is for Broadcom drivers for Dell PowerEdge R710's.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "windows server 2008" }