INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
When defining keys in table, why is it inserted in a random order? While working on a Love2d project, I noticed that when defining tables with a key and putting said tables in another table, in a loop, the tables were being inserted in a random order. To test this, I made a short script that will hopefully explain my predicament a little better. My first assumption is because the keys are inserted wherever I have memory available, though I'm not sure. I've never encountered this before, anyone have any ideas? ![enter image description here](
Lua implements tables as hash tables, hence the apparent random order when traversing them. That is by design so that access to tables can be done in amortized constant time. If order is important to you, use sequential indices and complex values, like this t[1] = { key="CA", value="California" } t[2] = { key="TX", value="Texas" }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "random, lua, key, lua table" }
Crystal Report formula to reset a count? ![]( I want to get the total qty of items sold by year by each part number. So far I have the following formula: if {INVOICE_DATE} >= DateTime(2012, 01, 01) and {INVOICE_DATE} <= DateTime(2012, 12, 31) THEN Sum ({INVOICE_QTY) Now, that formula just sums all the parts sold in that year. What I need is for it to reset the sum as it count through each invoice and by each part. How can I do this?
Your formula is not doing what you think it is. For each row in your report (I'll assume that this is by an Invoice_ID or something along those lines) this will simply display the grand total sum of {INVOICE.QTY} for _all invoices in the report_ and will not change from row to row. To get something that is like your image, you need to create a Cross-Tab object and configure it such that its rows are based on the Product_ID, the columns are based on Invoice_Date and set to be printed "for each year", and set the "Summarized Fields" to be the sum of {INVOICE.QTY}.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, crystal reports" }
Enable write_http in collectd I am trying to build collectd from source and want to explore write_http plugin. However when configure is run, it shows: write_graphite . . . yes write_http . . . . . no write_kafka . . . . . no How to enable it? Is there some specific dependency needed?
In order to enable the write_http plugin,install the libcurl-devel dependency apt-get install -y libcurl-devel
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "collectd" }
Rectifiability implies continuity Consider a rectifiable curve $\gamma:[0,a] \rightarrow S$ on a compact and metric space S. I wonder since the path length of $\gamma$ is finite, it implies that $\gamma$ is continuous? Thanks in advance
Continuity is usually a requirement in the definition of a curve. Let $x_0$ and $x_1$ be two different points in $S$ and let $\gamma\colon[0,1]\to S$ be given by $$ \gamma(t)=\begin{cases}x_0& \text{if }0\le t\le 1/2,\\\x_1 &\text{if } 1/2<t\le1.\end{cases} $$ Then $\gamma$ is a discontinuous curve, but for any partition $0=t_0<t_1<\dots<t_n=1$ of $[0,1]$ $$ \sum_{k=1}^n d(\gamma(t_{k-1}),\gamma(t_{k}))= d(x_0,x_1). $$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "metric spaces" }
Is this process a Brownian motion? A martingale problem Let $(M_t)$ be a martingale w.r.t a filtration $(\mathcal F_t)$. The martingale representation theorem implies there exists a Brownian motion $(B_t)$ adapted to $(\mathcal F_t)$ such that $M_t$ is the solution of an SDE of the form $$dM_t=\sigma(t,M_t)d B_t $$ Suppose that we found a process $(X_t)$ adapted to $(\mathcal F_t)$ such that $$dM_t=\tilde \sigma(t,M_t)d X_t $$ Does that mean that $(X_t)$ is a Brownian motion? If so, what is the theorem behind that result?
No. If $M_t$ is a martingale which is not a Brownian motion with respect to $(\mathcal{F}_t)$, then you can just pick $dX_t = dM_t$ and $\tilde{\sigma} = 1$.
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "probability theory, stochastic processes, stochastic calculus, martingales, stochastic analysis" }
File Saveas or copy from xls to xlsx I have an excel file in the **C** disk named **C:\Book1.xls** How can I saveas **C:\Book1.xls** to **C:\Book2.xlsx** ? Is there a **System.IO.File.SaveAs** class? The following code doesnt work; IO.File.Copy(sourceFileName:="‪‪C:\Book1.xls", destFileName:="C:\Book1.xlsx", overwrite:=True) **_Edit:_** I dont want to use Excel Interop because of Microsoft Office versions.
You can use this nuget package for converting your current xls document to xlsx. Something like this will work for you : Workbook workbook = new Workbook(); workbook.LoadFromFile("Book1.xls"); workbook.SaveToFile("Book2.xlsx", ExcelVersion.Version2016); This is the main page of package that you may find more details.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -1, "tags": "vb.net" }
How can I listen to one event from two template handlers? For instance in the below, only the `foo` event handler is called. (Which is odd – I would have expected the `bar` event handler to be called, since the `<form>` element is in the `bar` template.) <template name="foo"> {{#bar klass="down"}} <button type="submit">test</button> {{/bar}} </template> <template name="bar"> <form> {{> Template.contentBlock}} </form> </template> Template.foo.events 'submit form' -> alert 'foo' Template.bar.events 'submit form' -> alert 'bar'
The answer of how to do so is the code in the question, which in fact works as desired. The `bar` handler is called, followed by the `foo` handler. <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "meteor, spacebars" }
Using iron-router to go to a certain id section of the page (url#portion) in Meteor.js I have routes set up with iron-router that make sure the page goes to the top of the page: Router.route('/services', { name: 'services', template: 'services', onAfterAction: function () { scrollTop(); } }); function scrollTop() { window.scroll(0, 0); } However, if I am on another route, and I have a link like /services#thisid it will still take me to the top of the page (not to the portion of the page with the id=thisid). Is there a way to get around this?
This should address your issue both for this issue and your layout override question. Router.configure({ layoutTemplate: 'main', onAfterAction: function(){ console.log('hash', this.params.hash); if(!this.params.hash){ scrollTop(); } } }); Router.route('/services', { name: 'services', template: 'services', }); Router.route('/inquiry', { name: 'inquiry', template: 'inquiry', layoutTemplate: 'alternate' }); The check for `this.params.hash` ensures that there is no value for the hash before executing the scrollTop. The `layoutTemplate` on the inquiry route overrides the layout while still respecting the global onAfterAction.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, meteor, iron router" }
Boost 1.60.0.tar.bz2 not extracting correctly Forgive me for any silly mistakes but I'm very inexperienced. I have a file boost_1_60_0.tar.bz2 and am trying to extract it to /usr/local using the command tar --bzip2 -xf ~/Downloads/boost_1_60_0.tar.bz2 When I try to do this it gives me over a thousand errors each with the same basic format like this example: boost_1_60_0/doc/html/boost_asio/reference/serial_port_base/: Failed to create dir 'boost_1_60_0'Can't create 'boost_1_60_0/doc/html/boost_asio/reference/serial_port_base' When I do this I have cd'd into usr/local. Thank you for your help.
You don't have permission to write into /usr/local as an ordinary user. Instead you should extract to a build directory, for example under your home directory, and then follow the boost build and installation instructions in the "getting started" page. That will put the files into /usr/local with a reasonable structure.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "boost, terminal" }
Generating specific cpu, disk and network utilization workloads on Linux I am looking for a Linux tool to generate workloads with pre-defined cpu, disk and network utilization. For example, I need to keep my cpu utilization on 55% and the disk utilization on 30% for a minute on my Ubuntu workstation. Is there any tool to generate such workloads for cpu, disk and net? p.s. It is preferable to have one tool to do all the above mentioned features. But, if there are different tools for cpu, disk and net, I will be happy if you could share the links.
As there is no `take 30% of system resources` function, i don't think there is a corresponding tool. The Linux kernel gives out as much resources as needed and free, depending on the scheduling mechanism and more. A tool like you are looking for would have to: * Generate Load (no problem) * Check the system load (no problem) * Regulate the _power_ of the load generating functions (BIG problem) The different amount of load could be accomplished with dynamic sleeps, and more, but the difficulty is very high, the efficiency very low. For disk IO you could test _IOZone_ for example, and play a little bit with the parameters.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "linux, ubuntu, utilization, workload" }
Get values from the key-value pairs in a comma separated string I have string value like below: var result = "{DimensionTransactionMonth=August, DimensionTransactionYear=2012}" I need to transform like below: var finalResult = "August,2012"; Does anyone know how to do it?
Thus you are dealing with kev-value pairs, I would convert your input to `Dictionary<string,string>`: var result = "{DimensionTransactionMonth=August, DimensionTransactionYear=2012}"; var settings = result.Trim('{', '}') .Split(',') .Select(s => s.Trim().Split('=')) .ToDictionary(a => a[0], a => a[1]); Now you can easily get final result: var finalResult = String.Join(",", settings.Values); // "August,2012" Or some specific value by its key: var month = settings["DimensionTransactionMonth"]; // "August"
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "c#" }
What is the best way to return a list<t> via a method? Suppose I have a method that returns a list of String names. public List<String> buildNamesList(){ List<String> namesList = new List<String>(); //add several names to the list return namesList; } Now if I have a method that needs that namesList would returning it like so be the best way? public void someMethod(){ List<String> namesList = new List<String>(); namesList = buildNamesList(); //traverse namesList }
If you are creating a new list in your buildNamesList method, I would just say: var namesList = buildNamesList();
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "c#, .net, c# 4.0, collections" }
Python: What is the best approach to find and replace attribute values for an XML tag type? For some attributes, I wish to validate the values and replace some of them with more succinct ones. <data source="file:\\c:\main\data.txt"/> Replaced by: <data source="c:\main\data.txt"/>
I think you can use `BeautifulSoup`, you can use it to parse and modify a xml file: >>> s=r'''<data source="file:\\c:\main\data.txt"/>''' >>> soup = BeautifulSoup(s) >>> t = soup.find("data") >>> t['source'] 'file:\\\\c:\\main\\data.txt' >>> t['source'][7:] 'c:\\main\\data.txt' >>> t['source'] = t['source'][7:] >>> print str(soup) <html><body><data source="c:\main\data.txt"></data></body></html>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, xml, regex" }
Deep copy of an NSMutableArray of custom objects with NSMutableArray members I'm trying to make a deep copy of an `NSMutableArray` whose objects are instances of a custom class similar to this: @interface CustomParent : NSObject @property NSInteger Id; @property (strong, nonatomic) NSString *IdStr; @property (weak, nonatomic) NSDate *Date; @property (strong, nonatomic) NSMutableArray *CustomChildren; @property (strong, nonatomic) CustomType *Type; @property float Value; @end I know there are lots of posts dealing with copying objects, but I don´t find examples for getting a complete copy of objects with collection members or properties. `NSMutableArray *dstArray = [[NSMutableArray alloc] initWithArray:srcArray copyItems:YES];` raises an exception involving the `copyWithZone` method. How can I do this? Thanks!
In order to deep copy the content of the array [[NSMutableArray alloc] initWithArray:srcArray copyItems:YES]; will send `copyWithZone:` to every object inside the collection. If they don't respond to this selector, you'll get a crash. Have your `CustomParent` class to conform to the `NSCopying` protocol and you're done. Here's some extra info on how do achieve it: Implementing NSCopying
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 2, "tags": "ios, objective c, nsmutablearray, deep copy" }
how to change a webbrowser's listbox defined in a user control from another form I've been trying to add items to a `listbox` defined in a HTML file,shown in a webbrowser. I created this listbox in a user control I tried this code but I came up empty: **My Code:** public string _listBoxProperty { set { webBrowser1.Document.GetElementById("Select1").OuterHtml = value; } get { return webBrowser1.Document.GetElementById("Select1").OuterHtml; } } Thank you profusely :)
Try This: you can only modify on webBrowser1_DocumentCompleted else it will give you an error this is property of webbrowser control you are using private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { HtmlElement opt = webBrowser1.Document.CreateElement("option"); HtmlElement ddlPopulate = webBrowser1.Document.GetElementById("Select1"); opt.InnerText = "TestValue"; ddlPopulate.AppendChild(opt); } Hope This Help.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, webbrowser control" }
How to compare Option[String] with nullable column in Slick? I have a column that is nullable inside my database and I am performing this kind of comparison: TableQuery[Tables.TableName].filter( x => x.nullableStringColumn === optionString ).exists.run However I am not getting the expected results, empty column should match None and filled column should match the string if equal
You should try TableQuery[Tables.TableName].filter( x => (x.nullableStringColumn.isNull && optionString.isEmpty) || (x.nullableStringColumn === optionString) ).exists.run
stackexchange-stackoverflow
{ "answer_score": -2, "question_score": 0, "tags": "scala, slick 2.0" }
How to plot a 3D surface with a simple black and white style? _Mathematica_ has great plotting capabilities. However, sometimes what is needed is a very basic black and white plot without textures, lighting, glow and other complex features. So, here is my question: what kind of `Plot3D` options will allow me to get something similar to ![](
I would say you go for the `Lighting` option: Plot3D[Exp[-(x^2 + y^2)], {x, -2, 2}, {y, -2, 2}, Lighting -> {{"Ambient", White}}, PlotRange -> All, Mesh -> {20}] !Mathematica graphics
stackexchange-mathematica
{ "answer_score": 25, "question_score": 24, "tags": "plotting, graphics3d" }
Why is my Google request denied? I am trying to integrate Salesforce with Google textsearch in order to acquire a JSON response with desired information. My request is getting denied and I can't figure out why. Any help is much appreciated. httprequest req = new httprequest(); http http = new http(); req.setmethod('GET'); string url = ' + '?query=' + name + '+' + city + '+' + state + '+' + zipcode + '&Key={MY-API-KEY}'; req.setEndpoint(url); HttpResponse resp = http.send(req); system.debug(resp.getbody()); string jsonResults = resp.getbody(); The response from this request is: 07:44:31.155 (155112095)|USER_DEBUG|[105]|DEBUG|{ "error_message" : "An internal error was found for this API project.", "html_attributions" : [], "results" : [], "status" : "REQUEST_DENIED" }
It turned out the problem was in this line of code: * '&Key={MY-API-KEY}'; Instead of using 'Key' I used 'key' and it worked.
stackexchange-salesforce
{ "answer_score": 2, "question_score": 0, "tags": "rest api, webservices, integration, json, httprequest" }
How does one make a hadoop mapper read entire sentences I am trying to feed my mapper in a mapreduce project one sentence at a time for some text analysis. this text could look something like: > Nicholas looked at her face with surprise. It was the same face he had projected against the epiphysial cartilage. This arrangement favours during the whole time of the reading, gazed at his delicate fingers the frontier. convincing unacceptable confrontation swiftly paid joke instant hospitals. The one and the other may serve as a pastime. But what's chief officials. however hadoops fileinputformat reads the following: ![input]( How do I program hadoop's inputformat to read entire sentences delmited by a "." ? i tries using a key value inputformat but hadoop always seems to cut a sentence and a breakline.
You can create a custom input format to read the sentence delimited by ".". For this you need to create a RecordReader and a class lets say MyValue which implements writableComparable interface. This class you can use to pass as value type in your mapper. I will try to implement this at my end, will updated this post in coming days. Read about custom input dormat you might get solution on your own.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "hadoop, mapreduce" }
How many bytes does ffprobe need? I would like to use `ffprobe` to look at the information of media files. However, the files are not on my local disk, and I have to read from a remote storage. I can read the first `n` bytes, write them to a temporary file and use `ffprobe` to read the information. I would like to know the least such `n`. I tested with a few files, and 512KB worked with all the files that I tested. However, I am not sure if that will work for all media files.
ffprobe (and ffmpeg) aims to parse two things when opening an input: 1. the input container's header 2. payload data from each stream, enough to ascertain salient stream parameters like codec attributes and frame rate. The header size is generally proportional to the number of packets in the file i.e. a 3 hour MP4 file will have a larger header than a 3 min MP4. (if the header is at the end of the file, then access to the first 512 kB won't help) From each stream, ffmpeg will decode packets till its stream attributes have been populated. The amount of bytes consumed will depend on stream bitrate, and how many streams are present. So, the strict response to ' _I am not sure if that will work for all media files_ ' is it won't.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ffprobe" }
Examining how an assembly instruction is stored I'm looking to update the assembly instruction at a particular address. In order to do so, I disassembled a C function in order to see how assembly instructions are stored, specifically looking at the instruction below: 0x088... jmp 0x88465002 (gdb) x /2b 0x088 0x088... <main+20> 0xeb 0x15 I discovered that instructions are encoded in bytes, e.g. `JMP` is encoded as `0xEB`. However, why is the location of the `JMP` stored as `0x15`? Is this because we are jumping `0x15` bytes down the stack (i.e. `0x15` is the offset)? Thanks--
`0xEB` is the opcode for short relative jump on x86. Short means signed displacement on 8 bits. And yes `0x15` is the displacement, relative to the current instruction counter value (so address of immediate next instruction of this one), 0x15 = 21 bytes next.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -2, "tags": "assembly, gdb" }
Keyboard shortcut to bring up System Monitor I am running Ubuntu 16.04 LTS. I would like to make a keyboard shortcut to bring up the System Monitor - I should be most grateful if someone could let me know how to do this. I am aware of the Custom Settings in the Keyboard (under System Settings) but can't get this to open the System Monitor app.
### The command you need If you already found out how to set a custom shortcut: the command you need to set is: gnome-system-monitor ### How to find out the command To find a command like that is often easy: * Open the application * Open a terminal, type `xprop`, click on the application's window. In the terminal output that appears, look for a line like: WM_CLASS(STRING) = "gnome-system-monitor", "Gnome-system-monitor" ...and there we are, often the lower case version is the command to run the application. There are a few other ways though. One is to look into the corresponding `.desktop` file in `/usr/share/applications` and see what (the first) `Exec=` -line sais.
stackexchange-askubuntu
{ "answer_score": 6, "question_score": 4, "tags": "keyboard, shortcuts" }
SDL Tridion Developer Certification I am looking for SDL Tridion Developer Certification, but I don't know how to prepare for it. What are the topics which get tested on the Tridion Developer Certification exam? If anyone has any material, e.g. links which can get shared in the community, please share. This post may help other developers looking for to become Tridion Developer certified. Thanks in Advance
SDL offer a full education program, details of which can be found here: < You can also spend time reading blog posts, stack overflow etc.. but you will not find any publically available exam material In my opinion, the best preparation for Tridion certification is using the platform preferably alongside an experience user/developer.
stackexchange-tridion
{ "answer_score": 9, "question_score": 8, "tags": "sdl tridion" }
Truncate/Convert Datacolumn Dates. C# Console App I have ODBC DSN connection that I bring into DataTable. Column Three is populated with TIMESTAMP data. I have... BRANCH----| TYPE-----| ID 1---------------| R-----------| 14/03/2013 9:42 1---------------| R-----------| 9/01/2015 9:42 3---------------| W-----------| 13/09/2014 9:42 2---------------| R-----------| 1/03/2012 9:42 I want to see: 1---------------| R-----------| 03/2013 1---------------| R-----------| 01/2015 3---------------| W-----------| 09/2014 2---------------| R-----------| 03/2012 I have used the code below before to truncate data. However I cant make it work in this case due to type mismatch. Any pointers would be great. dcUnits.Expression = string.Format ("SUBSTRING({0}, 1, 1)+''+{1}+''+{2}", "BRANCH", "TYPE", "ID");
You can apply YearMonth standard format specifier.aspx#YearMonth) to the column. The "Y" or "y" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.YearMonthPattern property of a specified culture. For example, the custom format string for the invariant culture is "yyyy MMMM". This is just an idea which might work for you. DateTimeFormatInfo myDTFI = new CultureInfo( "en-US", false ).DateTimeFormat; DateTime myDT = new DateTime(ID); dcUnits.Expression = string.Format ("SUBSTRING({0}, 1, 1)+''+{1}+''+{2}", "BRANCH", "TYPE", myDT.ToString("y", myDTFI));
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#" }
Calling a Stored Procedure with PHP PDO Error I'm using PHP PDO with the ODBC driver to connect to an MSSQL database. I have a stored procedure called "uspGetLoginUserInformation". I'm trying to call it like so: $username = '[email protected]'; $password = 'test'; $stmt = $odbc->prepare("CALL dbo.uspGetLoginUserInformation(:username, :password)"); $stmt->bindParam(':username', $username); $stmt->bindParam(':password', $password); $stmt->execute(); I keep getting this error: **Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 102 [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near '.'. (SQLExecute[102] at ext\pdo_odbc\odbc_stmt.c:254)' in C:\wamp\www\plugin.php on line 96** Any ideas? I get that it's a syntax error, but even if I remove the "dbo." I still get a syntax error **Incorrect syntax near '@P1'**. Thanks!
Was using the wrong syntax. Prepare line should look something like this: $stmt = $odbc->prepare("Exec uspGetLoginUserInformation @Username=:username, @Password=:password");
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, sql server, pdo, odbc" }
Which approach is better to load a JDBC driver? There are two ways to load a driver: 1. `Class.forName()` 2. `DriverManager.registerDriver()` Method 1 internally also calls DriverManager.registerDriver and method 1 is the preferred way. But why? Is there any small difference or is performance etc. better? Any views are appreciated..
If you use Class.forName(), then you are not required to have any compile-time dependencies on a particular JDBC driver. This is particularly useful when you are writing code that can work with a variety of databases. Consider the following code: // Register the PostgreSQL driver Class.forName("org.postgresql.Driver"); Now compare it to: import org.postgresql.Driver; // Register the PostgreSQL driver DriverManager.registerDriver(new Driver()); And consider that in the first example, the class name could also have come from a properties file, XML file, etc., depending on what's convenient for your application.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 7, "tags": "java, jdbc" }
Unknown table in multidelete without joins I am trying to delete a value from a field in workbench. Getting an error > Unknown table nhs in multi delete I am trying to "NULL" a single filed in a single table. DELETE nhs FROM persons WHERE oid = 123 I was expecting this to delete the record. Whats wrong? I am only trying to delete a value from a single field in one table.
> I am trying to "NULL" a single filed in a single table I hope you are looking for UPDATE persons SET nhs = NULL WHERE oid = 123 `DELETE FROM persons WHERE oid = 123`, will remove the entire row, it can't delete a single column. To change a single column's value you need to use `UPDATE` statement.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "mysql, sql delete" }
Accepted answer ,up vote and bounty award Recently I posted a question on Pro WebMasters. After a couple of days no one had answered my question so I decided to start a bounty. After a while someone actually gave me a solution, so I accepted his answer. I waited until I could award him with the bounty and since I was capable of up vote him, I did that also. Isn't accepting an answer implies that you like his answer and you also want to reward him?
I don't think that it is against the rules to accept and upvote a good answer on top of the bounty. As far as I can tell, the 50 rep is from you, the 25 (acceptance + upvote) is given by SE on your behalf in recognition of a good and helpful answer. I have done this also, I felt the answer was very helpful and happily upvoted, accepted the answer and gave the bounty. Having said all that, if I am mistaken, can someone please correct me.
stackexchange-meta
{ "answer_score": 6, "question_score": -11, "tags": "discussion, reputation, bounties, accepted answer, up votes" }
[OneSignal][Unity] Create ID after login I am running into a small issue in my unity app after adding the OneSignal plugin. I can receive push notifications if I send them from the web server and everything is fast. However, my concern is that OneSignal assigns one ID to the device not to the user. My question is: there is any way to create an ID after my login? The only problem in the actual state is if the user has multiple accounts or if a friend connects from that device. Both users would have the same ID and therefore both would receive the same notifications. Thanks.
I would recommend using OneSignal.SendTag in your app to tag the user with your userId when they login. Then when they logout call OneSiganl.DeleteTag to remove it. This will allow you to send a notification with the `tags` field on the OneSignal create notification REST API POST call.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "push notification, onesignal, unity3d" }
Can there be a single technologically advanced nation, in a continent full of non-technologically advanced nations? The run down here is that there's this continent, and there is a lot of unclaimed land where countries haven't formed yet and a lot of tribes but there are some actual countries like kingdoms, (where kingdoms are at war). Yes there's magic. (That's the main reason for the kingdom's war). But I was planning to add this cyberpunk country, like it doesn't belong with these pre-industrial countries. Should I remove it? (I can always add it elsewhere). Also if the answer is yes, would it make more sense if the said advanced nation was an island?
While the Roman Empire had the technological knowledge to build aqueducts, roads and buildings like the Pantheon, in the same continent there were populations which were not far herding sheep in countryside. And this with no magic. Also while the Egyptian were building the Pyramids the rest of the African population were at most tribal nations, hunting or pasturing. So, yes, it is possible for one nation to be technologically more advanced than the others living on the same continent. Especially if trade routes (and the exchange of knowledge moving along them) are somehow not really efficient.
stackexchange-worldbuilding
{ "answer_score": 47, "question_score": 25, "tags": "society, technology, economy, government" }
Matching an empty string with regex I've seen posts here on stackoverflow that say that the regex `^$` will match an empty string... So it made me think... why not something like this: `^\s+$` \- does that not also work? I know it's more typing, but it in my mind, it also makes more sense. I've not used a whole lot of regex before, but it seems like my need for them is becoming greater as the days go by - so I'm taking the hint and attempting to learn.
> `^\s+$` \- does that not also work? Not for matching an empty string. In general, `X+` means `X` _one or more times_. So, `\s+` cannot match the empty string - it requires at least one `\s` in order to match. ^ \s + $ | | | | start of string ---------------------+ | | | whitespace character ------------------+ | | one or more of what precedes -------------+ | end of string ------------------------------+ Now, `X*` means `X` _0 or more times_ , so `^\s*$` would indeed match an empty string. * * * ## `^\s+$` !enter image description here ## `^\s*$` !enter image description here
stackexchange-stackoverflow
{ "answer_score": 20, "question_score": 9, "tags": "regex" }
Cron job to run every 1st day of the month I need to create a cron job that will run on the every 1st day of the month every minute of this day. I will create it from cpanel. Any help is appreciated. Thanks
The crontab entry should look like this : * * 1 * * cmd_to_run The columns mean every minute every hour 1st day of month every month any day of week, and then the command. I'm not sure about cpanel admin
stackexchange-stackoverflow
{ "answer_score": 23, "question_score": 10, "tags": "cron" }
Appengine - Upgrading from DB to NDB - Order dear all I'm upgrading one of my datastore entities from db to ndb. The order() call is a problem for me. As frontend will transfer a string such as "-created_at" or "title" for ordering. In the past, I basically put this value to query as shown below: query.order("-created_at") Now ndb doesn't support above syntax. Is there a recommended approach for translating order("-created_at") to order(-MyModel.created_at) ? Thanks a lot!
Use dictionary lookup sort_orders = { "-created_at": -MyModel.created_at, "some_other_order": SomeModel.some_property } def get_order(input): return sort_orders.get(input) That way you only accept valid/predefined set of possible orders. The `-` unary operator does work in the dictionary. e.g. s~lightning-catfish> -Series.updatedDate PropertyOrder(<updatedDate>, DESCENDING) I would personally make the function/method a class_method of the model, and the dictionary of valid orders defined at the class level as well. That way all the definitions are in the same place.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, google app engine, app engine ndb" }
How can I delete xsn form from Manage Form Templates programmatically? For some reason xsm form doesn't remove from Manage Form Templates on Feature deactivation process, so looks like I should handle it myself. Can someone tell how to do this programmatically?
So I've found solution like this. FormsService formsService = SPFarm.Local.Servers.GetValue<FormsService>(FormsService.ServiceName); foreach (var ft in formsService.FormTemplates) { if (ft.Name == "Your XSN Form Name Here") { ft.Deactivate(); ft.Delete(); } }
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 0, "tags": "infopath, form" }
List<char>.toString no convierte correctamente Tengo una lista de `char`, la cual quiero guardar en un _string_ con el método `ToString`. El problema es que me guarda cualquier cosa: ![Captura mientras está compilando]( Para mayor información, el método, lo que hace es recibir el _string_ cambiado de un `TextBox`, evalúa si existe algún caracter no entero dentro del _string_ , y si existe lo quita (encontrando el caracter, creando una lista con los caracteres del _string_ recibido, removiendo de la lista el caracter que coincida con el encontrado, que es no entero, luego devolviendo la lista a _string_ y mostrándola en el `TextBox`). ¿Por qué guarda mal el _string_?
El método `ToString` es un método heredado de la clase `Object` que devuelve una cadena que representa el objeto. Por defecto este método devuelve el nombre completo del tipo de objeto. Algunos tipos sobrescriben este método para que tenga un comportamiento diferente, pero no es el caso de las listas genéricas. Por eso al llamar al método `ToString` el resultado es el nombre del tipo de objeto. Si quieres convertir a `string` una lista de caracteres puedes utilizar el método `Concat`: string recortado = string.Concat(recortar);
stackexchange-es_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, linq, validación, lista" }
Connected but not adjacent vertex Are there specific terms or adjectives in graph theory to name these two situations? * Two vertices are non-adjacent (disjoint? I have seen that the term "disjoint" is rather used for paths with non-common vertices or edges). * Two connected non-adjacent vertices (the shortest path or paths connecting them have a lenght $> 1$).
You've exactly described the first situation, i.e. we indeed say that $u$ and $v$ are non-adjacent. For the second we do the same, but we want to also specify they are in the same component of $G$ which contains them if $G$ is not connected. These are already simple and well-understood descriptions and there's nothing "more standard". However, you are also free to use your own definitions in your actual use case if it's worth it.
stackexchange-cs
{ "answer_score": 2, "question_score": 2, "tags": "graphs" }
Запись значения по адресу pymem Мне нужно записать значение типа double по адресу "0EEAD0E0" программы, но я никак не могу найти как это сделать с помощью модуля pymem для python. Подскажите, пожалуйста, как это сделать.
import pymem addr = 0x0EEAD0E0 value = 1.0 pm = pymem.Pymem("program.exe") pm.write_double(pm.process_base + addr, value)
stackexchange-ru_stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "python" }
Existence of limit of product of functions with divergent and convergent limits Let $x>0$. Assume $f(x)>0$, $f$ is strictly decreasing, and $\lim_{x\downarrow 0} f(x)=+\infty$. If $xf(x)<K<\infty$ for all $x>0$ (where $K$ does not depend on $x$), does the limit $\lim_{x\downarrow 0} xf(x)$ exist? If it does not exists in general, under what conditions does it exist?
A counterexample is given by $$f(x) = \frac{3+\sin \log x}{x}$$ Note that $$f'(x) = \frac{\cos\log x -\sin\log x - 3 }{x^2}<0$$ so $f$ is monotone. Also, $$f''(x) = \frac{6-3\cos\log x + \sin\log x }{x^3}>0$$ so $f$ is convex. I don't expect there to be a sufficient condition that is easier to verify than the existence of the limit itself.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "calculus, limits" }
perl - regular expression - match case Hi I have some file that looks like this: some row /folder1/folder2/folder3/folder4/folder5 *.kuku.* noku /folder1/folder2/folder3/folder4/folder5 *.kuku noku another row another row if first line is absent I need to add it, if second line is absent I need to add only second line I wrote regular expressions , but they are not really works: if ($line =~ /(\*\.kuku\.\*\b)/) {do something} if ($line =~ /(\*\.kuku\b)/) {do something else} Any idea? Thanks
`\b` only matches on word boundaries. `\*\.kuku\.\*\b` will never match because `*` is not a word character. You could change it to `\s` so you match a whitespace. `\*\.kuku\.\*\s`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "regex, perl" }
Why does Greek have 'aorgesia' and 'aorist' rather than 'anorgesia' and 'anorist'? The Ancient Greek words ἀοργησία _aorgesia_ "a defect in the passion of anger" and ἀόριστος _aoristos_ "without boundaries" both start with the "alpha privatum," the negative prefix cognate to English _un-_ and Latin _-in/-im/-ir/-il_. However, every source that I have looked up has said that this prefix is realized as ἀν- _an_ \- when it comes before a vowel (including one that was historically preceded by a rough breathing /h/). What is the explanation for these exceptions, and do any others exist? EDIT: I kind of found the answer, so I guess I will post it in case anyone else has this problem later on. I may have follow-up questions.
Both of these roots originally had an initial w-. horos “boundary” is from older worwos, as attested by Mycenaean wo-wo, and dialect forms like ορϝος. In the case of orgē “anger” we do not happen to have any attested Greek dialect forms with w-, but IE *uerg- is supported by zero-grade forms like Sanskrit ūrj- “strength”.
stackexchange-linguistics
{ "answer_score": 9, "question_score": 5, "tags": "etymology, greek" }
Does $\text{dim}W = 0$ imply $W = \{\textbf{0}\}$? If we have $W$ and $X$ as subspaces of $\mathbb{R}^8$, with dim$W$ = 3, dim$X$ = 5 and $W + X = \mathbb{R}^8$, then this implies that dim($W \cap X) = 0$. Does this then imply that $W \cap X = \\{\textbf{0}\\}$, where $\textbf{0} \in V$? Why / why not?
Yes. One of (probably many) ways to say this is that if $W \cap X$ contained a non-zero vector $v,$ then the set $\\{v\\}$ would be linearly independent, and so the dimension of $W \cap X$ would be at least $1.$
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "linear algebra, vector spaces" }
Why does $\mathbb{Z}$ denote the set of integers? The set of Natural Numbers is denoted by $\mathbb N$ (For Natural) The set of Rationals are denoted by $\mathbb Q$ (for quotient) The set of Complex numbers are denoted by $\mathbb C$ (for complex) The set of Real numbers are denoted by $\mathbb R$ (for Real) Why is the set of integers denoted by $\mathbb Z$?
I typed " _Integers_ " into Google. The first hit was Wikipedia. In the second paragraph it says " _The set of all integers is often denoted by a boldface Z... which stands for Zahlen (German for numbers)._ "
stackexchange-math
{ "answer_score": 20, "question_score": 1, "tags": "elementary set theory, notation" }
Javascript within Joomla Module I am new to Joomla and have been able to do all I wanted until the point I needed to add some Javascript to a module. The code below only produces "Test1" and "Test2", but no alert pops up. What am I missing? <div> TEST1 <script type="text/javascript"> alert 'alert'; </script> TEST2 </div>
<div> TEST1 <script type="text/javascript"> alert("alert"); </script> TEST2 </div>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "joomla" }
How to override .toString method for ordered-set I'm using ordered-set for some stuff in Clojure 1.3.0. My `project.clj` includes `[ordered "1.1.0"]`. When I call `(str (ordered-set 1 2 3))` I get `"ordered.set.OrderedSet@6"` but when I call a normal clojure hash-set `(str (hash-set 1 2 3))` I get the correct `"#{1 2 3}"` as a result. The `str` method calls `.toString` somewhere, so how do I override the `.toString` method for `ordered-set` so I can get a proper string out of it? thanks
Well, there are two answers to this question. One is, the lazy maintainer of `ordered` (me) should get his act together and implement `toString`. The other is, you probably shouldn't be using `str` on anything where you care about readability - `pr-str` is a much more reliable data-presentation function. For example, `(str {:a 'a})` and `(str {:a "a"})` both result in `"{:a a}"`. With `pr-str` the type information remains.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "string, clojure, println" }
Issue opening and running Python in PowerShell I am new to python programming (already know C) and am following Zed Shaw's book Learn Python the Hard Way. For that, I need to use Python on PowerShell. When I type `python` in CMD, Python opens up alright and I can use all the commands normally. When I type `python` in PowerShell, a pop-up window appears, asking me how I want to open the file. ![Attached an image here]( Why does this happen? It also happens in VSCode where there are two options to run a Python program. One is labeled as just Run and the other as Run Python file in Terminal. When I click on Run, the same pop-up window appears.
You have a file named python located at C:\Users\Admin, and it isn't an executable file(.exe), the file isn't what you are looking for and it can be opened by the programs shown in the dialog, I infer from the programs the extension is either .xml or .pdf, though it is more likely to be .xml. You can run python in cmd without typing its full path but can't do so in PowerShell is because PowerShell doesn't find the path of the .exe, you likely installed Python to C:\Program Files\Python39, and the folder is added to system path variable and NOT user path, then you must have run cmd as admin so it has access to system path and finds python.exe. However from the folder path the shell is currently at, you likely haven't started PowerShell as admin, so it doesn't have access to system path and can not find python.exe. The solution: run powershell as admin. Also, don't use the default PowerShell, you are missing a lot if you don't use PowerShell 7.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "windows, powershell, python3" }
iis 7.5 url rewrite -not processing percent '%' symbol I imported rules from IIRF into IIS URL Rewrite, and most seemed to work fine. I just noticed tho that some urls have percent symbols in them (trying to redirect some bad inbound links, with percent encoded characters in them). The regex seems to not work when the percent is in there, so I assume it is trying to interpret is as a command or something. Can't find any documentation on this, anyone know?
appears that the rewrite rules already undo the url encoding, so it no longer sees a %3E as that, but instead as a '<'.. so using a > in place of %3E does the trick. Now, to go fix a bunch of urls. argh. Edit: Also, if you hand edit the web.config (versus using the UI editor), you will need to use & lt ; for the < symbols. It's probably best to use the UI to avoid confusion.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "iis, iis 7, url rewriting" }
Output array to Plugin::log Just wondering if its possible to output an array to the Plugin::log call? Would be really handy to see if an error occurs, what a data object's values are! Tried the following: Plugin::log(array('test')), LogLevel::Error); Plugin::log(json_decode(array('test')), LogLevel::Error); Plugin::log(var_dump(array('test')), LogLevel::Error); Plugin::log(print_r(array('test')), LogLevel::Error); Plugin::log(\CVarDumper::dump(array('test')), LogLevel::Error);
Passing `true` as the second parameter to print_r returns a string that can be written to the log. Plugin::log(print_r(array('test'), true));
stackexchange-craftcms
{ "answer_score": 6, "question_score": 5, "tags": "plugin development, logs" }
Unzip a file and then display it in the console in one step I have access to a remote server over ssh. I have only read (no write) access on the server. There is a zipped log file that I want to read. But because I have only read access, I cannot first extract the file and then read it, because when I try to unzip, I get the message `Read-only file system`. My idea was to redirect the output of the `gunzip`-command to some other command that can read from the standrat input and display the content in the console. So I do not write the unzipped file on the file system (that I do not have the right) but display it directly in the console. Until now I couldn't successfully do it. How to achieve this goal? And is there any better way to do it?
Since you do not have permission to unzip the file, you will first need to view the list of contents and their path. Once you get that then you can view content using `-p` option of **unzip** command. * View contents `zipinfo your.zip` * View file contents `unzip -p latest.zip wordpress/wp-config-sample.php` * In case it is a `.gz` file then use: `gunzip -c wordpress/wp-config-sample.php` Hope this helps!
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "shell, command line, unzip" }
Error while using google play services lib to implement ads in my app Helo guys. I'm trying to implement some ads in my app and both of them needs google play services lib. The point is, when I import that lib to my project it just freeze my Eclipse and start to show many dialogue windows about an error. I'm using Eclipse Standard/SDK Version: **Luna Release (4.4.0) Build id: 20140612-0600** with the android sdk updated on **Ubuntu 14.04.** I already tried to change the memory values at `eclipse.ini` to 512M ans 1024M but it didn't solve the issue. I've found many people discussing about this error and none of that answers gave me a solution. Follows the error message shown after the lib import: [2014-07-22 00:23:37 - Dex Loader] Unable to execute dex: GC overhead limit exceeded [2014-07-22 00:23:37 - AppName] Conversion to Dalvik format failed: Unable to execute dex: GC overhead limit exceeded
As Play Services Has Tons of Classes and DEX does not support unlimited Classes, it Might be related to that. Here is a blog post how to implement custom class Loading, maybe that will point you into the right direction. < Maybe you should consider trying to compile it via console or an alternative IDE like Android Studio (wich is imo way better than eclipse).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, eclipse, google play services, ubuntu 14.04" }
Gulp minify-css only for distribution How can I minify CSS generated from LESS only to 'dist' folder? Of course all gulp plugins are corretly installed. Everything goes OK except minifying CSS. Here is my code: gulp.task('styles', function () { return gulp.src('app/less/*.less') .pipe($.less()) .pipe(gulp.dest('.tmp/styles')); .pipe(minifyCSS({keepBreaks:false})) .pipe(gulp.dest('dist/styles')); }); If I move `.pipe(minifyCSS({keepBreaks:false}))` one line above it works. But I need to have compressed CSS only in dist forlder. Thanks for advice.
It might not be the best way, but I use two different gulp tasks. One task that compiles the CSS into my build directory and then another task takes that output and minifies it into my dist directory. Use a task dependency to ensure that the file gets built before the minify task runs. gulp.task('styles', function() { return gulp.src(styles) .pipe(concat('app.less')) .pipe(gulp.dest('./build/styles')) .pipe(less()) .on('error', console.log) .pipe(concat('app.css')) .pipe(gulp.dest('./build/styles')); }); gulp.task('styles-dist', ['styles'], function() { return gulp.src('build/styles/app.css') .pipe(minifycss()) .pipe(gulp.dest('./dist/styles')); });
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "css, gulp, minify, gulp less" }
I am troubling integrating react-Dropzone-Uploader The image data which is requested by the API is multipart form data but i am just providing the image data to it.i want to convert the image data to FormData.
Use **`FormData`** You'll need to use the **`append`** method on it to add the image. Here's some sample code: const formData = new FormData(); formData.append('nameOfTheKeyYouWantToSetThisDataTo', myFileInput.files[0], 'avatar.jpg'); You can then send the data to your API using the **`fetch`** API. fetch(url, { method: 'POST', body: formData }).then(function (response) { ... });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, reactjs, react dropzone" }
TCPDF SetFont and writeHTML I'm having a problem with TCPDF. My custom font (and any other included font) isn't working when using writeHTML. $tcpdf = tcpdf_get_instance(); $fontname = $tcpdf->addTTFfont('/antiquariat/sites/default/files/fonts/tstar-regular-webfont.ttf', 'TrueTypeUnicode', '', 32); $tcpdf->SetFont('tstarwebfont', '', 16); $tcpdf->writeHTML($html); Fonts won't change, even if I use "helvetica" or any other font. Second thing is, that the custom font isn't generated at all, but in first place I struggle with that not even any other font is used.
As no one answered to me and I didn't get it up like desired, I switched to DOMPDF which is working fine so far! This is not quite the solution I was looking for, but a working one!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 5, "tags": "tcpdf" }
C# Using VLC Wrapper to stream from IP Camera I am trying to construct a user interface to capture video from an IP Camera (Specifically an Onvif Device). I have constructed appropriate clients and binding elements. I am able to get the URI setup. I cannot however figure out how to use the VLC Wrapper to stream the video. I've imported the references/libraries using Nuget. I am able to add the VLC Active X plugin object to the windows forms. Past this I am struggling to figure out how to set up. I know i need to set up a call to the player and past it my constructed Uri (with the port, host, and scheme), and username and password. I'm not sure which steps to take next.
The ActiveX control is deprecated. You should be using a .NET binding like LibVLCSharp. The README will guide you through the steps of creating your first app. Basic steps are: * Install LibVLC through nuget * Install LibVLCSharp through NuGet * Call Core.Initialize() * Create your VideoView and your MediaPlayer
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, libvlc, ip camera, libvlcsharp" }
Submodule structure when changing field Let $G$ be finite group. Let $k$ be a finite field and $K$ an algebraically closed field containing $k$. An irreducible $k[G]$-module $V$ is said to be absolutely irreducible if $V \otimes_k K$ is an irreducible $K[G]$-module. Suppose that $V$ is a $k[G]$-module such that every composition factor of $V$ is absolutely irreducible. Do $V$ and $V \otimes_k K$ have the same submodule structure? That is, is it true that every $K[G]$-submodule of $V \otimes_k K$ is of the form $W \otimes_k K$, where $W$ is a $k[G]$-submodule of $V$?
Suppose that V is trivial of dimension 2. Then V has a finite number of submodules but the extended module has infinitely many submodules.
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "abstract algebra, group theory, finite groups, modules, representation theory" }
smbj: How can I get subdirectories only? I use < for samba access. I want get only the subfolders of my target directory. Whith following code I get "..", "." and all the files - is there an elegant way to get subdirectories only? SmbConfig config = SmbConfig.builder().withMultiProtocolNegotiate(true).build(); smbClient = new SMBClient(config); Connection connection = smbClient.connect(smbServerName); AuthenticationContext ac = new AuthenticationContext(smbUser, smbPassword.toCharArray(), smbDomain); Session session = connection.authenticate(ac); share = (DiskShare) session.connectShare(smbShareName); List<FileIdBothDirectoryInformation> subs = share.list("mydirWhichSubDirsIwant");
You need to filter out the results from the returned list. If you only want the subdirectories you can get them as follows: List<String> subDirectories = new ArrayList<>(); for (FileIdBothDirectoryInformation sub: subs) { String filename = sub.getFileName(); if (".".equals(filename) || "..".equals(filename)) { continue; } if (EnumWithValue.EnumUtils.isSet(sub.getFileAttributes(), FileAttributes.FILE_ATTRIBUTE_DIRECTORY)) { subDirectories.add(filename); } }
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "java, samba, smb, smbj" }
Can't add attribute to object JS I'm recovering an object from mongoose, I can see and access all it's attributes, but I can't create new attributes for that object. What I tried transfer.test= 'test'; Order of calls: console.log(transfer); transfer.test = 'test'; console.log(transfer); console.log(transfer.test); Output: { _id: '0000000000000303', Ammount: '1', State: 'SUCCESS', TimeStampStarted: '1512043753', LastUpdate: '1512043763', __v: 0 } { _id: '0000000000000303', Ammount: '1', State: 'SUCCESS', TimeStampStarted: '1512043753', LastUpdate: '1512043763', __v: 0 } test Why isn't it there? why am I not getting some error, warning etc? PD I checked the type of transfer, it's an object
What you see when console.log a Mongoose object is not all its info, just a representation. Mongoose objects have a lot of variables that Mongoose needs to manage it. Sometimes, this represantion is not updated. Although it is storing the information correctly in the object, it is not printing it well. If you don't need Mongoose characteristics in this object anymore, you can do transfer = transfer.toObject(); and it will be a JavaScript object from now on, and it should show everything updated.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, node.js, mongoose, attributes" }
Only Allow ForeignKey Selection of User Values I'm trying to build a form, where a user can select a foreignkey from a drop down menu. However, I can't seem to find a way to limit the foreignkey values to those associated with the logged in user. For example, Models.py class Site(models.Model): trip = models.ForeignKey(Trip) user = models.ForeignKey(User) When I pass the ModelForm to the template, a drop down list is generated with ALL the trip values. How do i get a drop down list to only contain the trip values of a specific logged in user instead?
You can do this: class SiteForm(ModelForm): class Meta: model = Site def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(SiteForm, self).__init__(*args, **kwargs) self.fields['trip'].queryset = Trip.objects.filter(id__in=user.site_set.values_list(trip, flat=True)) and in the view, form = SiteForm(user=request.user)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, django" }
How to delete some extra folder using rpm I am using Fedora 10, I have created an rpm file for my software. It removes all the files from the installed directory. If i use yum remove command or rpm -e command. but after installation my application automatically creates some extra folders in home directory. If I uninstall my application then file from home directories do not get removed. So what I have to do. Is there anything that I have to write in my spec file?
You need to create a post-uninstall script inside your rpm. > The **%postun** Script > > The **%postun** script executes after the package has been removed. It is the last chance for a package to clean up after itself. Quite often, %postun scripts are used to run ldconfig to remove newly erased shared libraries from ld.so.cache. See: Maximum RPM: Taking the Red Hat Package Manager to the Limit
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "linux, rpm, specs" }
This code explain how to use Alamofire with swift.but the error is " Editor placeholder in source file" .How to solve this? func downloadImage() { Alamofire.request(" { (progress) in print(progress.fractionCompleted) }) .responseData{ (response) in print(response.result) print(response.result.value ) } }
The same issue happened with me, The issue was I mistakenly typed some spaces with special characters which are not visible in Xcode (weird but yeah it's true) func downloadImage() { Alamofire.request(" { (progress) in print(progress.fractionCompleted) }) .responseData{ (response) in print(response.result) print(response.result.value ) } //Remove your extra spaces here i think there is somthing fishy in these whitespaces }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "swift" }
why is a cylinder lock key not symmetrical? If you look at a mortice lock key from the side (< it is symmetrical from tip-to-base. This is because the same key can be inserted into the same lock from either side of the door. however, on some doors with simple cylinder locks (like this) < the key can also be inserted from either side of the door, yet it is not symmetrical. how does this work?
The mortise lock type for the key that you depict has a single locking mechanism that can be reached by the key inserted from either side of the door. The cylinder lock you refer to is actually _two separate cylinders_ that are keyed alike, that each have a simple rod at their back that activates the lock mechanism.
stackexchange-diy
{ "answer_score": 8, "question_score": 1, "tags": "lock" }
Android 5 static bluetooth MAC address for BLE advertising Android 5 introduces BLE MAC address rotating for increased privacy. Every time when calling BluetoothLeAdvertiser.startAdvertising(), the MAC-address is changed. Is it possible to disable address rotating, and just use the same MAC address during the entire lifetime of BluetoothLeAdvertiser?
The MAC Address is a physical address and does not change. In BLE terminology, it is the Public Device Address or BD_ADDR for BR/EDR. I haven't tried it, but reading it with readAddress() should return the same value each time. What the Android's BLE framework does is NOT use that address when advertising. It rather enables privacy by using Private Resolvable Addresses which may change every few minutes or so but still allow bonded devices to recognize it using the IRK exchanged at bonding. For obvious privacy reasons, Android's BLE framework does not allow you to set the Controller to use the public address when advertising. So you cannot disable the "address rotating".
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 15, "tags": "bluetooth, bluetooth lowenergy, android 5.0 lollipop, ibeacon android" }
Python remove try inside except? In python I have a function called `func()` which could raise `NoSuchElementException`: I'm trying to call it with `input1` if not correct call it with `input2` else give up. Is there any better way to write this code for clarity: submit_button = None try: submit_button = func(input1) except NoSuchElementException: try: submit_button = func(input2) except NoSuchElementException: pass
you can do something like: for i in [input1, input2]: try: submit_button = func(i) break except NoSuchElementException: print(f"Input {i} failed") else: print("None of the options worked") If the first input doesn't throw an exception you break the loop, otherwise you keep in the loop and try the second input. This way you can try as many inputs as you want, just add them into the list The else at the end executes if you never broke the loop, which means none of the options worked This works well if you want to try several inputs and treat them equally. For only two inputs your code looks readable enough to me. (try this, if it doesn't work try that)
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "python, python 3.x, exception, try catch" }
MS SQL Server How to find Linked Server IP address and local instance I've inherited a linked server and would like to access the server and db\instance locally. I suspect the linked server isn't necessary and a better solution might be available. Problem is there is no documentation on the Linked Server and the person that set it up has long since left. My question is: How can I find out the IP address, machine name, SQL db and instance name(s) from the linked server?
You can either use EXEC sp_linkedservers Or SELECT * FROM sys.servers To find more info on your current linked servers. The error referencing `MSDASQL` suggests an issue with an ODBC (system) data source created on the server, so if you go to Control Panel->Administrative Tools-> Data Sources (ODBC) you might start finding your answers there.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql server, linked server" }
List of all words matching regular expression Let assume that I have some string: "Lorem ipsum dolor sit amet" I need a list of all words with lenght more than 3. Can I do it with regular expressions? e.g. pattern = re.compile(r'some pattern') result = pattern.search('Lorem ipsum dolor sit amet').groups() result contains 'Lorem', 'ipsum', 'dolor' and 'amet'. EDITED: The words I mean can only contains letters and numbers.
>>> import re >>> myre = re.compile(r"\w{4,}") >>> myre.findall('Lorem, ipsum! dolor sit? amet...') ['Lorem', 'ipsum', 'dolor', 'amet'] Take note that in Python 3, where all strings are Unicode, this will also find words that use non-ASCII letters: >>> import re >>> myre = re.compile(r"\w{4,}") >>> myre.findall('Lorem, ipsum! dolör sit? amet...') ['Lorem', 'ipsum', 'dolör', 'amet'] In Python 2, you'd have to use >>> myre = re.compile(r"\w{4,}", re.UNICODE) >>> myre.findall(u'Lorem, ipsum! dolör sit? amet...') [u'Lorem', u'ipsum', u'dol\xf6r', u'amet']
stackexchange-stackoverflow
{ "answer_score": 19, "question_score": 9, "tags": "python, regex" }
Why doesn't component scan pick up my @Configuration? I have a config file like package com.mypackage.referencedata.config; @Configuration @ComponentScan ("com.mypackage.referencedata.*") public class ReferenceDataConfig { In a spring xml if I have <context:component-scan base-package="com.mypackage.referencedata.config.*" /> it does not get loaded. If I use <context:component-scan base-package="com.mypackage.referencedata.*" /> it works. What gives? I'd expect the 1st to work as well.
<context:component-scan base-package="com.mypackage.referencedata.config.*" /> Will scan packages inside `com.mypackage.referencedata.config` as it is package. com.mypackage.referencedata.config Will work fine.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "java, spring, configuration, annotations" }
Configur a spec file for rpm build and installation for a java project I was to create a RPM file for a java based project. So what I have is an Enterprise archive and some configuration file. My task is to write a spec file to build the rpm and to share so that end user can install it into the system. At installation, the ear should be copied to the deployment folder of jboss. Database must be there if not, do create the new one. I am able to write the rpm build configuration in spec file under %prep, %build and %install sections. However, I am not able to find how can I configure spec file so that I can copy the ear into the deployment folder and the configuration file into the required path while installation. Could you please help. Thank you in advance.
You can write "scriptlets" under Section '%pre' (processings before installation on the target host) and '%post' (after installation on the target host). In these scripts you have to find out where your deployment folder is located. Is your JBOSS packed in an rpm?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "rpm, rpm spec" }
XMLSerializer in IE9 compatability mode not working I have this code: .... jQuery(document).ready(function() { function showResponse(responseText, statusText, xhr, $form) { var myxml = responseText; var serializer = new XMLSerializer(); var xmltostring = serializer.serializeToString(myxml); It works fine in all browsers except IE9 when IE9 is in compatability mode. For reasons we won't go into the client needs to run IE9 in compatability mode so I am trying to find a solution. The error that is reported is: 'XMLSerializer' is undefined Does anybody know a way to deal with this? Is there another way to convert the DOM document/object into text like XMLSerializer does? Thanks.
Ended up doing something like this which seems to get the job done: var xmltostring=''; if (typeof window.XMLSerializer !== 'undefined') { var serializer = new XMLSerializer(); xmltostring = serializer.serializeToString(myxml); } else { if(window.ActiveXObject){ xmltostring = myxml.xml; } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, jquery, internet explorer, dom, xmlserializer" }
How to solve complex fractions? > $$f\circ g=\frac { \dfrac { x+3 }{ x-6 } -2 }{ \dfrac { x+3 }{ x-6 } +8 }$$ How would I solve this complex fraction? I know what the answer is, but I am just not sure how they got there. The answer is $$\frac{-x+15}{9x-45}$$ I have tried multiplying both sides by $(x-6)$ but I am getting $x^2-3x-18$? What am I doing wrong here?
$$f\circ g=\frac { \frac { x+3 }{ x-6 } -2 }{ \frac { x+3 }{ x-6 } +8 } =\frac { \frac { x+3-2x+12 }{ x-6 } }{ \frac { x+3+8x-48 }{ x-6 } } =\frac { -x+15 }{ x-6 } \cdot \frac { x-6 }{ 9x-45 } =\frac { 15-x }{ 9x-45 } $$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "linear algebra, fractions" }
Creating a file that returns an image from an external server As the title says, I want to create a file that returns an image from an external server without downloading / storaging it. I tried something with PHP headers, but it didn't work as intended (I can't find the code right now sorry). For example, if we have an image_displayer.php file. image_displayer.php?url= This URL should return the " image. This image will be displayed from an HTML file from the same server. I couldn't get it working with PHP headers (it was giving problems in the HTML file) It doesn't have to be in PHP. It doesn't matter to me. Thanks in advance.
You could try something like this: $image_data = file_get_contents(IMAGE_URL); $image_resource = imagecreatefromstring($image_data); header('Content-Type: image/png'); imagepng($image_resource); imagedestroy($image_resource); If you just want to quickly show the image without handling it, you could simply do a 301 redirect to it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, php, html, image, http headers" }
Using Polymer conditional attributes with HAML According to the documentation for Polymer expressions, you can bind data to conditionally assign an attribute using the conditional attribute syntax: > # Conditional attributes > > For boolean attributes, you can control whether or not the attribute appears using the special conditional attribute syntax: > > > attribute?={{boolean-expression}} > That's great, but I'm using HAML where attributes are assigned to elements like this: %element{attribute: "value"} I can't add a question mark before that colon without HAML giving me a syntax error. So how can I use Polymer's conditional attributes (or a functional equivalent) when I'm using HAML to generate my HTML?
One potential solution is to use the `:plain` filter to insert raw HTML into your HAML file: :plain <element attribute?={{boolean-expression}}></element> A bit ugly, but it seems to work. If you need to enclose some HAML-generated tags in one of these plain HTML tags, you'll need to use the `:plain` filter twice; once for the opening tag, and once for the closing tag. :plain <element attribute?={{boolean-expression}}> -# HAML Content Here :plain </element> Be sure not to indent your HAML code after the opening tag, otherwise it will become part of the "raw HTML" output and get sent as plain text to the browser instead of being processed as HAML.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "haml, polymer" }
Bios not recognizing USB in EFI mode I got a brand new Laptop with pre installed windows OS i wanted to do a clean install Okay so this is what i did i created a bootable USB of windows 8.1 Pro. Then i booted my laptop which was by default in EFI mode which didnt detect my pendrive so i did a google search and the suggestion was to change the bios to legacy mode. i changed it to legacy mode and the usb was detected i did a clean install successfully but the problem was the clean install changed my laptop hdd to mbr disk. but i want it to be an gpt installation How do i do it without losing my data. if conversion without data loss is not possible how to i make sure i do a clean install by making sure it installs to a efi partitioned hdd I want a gpt drive because the boot time is faster and is less annoying i dont want to see a black screen with a dash which displays for a few seconds. Please help me out im really frustrated with this two different systems
Well after experimenting a bit i found the answer to my own question. If one has to clean install windows 8 and to install on a GPT partitioned hdd , the bios settings must be changed to UEFI mode and only then the installation must begin. for the bios to recognise ones USB as UEFI device ,the win iso must be installed on the USB as GPT partition. I used a software called Rufus it had the ability to make my pen-drive bootable as UEFI device. If one has to clean install windows 8 and to install on a legacy(MBR) partitioned hdd , the bios settings must be changed to legacy mode and only then the installation must begin. Some Bios have the capability of recognising both legacy and UEFI devices hence the setting must be set to both if you don't really care about the partitioning system
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "windows 8, bios, operating systems, efi" }
How to escape comma in SOQL UPDATE: SELECT Id, Name, Signature FROM User WHERE Signature = 'This is a test, this is a another test, this is a last test' the above query returns the data only after I have split that in lines Any explanation? I do not see any HTML code in the field END UPDATE I'm trying to write simple SOQL query that has comma in it. > SELECT Id, Name, Signature FROM User WHERE Signature = 'This is a test, this is a another test, this is a last test' If i run the above SOQL I do not get any result and I even tried with `LIKE` > SELECT Id, Name, Signature FROM User WHERE Signature LIKE 'This is a test, this is a another test, this is a last test%' Is there a way escape the `comma`?
Here is how I able to make it work, hope this will help others: string s = 'This is a test,'+'\r\n'+'this is a another test,'+'\r\n'+ 'this is a last test'; SELECT Id, Name, Signature FROM User WHERE Signature =: s;
stackexchange-salesforce
{ "answer_score": 0, "question_score": 0, "tags": "soql" }
Spliting a text using json parser in java I have few lines of strings in my property file i need to import it and split those lines and use it the way i want Example format of my property file 007.customerclass = component:keyboard;determinantType:key;determinant:test;waste 008.ReasonClass = component:mouse;determinantType:click;determinant:rest;RClass I need to split the entire 007 line and 008 into 4 different parts . Expected output : keyboard key test waste and mouse click rest RClass I have achieved this using `split` but i want to achieve it using `jsonparser` to minimize my code Thank you
This is not a valid JSON format. However, you can work it out this way: String propertyValue = "component:keyboard;determinantType:key;determinant:test;waste"; // tokenize the input string with the separator StringTokenizer tokenizer = new StringTokenizer(test, ";"); // get the tokens and replace the unwanted part String component = tokenizer.nextToken().replaceAll("component:", ""); String determinantType = tokenizer.nextToken().replaceAll("determinantType:",""); String determinant = tokenizer.nextToken().replaceAll("determinant:", ""); String endElement = tokenizer.nextToken(); System.out.println(">>1"+component+" 2>>"+determinantType+" 3>>"+determinant+" 4>>"+endElement);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, json" }
Redirect Traffic to "Site Down For Maintenance" Page - WordPress on Amazon EC2 I have a WordPress blog hosted on an Amazon EC2 microinstance. I created a child theme which I am currently using. Now that the site is live, I need to maintain it for a couple of hours every other day. My question is, how do I direct any users that may visit the site to a "Down For Maintenance" page in my child theme? I looked at this question which suggested altering the routes but this was specifically for Kohana. Any assistance will be appreciated. Thanks in advance. PS: Sorry if this question is more appropriate for Server Fault, however, I was banned from SF for asking two questions that were down voted.
You need to use this plugin for your requirements. Enjoy!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "wordpress, amazon ec2" }
Is there a method just write `---` to get an em-dash, putting thinspace both before and after it? Is there a method just write `---` to get an em-dash, putting a thinspace both before and after it? The situation about break is similar with the original ---.
You can use `microtype`: \documentclass{article} \usepackage[kerning=true]{microtype} \SetExtraKerning {encoding = {OT1,T1,T2A,LY1,OT4,QX,T5,TS1,EU1,EU2}} % all text { \textemdash = {167,167} % thinspace = 1/6 em } \begin{document} Single hyphen in text mode: text-text, and in math mode: $a-b$. Double hyphen in text mode: text--text, and in math mode: $a--b$. Triple hyphen in text mode: text---text, and in math mode: $a---b$. Quadruple hyphen in text mode: text----text, and in math mode: $a----b$. \end{document} Compiled: !compiled example 400% zoom: !compiled example - zoom If you do not like other `microtype` features (i.e., protrusion and expansion), you can disable them by adding respective options to `\usepackage`.
stackexchange-tex
{ "answer_score": 21, "question_score": 20, "tags": "spacing, punctuation, kerning" }
How to deploy Administration Area only one a different website I have actually a project which is divided on 3 parts (with 2 areas) * Website * Administration (area) * Moderator (area) **Website** will be deploy on _www.site.com_ without areas **Administration** and **Moderator** areas will be deploy on _www.adminsite.com_ without website ## Why I've do this ? * Maintain only one project. * Share code and views ## Question How I can deploy my application like I want ? \- Is there a way to deploy only website without areas ? \- Is there a way to deploy Areas without website ? ## Are there another solutions, I'm listening to you ?
After wainting answers, I consider the only way to do it in the best way is to create another MVC website project and duplicate Views. Thanks for @shwetaOnStack for his attention.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "asp.net mvc, asp.net mvc 5, web deployment" }
How do I ensure my javascript only executes after all external <script src="..."> have loaded their contents? Our website uses the Google API to execute google searches. The problem I am experiencing is that the following code fails... <script src=" type="text/javascript"></script> <script type="text/javascript"> google.load('search', '1'); </script> It fails with the following error message: > 'google' is undefined My guess is that this is happening because the Google API has not loaded completely before the script executes. Should I use JQuery's document.ready? I read that this will start executing script when the DOM has finished loading. I assume this does not include loading external resources like scripts, stylesheets and images?
Unless you specify `defer` or `async` attributes, `<script>`s always load and execute sequentially; the second script will only be executed after the first one has loaded and executed. (Note that this doesn’t necessarily mean you’ll already notice a difference at this point; for example, I could execute the script `window.onload = function() { alert(42); };` right now, but I will only see its result when the `onload` event fires.) If you’re using this code: <script src=" <script> google.load('search', '1'); </script> And you get an error message saying `google` is undefined, it means the first script failed to load.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "javascript, jquery" }
Convert a plane string to date format in Python I have a plane text like '20211111012030' and need to convert it to ' **YYYY-MM-DD HH:MM:SS** '(2021-11-11 01:20:30) format in python .How can I convert it to a specific format as above
You could use a regex approach: inp = '20211111012030' output = re.sub(r'(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})', r'\1-\2-\3 \4:\5:\5', inp) print(output) # 2021-11-11 01:20:20
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "python, pyspark, databricks" }
Unable to rollback GAE Deployment Transaction I am trying to use the appcfg.sh in the GAE Java SDK to rollback a stuck (in progress) deployment. However the rollback is failing because I have an space character in the Folder name for the Project: appengine-java-sdk-1.3.5/bin/appcfg.sh rollback "workspace/ **Crowded\ Intelligence** /war/" (fails) appengine-java-sdk-1.3.5/bin/appcfg.sh rollback 'workspace/ **Crowded\ Intelligence** /war/' (fails) appengine-java-sdk-1.3.5/bin/appcfg.sh rollback workspace/ **Crowded\ Intelligence** /war/ (fails) Any thoughts on how I can get around this?
if you dont want to rename or renaming is not a solution for you, then you may do this: cd /users/username/workspace/Crowded Intelligence/ now when in your project do /users/username/downloads/appengine-java-sdk-1.3.5/bin/appcfg.sh rollback war This way you dont mention the part with the space in it
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, google app engine" }
PDO Prepared statement Uncaught exception error message i am trying to run this PDO Prepared statement $stmt = $pdo_conn->prepare( "INSERT into email_attachments (email_seq, attachment) values (:email_seq, :attachment) "); $stmt->execute(array( ':email_seq' => $admin_email_sequence, ':attachment' => $_SERVER["DOCUMENT_ROOT"].'/'.$settings["ticket_files_folder"].'/'.$ticketnumber.'-'.$currentDate.'-'.$at[filename], $at[attachment] )); but I'm getting this error: > `Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in /home/integra/public_html/autocheck/support_emails.php:662 Stack trace: #0 /home/integra/public_html/autocheck/support_emails.php(662): PDOStatement->execute(Array) #1 {main} thrown in /home/integra/public_html/autocheck/support_emails.php on line 662`
You have an extra **)** inside your execute array, also you have an extra array element ( **$at[attachment]** ) Try this code $stmt = $pdo_conn->prepare("INSERT into email_attachments (email_seq, attachment) values (:email_seq, :attachment) "); $stmt->execute(array( ':email_seq' => $admin_email_sequence, ':attachment' => $_SERVER["DOCUMENT_ROOT"] . '/' . $settings["ticket_files_folder"] . '/' . $ticketnumber . '-' . $currentDate . '-' . $at[filename] ));
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "php, pdo" }
Specialize base class with template template parameter I bang my head against the following code: template<class... Ts> struct typelist{}; template<class S> struct Fun; template<template<class...> class S, class... Ts> struct Fun<S<Ts...>> { std::tuple<Ts...> _fun; }; template<class S, class P> struct Gun; template<template<class...> class S, class... Ts, class P> struct Gun<S<Ts...>, P>: Fun<S<Ts...>>{ auto hun(){ std::cout << std::get<0>(_fun); // error: use of undeclared identifier '_fun' } }; auto main(int /*argc*/, char* /*argv*/[])-> int { auto gun = Gun<typelist<int>, float>{}; gun.hun(); return 0; } I do not get what is going on here and why I am getting that error. There must be smth obvious I do not see...
Note that the base class is dependent on the template parameters, and `_fun` is a nondependent name, which won't be looked up in dependent base classes. You could make the name `_fun` dependent then it'll be looked up at the time of instantiation; at that time the exact base specialization is known. e.g. std::cout << std::get<0>(this->_fun); // ~~~~~~ std::cout << std::get<0>(Fun<S<Ts...>>::_fun); // ~~~~~~~~~~~~~~~
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++, templates, inheritance, variadic templates" }
Label field with just an image How can I add a Field that is just an image ? I;ve being try to override paint in LabelField but its not working - import net.rim.device.api.system.EncodedImage; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.component.LabelField; public class CustomLabelField extends LabelField{ private EncodedImage image; public CustomLabelField (EncodedImage image){ super("",HCENTER | ELLIPSIS ); this.image = image; } public void paint(Graphics graphics){ graphics.drawImage(0, 0, image.getWidth(), image.getHeight(), image, 0, 0, 0); } Thanks
Have you tried using the BitmapField? If you only need an image this is the object to use.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "blackberry" }
How to add custom Angular library package to Azure DevOps? I have a Angular custom library and i want to push the library to Azure DevOps Artifacts.
You need to create a artifact feed, then build and publish the library to the specific Azure DevOps feed. Please refer to the following documents to know more about that: * Use npm to store JavaScript packages in Azure DevOps Services or TFS * Publish an npm package Besides, there's a blog described about that, it's straightforward to follow : Create angular library in your private npm registry on AzureDevOps . Hope that helps.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "azure devops, azure artifacts" }
How make layout for Samsung S2 size and another for Note2 size i want to make layout for Samsung S2 size and another for Note2 size i make multi layouts for normal and large and xlarge but s2 and note2 at the same category
For galaxy s2 the screen resolution is 480x800 while for note 2 it is 720x1280 For making layout for s2 place it in the folder layout-hdpi while for note 2 place it in layout-xhdpi Do give a reading of official documentation here www.developer.android.com/guide/practicesscreens_support.html
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android" }
Reference for a property of convex function Let $F:\mathbb{R} \to \mathbb{R}$ be a continuously differentiable function. It is known that if $F$ has a strict local maximum, then it is not a convex function. I just would like to ask you for a proper classic reference for that, I mean, a book where I can find that statement proved (or something similar). ADDITION: I am just asking for a book where all those basic concepts involving convexity are dealt, no matter whether this very specific statement is proved or not. EDITED: I replaced _an absolute maximum_ with _strict local maximum_.
Suppose that $F$ has a strict local maximum at $x^*\in\mathbb R$. Then, there exists some $\varepsilon>0$ such that $f(x^*)>f(x)$ for all $x\in U$, where $U\equiv(x^*-\varepsilon,x^*+\varepsilon)\setminus\\{x^*\\}$. To obtain a contradiction, suppose that $F$ is convex. Let $x_1\equiv x^*-\varepsilon/2$ and $x_2\equiv x^*+\varepsilon/2$. Clearly, $x_1,x_2\in U$ and $(x_1+x_2)/2=x^*$. By convexity and strict maximality of $x^*$, $$f(x^*)=f\left(\frac{x_1+x_2}{2}\right)\leq\frac{f(x_1)+f(x_2)}{2}\underbrace{<}_{!!!}\frac{f(x^*)+f(x^*)}{2}=f(x^*),$$ which is a contradiction. I don't know of any standalone references for this; I just made up the proof myself, using the definitions.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "calculus, derivatives, convex analysis" }
python: input is not matching import os import fileinput filenames1=os.listdir("./chi_square_metal_region_1") filenames1.sort() for line in fileinput.input("./test_input.dat"): for eachfile in filenames1: if eachfile == line: print yes I don't get any errors when I run this code, but it's not printing 'yes', which is the expected output. It should print 'yes' twice as I there are two files in input which match with `eachfile`. Why is it not printing the expected output?
The problem is that: for line in fileinput.input("./test_input.dat"): the variable line will contain '\n' at the end. Try this: import os import fileinput filenames1=os.listdir("./chi_square_metal_region_1") filenames1.sort() for line in fileinput.input("./test_input.dat"): for eachfile in filenames1: if eachfile == line[:-1]: print yes
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, input" }
THREEJS - OBJMTLLoader and Bump Map I'm loading an OBJ with an MTL which references a diffuse map and a bump. The map_Kd (diffuse map) is reading and loading in the renderer, but the map_Bump (bump map) is not. When I log the material to the console, the bumpmap property is null. Does OBJ MTL Loader work with bump maps?
I looked into MTLLoader.js and found that bump maps are not added from the mtl file. I think I've fixed this: In the file, there's a section for diffuse maps: case 'map_kd': // Diffuse texture map params[ 'map' ] = this.loadTexture( this.baseUrl + value ); params[ 'map' ].wrapS = this.wrap; params[ 'map' ].wrapT = this.wrap; break; Immediately after that, I added this: case 'map_bump': // Diffuse bump map params[ 'bumpMap' ] = this.loadTexture( this.baseUrl + value ); params[ 'bumpMap' ].wrapS = this.wrap; params[ 'bumpMap' ].wrapT = this.wrap; break; This is working for my example. If any developers see pitfalls with this modification, please let me know. Thanks.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "three.js" }
What (semi-)official hitchhiking spots exist in The Netherlands? In relation to this question, what official hitchhiking spots exist in The Netherlands? Is there more than one such sign in The Netherlands, besides the one pictured at Gooiseweg (Amsterdam) in the other question?
Those spots are called 'Liftershalte' in Dutch, Wikipedia has a list: < Don't expect too much there are only 6 of those, it's a bit of a gimmick more then anything else.
stackexchange-travel
{ "answer_score": 8, "question_score": 4, "tags": "hitchhiking, netherlands" }
CXX0017: Error: symbol not found in static library When I try to watch some variables in a static library linked with current startup project I receive this error: CXX0017: Error: symbol not found I've tried to rebuild the project/close IDE but I have same error. I can use breakpoints/step/other features. Do you have any idea why is this happening? Maybe some weird compiler flags or else... Edit: Only some variables can't be viewed in debugger! In general local variables.
Taken From < > please check whether pdb file have loaded properly from correct project folder, you can select **Debug -> Windows -> Modules** , on the Modules window, right click the symbol item, select Symbol Load Information, from the pop up window, you can see whether the pdb file is loaded and where the pdb file is loaded from.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 5, "tags": "visual studio 2010, visual studio, debugging, visual studio debugging" }
Should users give a reason why they are accepting an answer? Should users give a reason in the form of a comment why they are accepting an answer? I would hesitate and say it should be required, but should it be strongly encouraged? And strongly encourage by popping up a box if the asker hasn't commented on the answer they are accepting asking them if they want to give a comment why this answer works.
I think the reason why a user accepts an answer is implied... The solution _works_ and is the best/most elegant one provided. If the solution doesn't answer your question but helps you solve it on your own, then you might want to provide a comment saying why you accepted it.
stackexchange-meta
{ "answer_score": 3, "question_score": -2, "tags": "feature request, accepted answer" }
Send From Mobile Template to Default Template using cookies I am trying to use php to link from my mobile site to my default site. I am able to set the cookie on the theme page but when I get redirect back to the default page it just redirects me to the mobile page. I can see the cookie gets created but for some reason it wont read the cookie. Any ideas? On a side note is it right to be using a php cookie to do this? The Code: Default Templates Index page <?php if(isset($_COOKIE['cookie'])){ exit; } else{ // use detectmobilebrowser code to redirect it to m.defaultthemeurl.com } ?> Mobile Theme: <?php if(isset($_GET['default'])) { setcookie('cookie', '1', time()+165*10, '/', 'defaultthemeurl.com'); header('Location: exit; } ?> <a href="?default">logout</a>
because <a href="?default">logout</a> doesn't actually add a value to $_GET['default'] so the isset() failed. try <a href="?default=foo">logout</a> instead
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, cookies, mobile" }
is it possible to convert a 328 design to use a 32U4? I have several projects that use simple 328 based arduinos that I built myself, similar to the familiar "arduino on a breadboard" projects that I'm sure everybody has seen. They have just the bare minimum, no ftdi, etc. Is it possible to drop in the 32U4 without modifying the circuits, or would I have to do a bunch of work to the circuits to get them to work with the 32U4 chips, and if so what are the general steps?
Just had a quick look at the datasheets, and the main difference I see physically is the 32u4 is 44 pin package and the 328 is either 32 or 28 pin. Also the 32U4 seems to have a lot more peripherals. So based on that yes you will have to modify your circuit. Atmel are fairly consistant with ports and what their alternate functions are though. eg SPI on portB, uart on portD But you are just going to have to compare the pinouts on the datasheets see how they differ. And adjust pin connections accordingly. Datasheets are easy to find. Good Luck!
stackexchange-arduino
{ "answer_score": 4, "question_score": 1, "tags": "atmega328, atmega32u4" }
Vector space of bidirectional sequences indexed by $\mathbb{Z}$ I am trying to claim the following: Consider the vector space of all $(x_i)_{i \in \mathbb{Z}}$ ($x_i \in \mathbb{C}$), over $\mathbb{C}$, where all $x_i$ are zero except finitely many of them. Suppose a vector $(b_i)_{i \in \mathbb{Z}}$ is not the zero vector. Then $\\{(b_{i+n})_{i \in \mathbb{Z}}|n \in \mathbb{Z}\\}$ spans the space. I have been trying to prove that the sequence consisting of all zeros and only one 1 in the $i$-th position, $e_i$, belongs to the above span. Then, the $e_i$ being a basis for the space proves my claim. I have been trying computations, but failing.
**Counterexample:** Take $b=e_0+e_1$. Let $S$ be the shift operator, so that $(S^nb)_k=b_{k-n}$. If shifts of $b$ would span the whole space, you will have $$e_0=\sum_{n\in\mathbb{Z}} a_n S^nb\qquad (1)$$ with only finitely many $a_n$-s being nonzero. Let $n_{max}$ be the maximal $n$ with nonzero $a_n$, and $n_{min}$ --- the smallest $n$ with nonzero $a_n$. I claim, that $n_{max}\leq -1$. Indeed, assume $n_{max}\geq 0$. Then $n_{max}+1$-st component of the rhs of (1) is $a_{n_{max}}+a_{n_{max}+1}=a_{n_{max}}$. But it has to be 0, since left hand side's only nonzero component is the 0'th one. Similarly, you can show, that $n_{min}\geq 0$. Thus you would have $0\leq n_{min}\leq n_{max}\leq -1$. Contradiction.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "linear algebra, vector spaces" }
How to create dynamic database in entity framework with specified path? currently i create dynamic database **using CreateDatabase() method** in Entity Framework. it executes sucessfully and it creates database at following path: **"c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA"** but i want to create database in my application's directory. how to do this? please help me.
Normally all databases are created on default path configured in SQL Server. Only if you are using SQL Server Express and if you define connection string which specifies database to be created in your data folder it will use your application folder. It will work only with SQL Server Express. Make sure that inner part of connection string looks like: Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\YourDbFile.mdf;Database=YourDbName; Integrated Security=SSPI; Where `|DataDirectory|` placeholder which will be replaced by path to your data directory. For web application it should be App_Data and for standalone applications it should be application's folder. You can also use any path directly in connection string or control DataDirectory resolution from code by using: AppDomain.CurrentDomain.SetData("DataDirectory", YourPath);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "entity framework 4, entity framework 4.1, entity, edmx" }
why no tailOption in Scala? Why is no `tailOption` in Scala, if there is `headOption` ? This is an old question, found no answer on google.
There is no need for `tailOption`. If you want a function behaving like `tail`. but returning empty collection when used on empty collection, you can use `drop(1)`. I often use this when I want to handle empty collection gracefully when creating a list of pairs: s zip s.drop(1) If you want `None` on empty collection and `Some(tail)` on non-empty one, you can use: s.headOption.map(_ => s.tail) or (if you do not mind exception to be thrown and captured, which may be a bit slower): Try {s.tail}.toOption I can hardly imagine a reasonable use case for the other options, though.
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 10, "tags": "scala" }
PostgreSQL and South migrations sequences I switched from MySQL to PostgreSQL and running migrations and it is a bit strange after MySQL. When I run `./manage.py migrate` on a clean db, whenever the migration comes to a field which is ForeignKey or any other relation field, which is not yet created in db, it raises an error and stops. In MySQL you just run migrate and it does all for you, MySQL created these non-existing fields. So can I somehow to control the execution of migrations like, please postgres go and do that migration first and that second and so on, because otherwise all you gotta do is do migrate manually one by one.
You can explicitly set dependencies between migrations, as described in the docs.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, django, postgresql, django south" }
How to avoid to_char() cast in concatenation oracle? How to avoid to_char() cast with formatting fractional value to avoid possible errors in future depending on input values? e.g. SELECT -0.56 || 'value' FROM DUAL; will return > -.56value and I would like to have > -0.56value. I know that I can use select to_char(-0.56, '990.00') || 'value' from dual; But I don't know how many digits can be in the future
You can use `to_char(-0.56, '999999990.00')` with enough 9's to cover all your possible values. (There is always a limit, since the NUMBER data type is at most 38 digits - and yes, you could have 37 9's and a 0 in the format model.) This may add some unwanted spaces to the left; to modify that behavior, use the `fm` modifier: `to_char(-0.56, 'fm99999999990.00')`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "oracle, concatenation" }
Chapter list in TOC whilst using \chapter{} only I have a fiction book to typeset and I am using scrbook class as I thought that it is very flexible. For every chapter beginning I am using \chapter{} command and leave the field inside {} empty, so the command gives me only the text "Chapter 1." and so on. However, if there is no name for a chapter, it does not appear in TOC. Is it possible to make them appear? I hope this explains what I'm trying to achieve. **EDIT1** : I am strongly considering to use memoir class, so if somebody knows how to do this in memoir class, please, let me know. **EDIT2** : I just noticed, that with memoir class it happens automatically, but I am still interested in scrbook class hacks.
With `scrbook` you can get what you want with the following: \documentclass{scrbook} \renewcommand{\numberline}[1]{\chaptername~#1} \begin{document} \tableofcontents \chapter{\null} abc \chapter{\null} def \end{document} I assume that you don't use sections; in that case the trick must be different. * * * For using also parts, one can take a different approach: \documentclass{scrbook} \usepackage{etoolbox} \makeatletter \def\part@numberline#1{\partname~#1} \def\chapter@numberline#1{\chaptername~#1} \patchcmd{\l@part}{\begingroup}{\begingroup\let\numberline\part@numberline}{}{} \patchcmd{\l@chapter}{\begingroup}{\begingroup\let\numberline\chapter@numberline}{}{} \makeatother \begin{document} \tableofcontents \part{\null} \chapter{\null} abc \chapter{\null} def \end{document}
stackexchange-tex
{ "answer_score": 6, "question_score": 5, "tags": "table of contents, chapters, koma script, scrbook" }
pylint false positive for unused argument I'm in the process of cleaning up code with pylint in order to be able to use it for pre-commit validation. I have a lot of "unused-argument" warning when in fact they are used. Here is an example triggering a false positive. def addSeven(foo): #Here I have a warning "Unused argument 'foo'" foo += [7] example = [3, 4, 5, 6] addSeven(example) print example I do not wish to suppress globally this warning because i would like to see the times when an argument is really unused. Is there an other option that manually adding a disable comment in each occurence? Is it a known problem with pylint?
This is reasonable behavior from pylint; if the object passed is immutable then the statement given is essentially a no-op. Only when is mutable does it seem incorrect. Unfortunately if you don't want to globally disable the warning then you will need to disable it per instance.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 10, "tags": "python, pylint" }
Redeeming a 3DS game code without installing the game? A while ago I bought a Friends of Nintendo Humble Bundle, which came with quite a few codes. I still have the codes, as I couldn't find a way through the 3DS to redeem the games without installing them immediately. This is troublesome, as the first one I downloaded was Street Fighter IV, which took up quite a lot of my available blocks, and I am keen to play it for now! Although I could just redeem the code, install the game and then uninstall it, this takes up some time and can be a bit of a nuisance. I was wondering if there was a way to redeem these codes and not install them, so I can just go to my download software page and install them whenever I want at a later date, similar to how Steam handles the game library.
You can use this Nintendo site to redeem codes on a PC. It requires you to log-in with your eShop account, then you can fill in the code. Obviously it will not download the game on your computer, but it should be registered to your account.
stackexchange-gaming
{ "answer_score": 2, "question_score": 3, "tags": "nintendo 3ds 3dsxl 2ds, nintendo eshop" }