prompt
stringlengths
66
13.6k
chosen
stringlengths
40
27.8k
rejected
stringlengths
16
13.3k
I have this code: `$myVariable = someRanDomFunction($blah)` The problem is that `someRanDomFunction()` might return an array, an object, an empty array, boolean value or NULL. What if the best way to check that `$myVariable` has some data? right now i'm doing this: `!empty($myVariable )` Will it cover all cases? or maybe i should do `($myVariable != NULL && !empty($myVariable ))`? **UPDATE\*** By 'some data' i mean `TRUE` if its bool, not empty array, and any value other than NULL
``` var_dump(empty(NULL)); // returns bool(true) ``` empty is enough. If you say a boolean is no data, check also for !is\_bool. (`empty(false)` returns also `true`) Or better, use only `if ($result)`; this should be enough. Or what do you call "some data"? UPDATE: What you need: > > php > var\_dump(!empty([])); > > > > > > > bool(false) > > > > > > > > > php > var\_dump(!empty("")); > > > > > > > bool(false) > > > > > > > > > php > var\_dump(!empty(false)); > > > > > > > bool(false) > > > > > > > > > php > var\_dump(!empty(true)); > > > > > > > bool(true) > > > > > > > > > php > var\_dump(!empty(null)); > > > > > > > bool(false) > > > > > > > > >
Simply doing an implicit boolean check will exclude `false`, `array()`, and `null`. ``` if ($myVariable) { //will execute as long as myVariable isn't an empty array, false, null, or 0 / '0' } ``` `!empty()` does exactly the same thing, with added suppression of warnings about undefined variables / array indices. It's a little wordier, though.
I'm using jQueryUI and have a modal dialog setup. The designer wants the close button to look like this: ![enter image description here](https://i.stack.imgur.com/Stoof.png) I currently have it set up like this: ![enter image description here](https://i.stack.imgur.com/XIe09.png) The icon is not quite right, ignore that, I do however want to move it up into that top right corner. I thought I could accomplish it with the following CSS: ``` .ui-dialog .ui-dialog-titlebar-close { border-radius: 17px; height: 33px; margin: -10px 0 0; padding: 1px; position: absolute; right: -18px; top: -24%; width: 33px; z-index: 9999; } ``` However now it looks like this: ![enter image description here](https://i.stack.imgur.com/f97VZ.png) ![enter image description here](https://i.stack.imgur.com/iowij.png) How do I get it on top of the dialog? I already have a big z-index on it which doesn't work. Thankyou.
set class ui-dialog css property overflow as visilble. Hope that helps.
Try to give the different value of `border-radius` and `height` value. it could be the reason border-radius value is just half of the height. so change the `height` value. For example ``` .ui-dialog .ui-dialog-titlebar-close { border-radius: 17px; height: 50px; /*change from 33 to 50px*/ margin: -10px 0 0; padding: 1px; position: absolute; right: -18px; top: -24%; width: 33px; z-index: 9999; } ```
My Django models are organized as follows. ``` class Animal(models.Model): first_name = models.CharField(max_length=128, unique=True) class Meta: abstract = True class Cat(Animal): def meow(self): return "mreooooow" class Dog(Animal): def bark(self): return "AARF!" class EvilMonkey(Animal): def plot_world_takeover(self): return "muahahaha ..." ``` As you see, every "animal" has a unique first name within its own species. How do I filter for animals with the name "Ned"? `Animal.objects.filter(first_name="Ned")` apparently does not work.
You may want to go the route of [multi-table-inheritance](https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance). This would let you make queries on the base model.
From the docs: *Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. **This model will then not be used to create any database table.** Instead, when it is used as a base class for other models, its fields will be added to those of the child class.* Nathaniel already mentioned the solution.
we got the following vectors: $$v\_1, v\_2, w\_1, w\_3 \in V$$ $V$ is a vector space so that $\DeclareMathOperator{Sp}{Sp}\Sp\{v\_1,v\_2\} = \Sp\{w\_1,w\_2\}$ it's also defined that $\{v\_1,w\_2\}$ is linear independent. 1. Prove that the group $\{v\_1,v\_2\}$ is also a linear independent. I thought about proving it by contradiction: if $\{v\_1,v\_2\}$ is linear dependent, than we can get rid of one of the vectors. for example $v\_2$ so that $\{v\_1\}$ will be linear independent. but it is a contradiction to the given definition which says that $\{v\_1,w\_2\}$ is linear independent. that's how I thought about how to solve it but i'm not exactly sure how to prove it in my answer.
Let $[F]$ be the area of a figure $F$. Since $\angle{WYA}=30^\circ,\angle{AYZ}=60^\circ$, one has $$\begin{align}a+b&=[YWA]\\&=[\text{sector}\ YWA]-\left([\text{sector}\ ZYA]-[\triangle{ZYA}]\right)\\&=(2\sqrt 3)^2\pi\times\frac{30}{360}-\left((2\sqrt 3)^2\pi\times\frac{60}{360}-\frac{\sqrt 3}{4}\times(2\sqrt 3)^2\right)\\&=3\sqrt 3-\pi\end{align}$$ Hence, one has$$m=12-4(a+b)=12-4(3\sqrt 3-\pi)=4\pi+12-12\sqrt 3.$$
Base on the following simple principle:- $n(A \cap B) = n(A) + n(B) – n(A \cup B)$, the said region can be found by a series a additions and subtrations of regions whose areas can easily be found. Example:- ![enter image description here](https://i.stack.imgur.com/Yavgu.png) For further example, see my answer in [Find the area of the region which is the union of three circles](https://math.stackexchange.com/questions/595920/find-the-area-of-the-region-which-is-the-union-of-three-circles)
I want to use perl regular expressions on the vim command line. For example, to capitalize the words on the current line, you could type: ``` :s/(\w+)/\u$1/g ```
You can filter any line or range of lines through an external command in vim, using !. E.g., you can do: `:.!perl -pe "s/(\w+)/\u\1/g"` which will filter the current line through that perl command. ( Here `:` to get into command line mode, and the `.` which follows mean the current line; you can also specify a line range or `%` for the whole file, etc.) If you want to use vim's built in substitution patterns, the closest you'll come is to use vim's "very magic" option, \v, like so: `:s/\v(\w+)/\u\1/g` see `:help pattern` and `:help substitute` for more details. I don't think "very magic" is quite identical to perl's patterns, but is very close. Anyway, you can always use perl itself if you're more comfortable with it, as above.
Use the [eregex.vim](http://www.vim.org/scripts/script.php?script_id=3282) plugin. It's very useful and I have had no problems with it.
How would you test a developer that claims to have \*nix shell experience (just to be clear, we don't want to test if someone can develop on \*nix, only that they know their way around the command line). I was thinking about making them solve a problem of getting information out of log files, which would involve some basics like cat, grep, cut, ... combined with piping. What other basic knowledge would you ask for? Once again, this isn't for interviewing someone who will develop for \*nix systems, and also not for \*nix system admins, but just for regular developers that sometimes need to do some work on a \*nix system.
From my experience with my numerous colleagues since I started to work, nobody wants to fake Unix knowledge: either they "*know their way around the command line*" or they simply say "no way!". Just ask if the candidate is willing to work on a Unix workstation and let him tell you how far he can go through bash. He will eventually name some commands; the most obvious ones are `cd`, `cat`, `more` or `less`, `vi` or `emacs`, `grep`, `awk`, `sed`. Listen carefully whether he mentions `man`. If it is for developing, he should be familiar with `make` and Makefiles, and some source control command line interface (`svn`, `git`, `cleartool`, `hg`, `cvs`...)
It depends on what level of experience you want them to have. IF this isn't for someone who will develop for \*nix systems, and also not for \*nix system admins, but just for regular developers that sometimes need to do some work on a \*nix system, how much experience do they actually need? Anything such a developer might need in \*nix shells (ls, chmod, cat etc.) could probably be written on a single page cheat sheet. If so, requiring \*nix shell knowledge where it is not required might eliminate some good candidates.
I have data that looks like this: ``` country source 0 UK Ads 1 US Seo 2 US Seo 3 China Seo 4 US Seo 5 US Seo 6 China Seo 7 US Ads ``` For each country I want to get the ratio of each source. I did a groupby on country and source and got the table below which has the total counts for each source in each country but not sure how to go from here. ``` df.groupby(['country', 'source']).size() country source China Ads 21561 Direct 17463 Seo 37578 Germany Ads 3760 Direct 2864 Seo 6432 UK Ads 13518 Direct 11131 Seo 23801 US Ads 49901 Direct 40962 Seo 87229 ``` I'm looking for something like this: ``` Ads SEO Direct US .3 .1 .4 China .5 .3 .2 UK .5 .3 .6 ```
You could do something like for debugging such errors. ``` process.on('uncaughtException', function(err) { console.log(err.stack); throw err; }); ``` You could also increase your stack trace size limit and/or stack size. ``` node --stack_trace_limit=200 app.js //defaults to 10 node --stack-size=1024 app.js // defaults to 492kB ```
Stack Trace does not contain your file because this type of error is created server connection issue like: **Host Timeout** ``` [ 'code' ] e.code => ECONNRESET ``` **Console output** ``` { Error: socket hang up at createHangUpError (_http_client.js:250:15) at TLSSocket.socketCloseListener (_http_client.js:282:23) at emitOne (events.js:101:20) at TLSSocket.emit (events.js:188:7) at TCP._handle.close [as _onclose] (net.js:492:12) code: 'ECONNRESET' } ``` OR when the server terminates the connection unexpectedly or does not send a response. For more info check [node app error codes](https://github.com/cmrunton/tls-dashboard/blob/master/node_app/error_codes.md#host-timeout). or refer to this [issue](https://github.com/SocketCluster/socketcluster/issues/203).
I'm trying like that (also at <https://gist.github.com/1703994>): ```html <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?1.27.2"></script> <script type="text/javascript" src="http://mbostock.github.com/d3/d3.time.js?1.27.2"></script> <script type="text/javascript" src="js-libs/jquery-1.7.js"></script> <style> <!-- #test { width: 400px; height: 500px; } --> </style> </head> <body> <script type="text/javascript"> $(function() { var w = 600, h = 350; var vis = d3.select("#test").append("svg:svg") .attr("width", w) .attr("height", h) .append("svg:g") .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")"); var g = vis.selectAll("g") .data([ { x:1 , y: 2} ]) .enter().append("svg:g"); g.append("svg:path") .attr("fill", "red") .attr("stroke", "red") .attr("stroke-width", "10") .attr("d", "M 100 350 l 150 -300") g.select("path") .on("click", function() { console.log("Hello"); }); // XXX: how to execute click programmaticaly? }) </script> <div id="test"></div> </body> </html> ``` But doesn't work I think we may use <https://github.com/mbostock/d3/wiki/Internals#wiki-dispatch_on> But how to do it?
Simply call the `.on` method as a getter for the registered value (i.e. your handler function), then call the result of that: ``` g.select("path").on("click")(); ``` It gets a little more complicated if your handler uses the bound data and/or event fields, or if you've got multiple event listeners bound (e.g "click.thing1" and "click.thing2"). In that case, you're probably best off just firing a fake event using the [standard DOM methods](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-DocumentEvent): ``` var e = document.createEvent('UIEvents'); e.initUIEvent('click', true, true, /* ... */); g.select("path").node().dispatchEvent(e); ```
I came this thread looking for a d3 mousemove event for angular unit testing. @natevw answer ``` g.select("path").on("click")(); ``` helped a lot on mouseover event. But, applying that to mousemove was giving an e.source null error. The work around was to set the d3 event programmatically. ``` d3.event = document.createEvent('MouseEvent'); d3.event.initMouseEvent("mousemove"); d3.select(elm[0]).select("rect").on("mousemove")(); ``` Hope this helps.
This code does not work. Please tell what the error is.... ``` class Error(Exception): def __init__(self,mssg): self.mssg = mssg class InputError(Error): def __init__(self,val): super("Input Error") print val ``` Now I write in other part of my program ``` a = raw_input("Enter a number from 0-9: ") if (ord(a)>47 and ord(a)<58): pass else: raise InputError(a) ``` Now when I pass 'a' I get `super expected a type but got a string` I just want to pass that message to the base class and display it along with the wrong value. What am I doing wrong here
The problem is that you're using [`super()`](http://docs.python.org/library/functions.html#super) incorrectly. The proper way is: ``` class InputError(Error): def __init__(self, val): super(InputError, self).__init__(val) print val ```
[`super()`](http://docs.python.org/library/functions.html#super) is used to access methods of a superclass that have been overridden in the subclass, not to instantiate the superclass with arguments. What you appear to be trying to do is something like: ``` class InputError(Error): def __init__(self,val): super(InputError).__init__("Input Error") print val ``` although this isn't necessarily a good idea.
Can you make devices that produce and use electricity like power supplies, motors, light bulbs, etc. in a society without metal? Not just metal isn't in the device, you can't even use metal in the production process. Edit: There is enough trace metals for human biology to work, but not enough for metallurgy. Could static electricity generators(made from just rubbing, so metal not needed) or electric fish become feasible power supply replacements for batteries?
Graphite conducts and is a natural mineral. So does charcoal to some degree, and eventually graphene and nanotubes. I think they would work with biological materials and discover ways to treat and preserve tissues that act as electric components, and then mimic them with more synthetic forms. Look at the experiment with the dead frog twitching. If the metal in the experiment was rare and expensive so wires and probes were not commercially practical to develop, he would have focused his attention on the dead frog.
Electricity and magnetism are both present in biology (eg, see [Biomagnetism](https://en.wikipedia.org/wiki/Biomagnetism) and [Bioelectromagnetics](https://en.wikipedia.org/wiki/Bioelectromagnetics)) . Organic computers (brains) and machinery (muscles) and energy storage (food/electrolytes) are all around us. Non-metal conductive and non-conductive materials exist in gas, liquid and solid states (eg, water, ice, silica). Capacitors can be made with oil. The main issue is predicting the difficulty of bootstrapping scientific discoveries in biology without scientific knowledge and equipment based on relatively simpler metal-based technologies. You might be able to replace simple tools like scalpels with sharp mineral-based objects (ie flint, ceramics, plastics) but how do you invent the stethoscope, or heart-monitor, or electrical probe, or wires or any number of tools used in biology that currently require metal? My feeling is that given enough time a scientifically curious race would develop sophisticated bio-machinery as an offshoot of primitive breeding and genetic technology but would probably require at least 50K years to get there. If you want a real twist you could even argue that humanity or Earth itself is the product of such technology seeded by an advanced biotechnological race with space flight and extreme longevity.
this is my HTML ``` <div id="remove">Username</div> ``` and this is my JS code ``` function slice() { var t = document.getElementById("remove"); t.textContent = t.textContent.slice(0, -3); } slice(); ``` Username load from foreach ``` {foreach from=$last_user item=s} {$s.date} {$s.username} {/foreach} ``` This code working and remove 3 letter but when right click on browser and look at page sources i can see "Username" ! I need remove three letter because of privacy and security . something like \*\*\* name or usern \*\*\* Thank for help me !
The only secure way to make sure the client can't see a particular piece of information is to never send it to the client in the first place. Otherwise, there will always be a way for the client to examine the raw payloads of the network requests and figure out the information they aren't supposed to know. You'll need to fix this on your backend - either hard-code in ``` <div id="remove">Usern</div> ``` or, for a more dynamic approach, use a template engine (or whatever's generating the HTML) and look up how to change strings with it. For example, in [EJS](https://ejs.co/), if `user` is an object with a `username` property, you could do ``` <div id="remove"><%= user.username.slice(0, -3) %></div> ``` Changing the content only with client-side JavaScript will not be sufficient, if you wish to keep some things truly private. With Smarty, you can [define a modifier](https://www.smarty.net/docsv2/en/plugins.modifiers.tpl) that takes a string and returns all but the last three characters of it. ``` function smarty_modifier_truncate_three($string) { return substr($string, 0, -3); } ``` and then in your template, replace ``` {$s.username} ``` with ``` {$s.username|truncate_three} ``` If you want only the first three characters, it's easier because you can use the built-in [`truncate`](https://www.smarty.net/docs/en/language.modifier.truncate.tpl). ``` {$s.username|truncate:3} ```
JS doesn't change the source, it can only change the DOM, so what you can do is to keep the element empty and add a value to it using js, but don't forget that js runs on the client's side so its better here to send the string from the server without the last 3 characters.
I have a table : Name When I do a : **SELECT \* FROM Name**, it give the results as : ``` Name ====== aaa bbb ccc sss ``` I want the result to be like in one row only : ``` Name ==== aaa bbb ccc sss ``` How can I get this?
Try this one - ``` DECLARE @temp TABLE ( col NVARCHAR(50) ) INSERT INTO @temp (col) VALUES ('aaa'), ('bbb'), ('ccc'), ('sss') SELECT str_string = ( SELECT col + ' ' FROM @temp FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ``` Or try this - ``` DECLARE @string NVARCHAR(MAX) = '' SELECT @string = @string + col + ' ' FROM @temp SELECT @string ```
May be over-egging the pudding for your requirement but a CLR aggregate function for concatenating rows into single values is a very handy thing to have in your toolbox. Something like below. Runs much faster than xml in my experience, and supports GROUP BY etc so is quite powerful. Only works in SQL2k8 or above and will blow up if it concats a string to over 2GB. ``` [Serializable] [Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize = -1)] public struct Concatenate : IBinarySerialize { public string concat; public string delimiter; public void Init() { this.concat = ""; } public void Accumulate(SqlString text, SqlString delim) { if (!text.IsNull) { concat += (string)text + (string)delim; } delimiter = (string)delim; } public void Merge(Concatenate Group) { concat += (string)Group.concat + (string)Group.delimiter; delimiter = (string)Group.delimiter; } public SqlString Terminate() { return concat.Substring(0, concat.Length - delimiter.Length); } public void Read(BinaryReader r) { delimiter = r.ReadString(); concat = r.ReadString(); } public void Write(BinaryWriter w) { w.Write(delimiter); w.Write(concat); } ``` }
I want to bring the `user_id: 1` ones under the users with the codes I give below, but the results are always empty. I am not getting any errors, but I do not fully understand where I am making mistakes :/ \*In addition; What is `bson.M{}` What is `bson.D{}`. I did not fully understand what the differences are between? ```golang type Project struct { ID string `json:"id"` ProjectName string `json:"project_name"` Tags []ProjectTags `json:"tags"` Type int `json:"type"` Constituent string `json:"constituent"` CoverPhoto string `json:"cover_photo"` Ratio string `json:"ratio"` Width string `json:"width"` Height string `json:"height"` User []ProjectUsers `json:"users"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } type ProjectTags struct { TagName string `json:"tag_name"` Order int `json:"order"` } type ProjectUsers struct { UserID string `json:"user_id"` } ``` ```golang import ( "context" "net/http" "github.com/gin-gonic/gin" "go.mongodb.org/mongo-driver/bson" ) type projectListResponse struct { Status int `json:"status"` Description string `json:"description"` DatabaseMessage string `json:"database_message"` Projects []Project `json:"projects"` } func ProjectList(c *gin.Context) { projects := []Project{} cursor, err := (context.TODO(), bson.M{"users": bson.M{"$elemMatch": bson.M{"user_id": "1"}}}) if err != nil { c.JSON(http.StatusInternalServerError, &projectListResponse{ Status: http.StatusInternalServerError, Description: "There is problems with listing projects", DatabaseMessage: err.Error(), Projects: projects, }) return } for cursor.Next(context.TODO()) { var project Project cursor.Decode(&project) projects = append(projects, project) } c.JSON(http.StatusOK, &projectListResponse{ Status: http.StatusOK, Description: "All registered projects are listed successfully", DatabaseMessage: "No error", Projects: projects, }) return } ``` ``` { "status": 200, "description": "All registered projects are listed successfully", "database_message": "No error", "projects": [ { "id": "000000000000000000000000", "project_name": "Testxx 123", "tags": [ { "tag_name": "asdasd", "order": 1 } ], "type": 1, "constituent": "1", "cover_photo": "", "ratio": "x", "width": "100", "height": "200", "users": [ { "user_id": "1" }, { "user_id": "2" } ], "created_at": "2020-07-07T12:10:06.861Z", "updated_at": "0001-01-01T00:00:00Z" }, { "id": "000000000000000000000000", "project_name": "Test 12233", "tags": [ { "tag_name": "asdasd", "order": 1 } ], "type": 1, "constituent": "1", "cover_photo": "", "ratio": "x", "width": "100", "height": "200", "users": [ { "user_id": "1" }, { "user_id": "2" } ], "created_at": "2020-07-07T12:10:29.394Z", "updated_at": "0001-01-01T00:00:00Z" }, { "id": "000000000000000000000000", "project_name": "Test 12233", "tags": [ { "tag_name": "asdasd", "order": 1 } ], "type": 1, "constituent": "1", "cover_photo": "", "ratio": "x", "width": "100", "height": "200", "users": [ { "user_id": "5" }, { "user_id": "2" } ], "created_at": "2020-07-07T12:10:29.394Z", "updated_at": "0001-01-01T00:00:00Z" } ] } ```
--- Solution: --------- To add examples you have to decorate the action method with SwaggerOperationFilter: ``` [SwaggerOperationFilter(typeof(OperationFilter))] Upload(IFormFile file, [FromForm]IEnumerable<MetadataValue> list) [...] internal class UploadOperationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { if (operation.OperationId != nameof(DocumentController.Upload)) { return; } if (operation.RequestBody.Content.TryGetValue("multipart/form-data", out var openApiMediaType)) { var options = new JsonSerializerOptions { WriteIndented = true }; options.Converters.Add(new JsonStringEnumConverter()); var array = new OpenApiArray { new OpenApiString(JsonSerializer.Serialize(new MetadataValue {Metadata = Metadata.Cat1, Value = "ABC"}, options)), new OpenApiString(JsonSerializer.Serialize(new MetadataValue {Metadata = Metadata.Cat2, Value = "DEF"}, options)) }; openApiMediaType.Schema.Properties["metadata"].Example = array; } } } ``` To get values in the controller (not empty collection), you have to add custom ModelBinder: ``` [ModelBinder(BinderType = typeof(MetadataValueModelBinder))] public class MetadataValue { public Metadata Metadata { get; set; } public string Value { get; set; } } public class MetadataValueModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext)); var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (values.Length == 0) return Task.CompletedTask; var options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter()); var deserialized = JsonSerializer.Deserialize(values.FirstValue, bindingContext.ModelType, options); bindingContext.Result = ModelBindingResult.Success(deserialized); return Task.CompletedTask; } } ```
Following the answer provided by ***rperwinski***, if you are using ***Newtonsoft.Json*** instead of ***System.Text.Json***, you should replace: Inside the *IOperationFilter* ``` var options = new JsonSerializerSettings(); options.Converters.Add(new StringEnumConverter()); options.Formatting == Formatting.Indented; var array = new OpenApiArray { new OpenApiString(JsonConvert.SerializeObject(new MetadataValue {Metadata = Metadata.Cat1, Value = "ABC"}, options)), new OpenApiString(JsonConvert.SerializeObject(new MetadataValue {Metadata = Metadata.Cat2, Value = "DEF"}, options)) }; ``` And inside the *IModelBinder* ``` var options = new JsonSerializerSettings(); options.Converters.Add(new StringEnumConverter()); var deserialized = JsonConvert.DeserializeObject(values.FirstValue, bindingContext.ModelType, options); ```
In an effort to reduce the likelihood that I'll get mouse-related RSI in my (dominant) right hand, I've taken to using an additional second mouse with my left. I'd like to flip the left and right mouse buttons on *just* the left-hand mouse, but the **Switch primary and secondary buttons** option in the Mouse Properties window in Windows 7 applies to both mice. Does anyone know of a way of achieving what I'm after?
The following program worked for me, try it out, hope will be helpful for you! Best of luck! [EitherMouse 0.4](http://www.autohotkey.com/forum/topic48238.html) - auto switch mouse buttons on second mouse
Unless your mouse has some proprietary drivers/apps that let you reconfigure the buttons to whatever you want, you can't do it from Windows alone. As you already found, the Windows Mouse properties window applies to all plugged-in and recognized pointing devices. Collectively they will share one cursor and set of behaviors (double-click speed, appearance, primary/secondary, etc.).
I've written a small program in C++ that prompts the user for input, the user gives a number, then the computer displays the number reversed. For example: 17 becomes 71. 123 becomes 321. This is the program: ``` #include <iostream> #include <string> //for later use. using namespace std; int rev(int x) { int r = 0; while(x) { r = (r*10) + (x%10); x = x/10; } return r; } int main() { int nr; cout << "Give a number: "; cin >> nr; rev(nr); cout << nr; return 0; } ``` The final result of the program: prints the same number, function has no effect. What am I doing wrong? I tried several solutions but to no avail.
While probably not in the intended spirit, the simple answer is that if you're only going to display it in reverse, you can cheat and just work with a string: ``` std::string input; std::cin >> input; std::cout << std::string(input.rbegin(), input.rend()); ```
You're not actually using the value that `rev` returns. You're just using the value `nr` which you pass to rev, and since you don't pass by reference, rev isn't being affected locally. What you want to say is: ``` int nr; cout << "Give a number: "; cin >> nr; int result = rev(nr); cout << result; return 0; ```
I accidentally killed my `ssh-agent`, how do I restart it without having to reconnect ? I tried this but it does not work : ```bsh $ eval $(ssh-agent -s) Agent pid 8055 ``` Then, I open a new Gnome terminal with CTRL+SHIFT+N from the previous terminal window and type : ```bsh $ ssh-add Could not open a connection to your authentication agent. ``` But if I open a new Gnome terminal from my first Gnome terminal by typing : ```bsh $ gnome-terminal & ``` then this new window is able to connect to the `ssh-agent`. Is it not possible for all my Gnome terminals to "see" the `ssh-agent` without having to reconnect to the PC/server ?
**This doesn't work as you supposed. ssh-agent overwrites the configuration.** TO FIX THIS--- *Find agent:* ``` eval "$(ssh-agent -s)" ``` Agent pid 9546 *Kill PID:* ``` kill -9 9546 ``` THEN YOU CHECK ``` ssh git@gitlab.com-test ssh git@gitlab.com ``` It should work now.
Try restart using the following command: ``` sudo service ssh restart ``` The private/public RSA SSH keys are located in ~/.ssh/id\_rsa and ~/.ssh/id\_rsa.pub, respectively. You can transfer the public key to another machine to connect to it through public key authentication. This can be done via ssh-copy-id like so: ``` ssh-copy-id username@host ``` Or you can append your public key (id\_rsa.pub) to the server's /home/username/.ssh/authorized\_keys file, which is in essence what ssh-copy-id does.
I have a tab view in my activity, Currently I am doing a UI update in my fragments `onCreateView` but I don't think this is the correct place. Is there a method I can overload which will be called when my tab gains view? So that when my user clicks on or scrolls to my tab, I can then poll my server and update my view. Some simplified code: ``` @SuppressLint("NewApi") public class Rhino68PanelActivity extends FragmentActivity implements ActionBar.TabListener { static String TAG = "Rhino68PanelActivty"; /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which * will keep every loaded fragment in memory. If this becomes too memory * intensive, it may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rhino68_panel); // Set up the action bar. final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create the adapter that will return a fragment for each of the three // primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); // When swiping between different sections, select the corresponding // tab. We can also use ActionBar.Tab#select() to do this if we have // a reference to the Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this)); } } @Override protected void onDestroy() { super.onDestroy(); Network.cancelRequests(Rhino68PanelActivity.this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.rhino68_panel, menu); return true; } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in // the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. Fragment fragment = null; switch (position) { case 0: { fragment = new OneSectionFragment(); } break; case 1: { fragment = new TwoSectionFragment(); } break; case 2: { fragment = new ThreeSectionFragment(); } break; default: { fragment = new OneSectionFragment(); } } return fragment; } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return "1"; case 1: "2"; case 2: "3"; } return null; } } public static class oneSectionFragment extends Fragment { private static Context mContext; public StatusSectionFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_rhino68_panel_status, container, false); mContext = getActivity(); // update view .... return rootView; } //fucntions and methods } public static class twoSectionFragment extends Fragment { private static Context mContext; public StatusSectionFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_rhino68_panel_status, container, false); mContext = getActivity(); // update view .... return rootView; } //fucntions and methods } ```
Problem 1: know which tab has focus Solution: setOnPageChangeListener on your ViewPager. With the received index, you know which tab is active. Problem 2: how to execute a method from the active page (fragment) Solution: 1. create a public method in your viewpager adapter: onNewTabSelected(int index) 2. create your tab fragment accessible in your adapter (private MyTabFragment tabFragment;) 3. with the index, you know which Fragment you should use 4. create a public method in your Fragment 5. execute this method in the new created method inside your adapter
You can update your view in each SectionFragment by using: ``` @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { } else { } } ``` @see: [How to determine when Fragment becomes visible in ViewPager](https://stackoverflow.com/questions/10024739/how-to-determine-when-fragment-becomes-visible-in-viewpager)
I'm looking for a laymen's introduction to computer hardware and organization. Here are some of the topics I would like to cover. > > 1. Brief intro to electronics. > 2. Gates and state machines, intro to register transfer and timing. > 3. Basic CPU design. Control. > 4. Microprogrammed CPU design. > 5. Cache systems. > 6. Memory hierarchy:registers, cache, RAM > 7. Virtual memory organization. > 8. Disk storage systems. > 9. Internal busses-front side, memory, PCI > 10. Internal busses for storage-IDE, SATA, SCSI > 11. External busses-USB and firewire > 12. Display systems and GPUs > > > I would prefer free resources online, but if nothing is available a book is fine as well. I have no background with hardware so an introductory text would be wonderful. Also I'm sorry if this isn't directly programming but I don't know where else to ask.
As mentioned already Code: The Hidden Language of Computer Hardware and Software is a great book that covers the fundamentals. Here are a couple of other books: [Computer Architecture: A Quantitative Approach](https://rads.stackoverflow.com/amzn/click/com/1558605967) [The Essentials of Computer Organization and Architecture](https://rads.stackoverflow.com/amzn/click/com/076370444X) [Upgrading and Repairing PCs](https://rads.stackoverflow.com/amzn/click/com/0789736977) Here's a good site: [PC Architecture](http://www.karbosguide.com/books/pcarchitecture/start.htm)
For computer architecture, this books is really good [Parallel Computer Organization and Design](http://www.cambridge.org/ca/academic/subjects/engineering/computer-engineering/parallel-computer-organization-and-design)
I'm relatively new to C# working on a project currently where I want to exclude an item that is edited from an exception. In this scenario a user can edit an appointment including the appointment, however; there can not be overlapping appointments. When I run my program and edit the appointment, the exception is checking against the appointment being edited which it shouldn't. Can someone advise me on how to do this? ``` foreach (var appt in AppointmentScreen.ListOfAppts) { if (selectedStart <= appt.Start && selectedEnd > appt.Start && (!(SelectApptID >= 0)) || SelectApptID >= 0) { overlaping = true; } if (appt.Start <= selectedStart && appt.End > selectedStart && (!(SelectApptID >= 0)) || SelectApptID >= 0) { overlaping = true; } } ``` if more information is needed please let me know. I will be checking periodically throughout the day. thanks for all the help in advance
How about this: ```py from itertools import chain def get_grids(grid): x, y = len(grid), len(grid[0]) assert (x, y) == (9, 9) size = 3 out = [] for i in range(0, x, size): rows = [*zip(*grid[i: i + size])] for j in range(0, y, size): out.append([*chain(*zip(*rows[j: j + size]))]) return out ``` It uses [zip](https://docs.python.org/3/library/functions.html#zip) function to get three rows at the same time then use another zip that will take now from each row vertical slice (aka 3 columns) [chain](https://docs.python.org/3/library/itertools.html#itertools.chain) is used to flatten zip's tuples to one flat list The final result looks like: ```py [[1, 3, 2, 4, 6, 5, 7, 9, 8], [5, 4, 6, 8, 7, 9, 2, 1, 3], [9, 8, 7, 3, 2, 1, 6, 5, 4], [9, 2, 1, 3, 5, 4, 6, 8, 7], [4, 3, 5, 7, 6, 8, 1, 9, 2], [8, 7, 6, 2, 1, 9, 5, 4, 3], [5, 7, 6, 2, 4, 3, 8, 1, 9], [9, 8, 1, 6, 5, 7, 3, 2, 4], [4, 3, 2, 1, 9, 8, 7, 6, 5]] ``` Another option would be create matrix[9][9] and load values to it: ``` def get_grids(grid): l = len(grid) s = 3 out = [[None]*l for _ in range(l)] for n in range(l): for m in range(l): k = (n // s) * s + m // s j = (n % s) * s + m % s out[k][j] = grid[n][m] return out ``` Or you can use traditional list comprehension ``` def get_grids(grid): l = len(grid) s = 3 return [ [grid[(j // s) * s + i // s][(j % s) * s + i % s] for i in range(l)] for j in range(l) ] ```
If you are using numpy you can use reshape and swap axes to transform a 9x9 into a 3x3 matrix containing 3x3 sub-matricies. ``` A = np.array([ [0,0,0,3,0,1,6,0,2], [0,2,0,0,0,0,7,1,0], [0,0,8,0,7,0,0,0,0], [2,4,0,5,3,8,1,9,0], [9,8,0,0,0,0,0,0,0], [7,5,0,1,2,0,4,6,8], [0,0,2,8,0,7,0,4,0], [0,1,0,0,0,0,0,0,6], [0,3,4,9,1,0,0,0,0] ]) B = A.reshape(3,3,3,3).swapaxes(1,2) ``` Or if you want a 1D array containing all nine 3x3 boxes: ``` B = A.reshape(3,3,3,3).swapaxes(1,2).reshape(9,3,3) ``` Or you could reshape it to a 9x9 containing the elements of each box on a row: ``` B = A.reshape(3,3,3,3).swapaxes(1,2).reshape(9,9) ```
I need to change the icon color according to the movie rating. I made a function that receives the value of the classification and returns a value for the className inside the svg. However, all icons turn red. Someone help me to solve this problem. **Conditions for changing color.** **Rating: 0 to 100** 0 - white 20 or 40 - red 60 - orange 80 or 100 - green ``` //Punctuation/Note const setVote = (note) => { console.log("NOTE", note); if (note === 0) { // 0 return "white"; } else if (note >= 20 || note <= 40) { return "red"; } else if (note === 60) { return "orange"; } else return "green"; }; ``` ``` <div className='box-note'> <span className='rating'>{rating}</span> <i className='icon-vote-like'> <svg id="Icon_Thumbs_Up_Filled" data-name="Icon / Thumbs Up / Filled" xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 17 17"> <rect id="Box" width="17" height="17" fill="none" /> <path id="Path_1994" fill="#6cbe61" className={setVote(rating)} data-name="Path 1994" d="M97-8.286h2.805v-8.229H97Zm15.429-7.543a1.391,1.391,0,0,0-1.4-1.371H106.6l.666-3.134.021-.219a1.021,1.021,0,0,0-.309-.727l-.743-.72-4.615,4.519a1.326,1.326,0,0,0-.414.967v6.857a1.391,1.391,0,0,0,1.4,1.371h6.312a1.394,1.394,0,0,0,1.29-.837l2.118-4.834a1.328,1.328,0,0,0,.1-.5v-1.31l-.007-.007Z" transform="translate(-96.143 23.714)" /> </svg> </i> </div> ``` **CSS** ``` .white { fill: #ffffff; } .orange { fill: #ffa500; } .green { fill: #008000; } .red { fill: #ff0000; } ``` **Current state** [![enter image description here](https://i.stack.imgur.com/A4LTn.png)](https://i.stack.imgur.com/A4LTn.png)
You have wrong condition here: ``` else if (note >= 20 || note <= 40) { return "red"; ``` instead of `||` should be `&&`. But if you want to implement ranges, you should also correct other conditions: ``` const setVote = (note) => { console.log("NOTE", note); if (note <20) { // 0-19 return "white"; } else if (note >= 20 && note <= 40) { // 20-40 return "red"; } else if (note > 40 && note <= 60) { // 41-60 return "orange"; } else return "green"; // 60+ }; ```
I found the error, it should be **===**. Look: ``` const setVote = (note) => { console.log("NOTE", note); if (note === 0) { return "white"; } else if (note === 20 || note === 40) { return "red"; } else if (note === 60) { return "orange"; } else return "green"; }; ```
I have two functions and i want to call one function when the radio button is checked as an employee and the other when the radio button is checked as a user. ``` employee.form.send = function() { employee.validator.checkForm(); if (employee.validator.valid()) { employee.form.submit(); } }; invite.form.send = function() { invite.validator.checkForm(); if (invite.validator.valid()) { alert(1); invite.form.submit(); } } ``` I would normally call them with a click event like this ``` invite.find('#sendInviteButton').on('click',invite.form.send); ``` Now i want to call different functions when the `#sendInviteButton` is clicked. Depending on the radio button selected. How do i do that? I am not able to call the `invite.form.send inside` an if condition.
The easiest way would be to create a key/value dataset and join with the original data ``` keyval <- data.frame(a = c(0, 0.001, 1, 4, 4.001, 8.001), b = c('x', 'D', 'C', 'B', 'B', 'A'), stringsAsFactors= FALSE) library(data.table) setDT(df1)[keyval, b := b, on = .(a)] df1 # a b #1: 0.000 x #2: 4.000 B #3: 1.000 C #4: 0.001 D #5: 1.000 C #6: 4.000 B #7: 4.001 B #8: 1.000 C #9: 8.001 A ``` ### data ``` df1 <- structure(list(a = c(0, 4, 1, 0.001, 1, 4, 4.001, 1, 8.001)), .Names = "a", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9"), class = "data.frame") ```
Try as.factor (x, levels=c (whatever levels and values separated by comma))
I am trying to execute reverse tcp command on a android device connected remotely(using `adb connect <ip-address>`). But I am getting following error while executing: ``` adb -s 192.168.0.101 reverse tcp:8081 tcp:8081 error: more than one device/emulator ``` but I have only one device connected. ``` adb devices List of devices attached 192.168.0.101:5555 device ``` same command works fine if I connect my device using usb. Any Ideas ?
I just came across this, and while none of the answers worked I eventually got it working repeatably. Following these steps should get you wirelessly debugging your React Native app on your real Android device. I ran `adb kill-server && adb start-server` first. I'm not sure if that's strictly necessary. 1. Connect your phone and computer to the same network 2. Connect your phone to your computer via USB 3. `adb tcpip 5555` 4. `adb reverse tcp:8081 tcp:5555` 5. `adb connect YOUR.PHONE.IP.ADDRESS:5555` You can find your phone's wifi IP address from Network Settings -> Wifi -> Wifi Preferences -> IP Address. 6. Disconnect the USB wire. 7. If the app isn't yet installed, install the app on your phone the way you usually do over USB, `react-native run android` for most cases. Open the app, and you get an “Unable to load Script” error. Pressing ‘Reload’ gives an error “Could not connect to development server.” Overcome your despair and push onwards. 8. Open the developer menu (shake the phone with your React Native app open) and select “Dev Settings”. Select “Debug server host & port for device” from the menu. Find your computer’s ip address. Enter that in the window on your phone, followed by the port number 8081: `YOUR.COMPUTER.IP.ADDRESS:8081` 9. Now shake and reload.  Sometimes this doesn’t do anything, so closing the app and reopening does the trick. At this point, you should see the bundler loading up with the familiar green bar. 10. shake and hit “debug js remotely”. From here you should have your normal debugging experience, minus the wire.
``` adb kill-server adb start-server adb reverse tcp:8081 tcp:8081 ```
I have an MVC application using Razor. I have a partial view that uses a jquery script. The jquery script only works when it is referenced in the partial view and not in the \_layout view. When using firebug, I cannot see the script when it is referenced in the partial view. Is there a way to reference all scripts in the \_layout and have it work in all views and partial views? Thank you in advance
Look into using Robot's getPixelColor method: ``` color = robot.getPixelColor(coord.x, coord.y); ``` e.g., ``` import java.awt.AWTException; import java.awt.Color; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Robot; public class PixelColor { private static final long SLEEP_DELAY = 400L; public static void main(String[] args) { Point coord; Robot robot = null; try { robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); System.exit(-1); } Color color = null; while (true) { coord = MouseInfo.getPointerInfo().getLocation(); color = robot.getPixelColor(coord.x, coord.y); System.out.println(color); try { Thread.sleep(SLEEP_DELAY); } catch (InterruptedException e) {} } } } ```
To get the pixel color where the mouse pointer is, you have to get the mouse position in every iteration of the loop, and then use the method `getPixelColor`of robot. ``` while(true) { pointer = MouseInfo.getPointerInfo(); coord = pointer.getLocation(); System.out.print(coord.x + " " + coord.y); System.out.println(" color: " + robot.getPixelColor(coord.x, coord.y).getRed() + ", " + robot.getPixelColor(coord.x, coord.y).getGreen() + ", " + robot.getPixelColor(coord.x, coord.y).getBlue()); } ```
There must be something simple I am missing. I'm trying to get the index of the element but keep getting -1. HTML: ``` <div id="rating_boxes"> <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> <img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /> </div> ``` jQuery: ``` $("img.ratingbox").hover(function() { var index = $(this).parent().index(this); // have also tried $("#rating_boxes").index(this); // and $("#rating_boxes").index($(this)); // and $(this).parent().index($(this)); alert(index); $(this).attr('src', '/img/ratingbox-selected.gif'); }, function() { $(this).attr('src', '/img/ratingbox.gif'); }); ```
`index()` returns the index of the given element with a list of elements, not within a parent element. To find the index of the clicked image, you need to find all the images, not the *parent* of all the images. You want something like this: ``` // Find all the images in our parent, and then find our index with that set of images var index = $(this).parent().find("img").index(this); ``` You're also using the id selector instead of the class selector in your 2nd example. Instead of ``` $("#rating_boxes").index($(this)); // your way - select by ID ``` You want ``` $(".rating_boxes").index(this); // select by class ```
If you want to know the position of the rating box, a more robust way is to use: ``` var index = $(this).prevAll('img').size(); ``` I.e., calculate the number of img elements before this element. The index method requires you to first select the parent element, then all img elements inside. This is a tad faster.
Is it correct to write my classes like this? In question is the method `getPrice()` in the `Item` class. Every Item needs to have a `getPrice()`. But I can't actually return something. So I fire the `this.getPrice()` with gets me the Price of the `ProductItem`. Is there a more solid / better designed solution? ``` class Item { String description; public Item(String description) { this.description = description; } double getPrice(){return this.getPrice();} //TODO Correct like this? } class ProductItem extends Item { int amount; double pricePerUnit; public ProductItem(String description, int amount, double pricePerUnit) { super(description); this.amount = amount; this.pricePerUnit = pricePerUnit; } @Override double getPrice(){ return amount * pricePerUnit; } } ```
It sounds like `Item` should be an abstract class then, with `getPrice()` being an abstract method: ``` public abstract class Item { private final String description; public Item(String description) { this.description = description; } public abstract double getPrice(); public String getDescription() { return description; } } ``` That means you won't be able to write ``` Item item = new Item("foo"); // Invalid, because Item is abstract ``` But you can write: ``` Item item = new ProductItem("foo", 10, 2.0); double p = item.getPrice(); // 20.0 ``` Every concrete (non-abstract) subclass you declare will have to override `getPrice()` and provide an implementation. See the [abstract classes and methods section of the Java tutorial](https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) for more details.
`double getPrice(){return this.getPrice();}` is basically an infinite loop. You should set that price first. ``` class Item { String description; double price; public Item(String description) { this.description = description; } public void setPrice(double price) { this.price = price; } double getPrice(){return this.price;} } ```
I am trying to change the "show more" text depending on the state. This isn't working: ``` <div id="description"> text goes here </div> <div id="more-less-container"> <a href="#" id="more-less">expand / collapse</a> </div> <script> var open = false; $('#more-less').click(function() { if (open) { $('#description').animate({height:'10em'}); $('#more-less').innerHTML ='show less'; } else { $('#description').animate({height:'100%'}); $('#more-less').innerHTML ='show more'; } open = !open; }); </script> ```
Use `$('#more-less').text('show more');` instead of innerHTML. jQuery wraps DOM Elements into jQuery objects, if you would want to use the `innerHTML` property, you could use the `.html()` function instead - but `.text()` is better as it will html-escape the content. The alternative, to really access `innerHTML` property, is to get the DOM Element out of the jQuery object, as such: `$('#more-less')[0].innerHTML = 'show more';`.
innerHTML is a DOM function, for jQuery use .html() since you're manipulating a jQuery object ``` $('#more-less').html('show less'); ```
I used to think those are random events but someone over at [physics.stackexchange.com](https://physics.stackexchange.com/a/77002/29481) insists that randomness means something else so I am at a loss here. Can someone help me out? What do you call an event that happens without a cause?
Well, there is always the word **causeless**: so you could simply say a **causeless event**. A rough synonym is **fortuitous**. You could potentially say a **random event** or **chance event**. The commentators on the physics forum are correct: as a scientific term, that isn't the technical meaning of **random**. But unless you're intending to use it as a technical term, so what? -- there are plenty of words that have a different everyday meaning to their technical meaning.
Depending on context also consider [***self-generated***](http://dictionary.reference.com/browse/self-generated?s=t) > > ***self-generated*** adjective > 1. happening or arising without apparent external cause; "spontaneous laughter"; "spontaneous combustion"; "a spontaneous abortion" [syn: spontaneous] [ant: induced] > 2. originating from the self > > > Another apt word is ***unengendered*** from [***engender***](http://www.etymonline.com/index.php?allowed_in_frame=0&search=engender&searchmode=none) > > *etymology* engender (v.) Look up engender at Dictionary.com > early 14c., "beget, procreate," from Old French engendrer (12c.) "engender, beget, bear; cause, bring about," from Latin ingenerare "to implant, engender, produce," from in- "in" (see in- (2)) + generare "beget, create" (see generation). Meaning "cause, produce" is mid-14c. Related: Engendered; engendering. > > > Other alternatives along similar etymological lines are ***unbegotten*** ***eternal*** giving the sense of having no beginning or cause (self-existent). > > en·gen·der verb \in-ˈjen-dər, en-\ > : to be the source or cause of (something) > > >
This is probably a really simple question however Google isn't my friend today. I have something like this but it says call to undefined function ```php <?php class myClass{ function doSomething($str){ //Something is done here } function doAnother($str){ return doSomething($str); } } ?> ```
Try the following: ``` return $this->doSomething($str); ```
Try: ``` return $this->doSomething($str); ``` Have a look at this as well: <http://php.net/manual/en/language.oop5.php>
I have an UITextView in my iPhone app which is editable. New button is created inside the UITextView whenever user select a specific function. As the button is always placed on the left side in the text view, I need to position the cursor on the right side of the button so that user can see what they are typing. I can't seem to find a documented (or undocumented) method to set location of the cursor. Does anybody have any ideas or has anybody else achieved anything similar?
Try something like this: ``` dispatch_async(dispatch_get_main_queue(), ^{ inView.selectedRange = NSMakeRange(3, 0); }); ``` This will cause selectedRange to be executed on the main thread at the beginning of the next runloop.
change `selectedRange` of your textView. for example to place cursor at position 3: `[textView setSelectedRange:NSMakeRange(3, 0)];` In your case, added some spaces on the textView contents might helps. and observer `textview 's textDidChanged event` to prevent these space will be deleted by user.
I am trying to implement searching in my Meteor app. I don't exactly understand how it ties together. At this point, I have this following code: html: ``` <form class="navbar-search pull-left"> <input type="text" class="search-query" placeholder="Search"> </form> ``` js: ``` Template.menubar.events({ 'keyup input.search-query': function (evt) { console.log("Keyup value: " + evt.which); if (evt.which === 13) { console.log("Got an Enter keyup"); Session.set("searchQuery", "justATestVar"); } } }); ``` I can see the values of keyup as I press different keys into the search box, so I know the event is being hit. Capturing the "enter" keyup also works, but pressing enter causes the enter site to reload and when I do: ``` Session.get("searchQuery") ``` it returns undefined. I don't know if I'm handling this properly. Essentially, I just want to get the value from the search box and then use that value for making a search on my collection. Any help would be appreciated! Thank you.
What is probably happening is your form is being submitted when you hit enter. Try an `preventDefault()`. Probably something like this would work: ``` Template.menubar.events({ 'keyup input.search-query': function (evt) { console.log("Keyup value: " + evt.which); if (evt.which === 13) { console.log("Got an Enter keyup"); Session.set("searchQuery", "justATestVar"); } }, 'submit form': function (evt) { evt.preventDefault(); } ... ``` You could also try adding `evt.preventDefault();` in your keyup but I think it's the form submission that's doing it.
In case anyone got here trying to implement the search function as well, I recommend the following: ``` meteor add matteodem:easy-search ``` On client and server: ``` Players = new Meteor.Collection('players'); // name is the field of the documents to search over Players.initEasySearch('name'); ``` On the client, make a `template.html`: ``` <template name="searchBox"> {{> esInput index="players" placeholder="Search..." }} <ul> {{#esEach index="players"}} <li>Name of the player: {{name}}</li> {{/esEach}} </ul> </template> ``` [Reference](https://github.com/matteodem/meteor-easy-search)
``` var i = -1; $('.rightBtn a').click(function(){ --i; // this part works.. if(i == -z){ $(".homeSlider").css("margin-left", 0); $('.homeSlider').animate({ marginLeft: '-='+$(window).width() }, function(){ var i = -1; // this is where its not working alert(i); // alerts it correct at -1 return i; // this doesn't return it? }); return i; } else { $('.homeSlider').animate({ marginLeft: '-='+$(window).width() }); return i; } return i; //} }); ``` Am I just forgetting something? Also, say for the sake of the argument var z = 5
You're returning `i` without there being anything to receive it. Set the value, don't return it. Basically you're passing `i` back to the HTML. HTML is stupid. It doesn't know what to do with it.
To summarize, there are lots of things wrong here: 1. The `.animate()` function is asynchronous so it returns BEFORE the completion function runs so the completion function has no effect on the return value from your click function. 2. The return value from the click function is used to decide whether click propagation should continue or not and it should be a Boolean. 3. The local variable inside your completion function is overriding access to your global. Usually, you don't want a local and global variable with the same name. 4. The return value from the completion function is not used for anything so returning your local copy of `i` there isn't doing anything. I don't think you understand how asynchronous functions work. When you call animate, it starts the animation and returns immediately. The value of i will not have been changed yet by the completion callback. Thus, when it returns, it will return the value of the global `i`. Sometime later the completion function for the animation will get called. In that function you are declaring a new local variable named, `i`, settings it's value and return it. But nothing happens with the return value from the completion function so that does nothing. So, you animation completion function has no effect on the value of the global variable `i`. Then, returning `i` from the click function probably isn't doing what you want to do there either. The return value of the click function should be a Boolean and it's value determines whether click propagation continues or not. You return(false) to stop click propagation. So returning the value of `i` from the click function is also having no effect on the global variable. Lastly, it's usually an undesirable practice to have a global variable and a local variable with the same name. It will be easy to confuse the two and not realize which is being affected by any given piece of code. The local variable supercedes so when you declare a local variable with `var i;` and then assign to it with `i = -1;`, you are assigning only to the local variable and not affected the global variable.
My application's main Activity is a TabActivity and it contains an OptionsMenu. I define some other Activities (which go into a tab) and I would like to define a menu in each of these activities and have its menu merged with the main one. Is it possible?
Yes, this is possible. Basically you just inflate multiple xml files into the same options menu. Items are added to the menu in order of inflation. Just overwrite `onCreateOptionsMenu(Menu menu)` for your `TabActivity`, inflating the xml file containing the main options. Then overwrite it for each of your inner tab activities, inflating the tab-specific options. Just write them as you usually would: ``` @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.options, menu); return super.onCreateOptionsMenu(menu); } ``` The menu 'belongs' to the currently active inner tab activity, but to populate it, `onCreateOptionsMenu` is automatically called on the parent activities too (by `super`). However, strangely, `onMenuItemSelected(int featureId, MenuItem item)` does not do the same. To handle item selection, the inner tab activities still have to explicitly call the corresponding method on the parent activity (after you determine that the selected option is not tab-specific): ``` return super.onMenuItemSelected(featureId, item) || getParent().onMenuItemSelected(featureId, item); ```
Are you creating the menus dynamically or in separate XMLs? if Dynamically you can just set it up as ``` public void createMenu() { //Main Menu here switch(tab) { case '1': //add tab 1 menu break; case '2': //add tab 2 menu break; } } ```
On my laptop, turning on autorepeat (`xset r on`) does not work. When checking the output of `xev`, it seems that the reason why autorepeat fails is because another key is being pressed intermittently (although I am not pressing anything), which cancels autorepeating the currently held down key. When no keys are being pressed, the following events are recorded repeating consistently: ``` KeyPress event, serial 33, synthetic NO, window 0x1200001, root 0x123, subw 0x0, time 1652400, (-509,794), root:(455,814), state 0x0, keycode 221 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XmbLookupString gives 0 bytes: XFilterEvent returns: False KeyRelease event, serial 33, synthetic NO, window 0x1200001, root 0x123, subw 0x0, time 1652400, (-509,794), root:(455,814), state 0x0, keycode 221 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XFilterEvent returns: False ``` It seems that a key with keycode 221 is being pressed, even when it is not. Thus, is it possible to completely disable a keycode such that xorg does not recieve the keypress signal from that keycode at all? Or, is it possible to make keys autorepeat when held down, regardless of whether another key is pressed? --- Update: After running `sudo evtest`, it appears that when the hidden output is coming from ``` /dev/input/event11 PEAQ WMI hotkeys ``` No other input device seems to send events when nothing is pressed. Autorepeat works when checking keyboard events in evtest. --- The full output of `xev` running for a couple seconds when nothing is pressed: ``` Outer window is 0x1200001, inner window is 0x1200002 PropertyNotify event, serial 8, synthetic NO, window 0x1200001, atom 0x27 (WM_NAME), time 1651733, state PropertyNewValue PropertyNotify event, serial 9, synthetic NO, window 0x1200001, atom 0x22 (WM_COMMAND), time 1651733, state PropertyNewValue PropertyNotify event, serial 10, synthetic NO, window 0x1200001, atom 0x28 (WM_NORMAL_HINTS), time 1651733, state PropertyNewValue CreateNotify event, serial 11, synthetic NO, window 0x1200001, parent 0x1200001, window 0x1200002, (10,10), width 50, height 50 border_width 4, override NO PropertyNotify event, serial 14, synthetic NO, window 0x1200001, atom 0x15c (WM_PROTOCOLS), time 1651734, state PropertyNewValue MapNotify event, serial 15, synthetic NO, window 0x1200001, event 0x1200001, window 0x1200002, override NO ReparentNotify event, serial 28, synthetic NO, window 0x1200001, event 0x1200001, window 0x1200001, parent 0x4000d5, (0,0), override NO ConfigureNotify event, serial 28, synthetic NO, window 0x1200001, event 0x1200001, window 0x1200001, (2,0), width 952, height 1033, border_width 2, above 0x0, override NO PropertyNotify event, serial 28, synthetic NO, window 0x1200001, atom 0x15e (WM_STATE), time 1651735, state PropertyNewValue MapNotify event, serial 28, synthetic NO, window 0x1200001, event 0x1200001, window 0x1200001, override NO VisibilityNotify event, serial 28, synthetic NO, window 0x1200001, state VisibilityUnobscured Expose event, serial 28, synthetic NO, window 0x1200001, (0,0), width 952, height 10, count 3 Expose event, serial 28, synthetic NO, window 0x1200001, (0,10), width 10, height 58, count 2 Expose event, serial 28, synthetic NO, window 0x1200001, (68,10), width 884, height 58, count 1 Expose event, serial 28, synthetic NO, window 0x1200001, (0,68), width 952, height 965, count 0 ConfigureNotify event, serial 28, synthetic YES, window 0x1200001, event 0x1200001, window 0x1200001, (962,18), width 952, height 1033, border_width 2, above 0x0, override NO FocusIn event, serial 28, synthetic NO, window 0x1200001, mode NotifyNormal, detail NotifyNonlinear KeymapNotify event, serial 28, synthetic NO, window 0x0, keys: 4294967236 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 PropertyNotify event, serial 28, synthetic NO, window 0x1200001, atom 0x14f (_NET_WM_DESKTOP), time 1651736, state PropertyNewValue KeyRelease event, serial 30, synthetic NO, window 0x1200001, root 0x123, subw 0x0, time 1651775, (-509,794), root:(455,814), state 0x0, keycode 36 (keysym 0xff0d, Return), same_screen YES, XLookupString gives 1 bytes: (0d) " " XFilterEvent returns: False MappingNotify event, serial 33, synthetic NO, window 0x0, request MappingKeyboard, first_keycode 8, count 248 KeyPress event, serial 33, synthetic NO, window 0x1200001, root 0x123, subw 0x0, time 1652400, (-509,794), root:(455,814), state 0x0, keycode 221 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XmbLookupString gives 0 bytes: XFilterEvent returns: False KeyRelease event, serial 33, synthetic NO, window 0x1200001, root 0x123, subw 0x0, time 1652400, (-509,794), root:(455,814), state 0x0, keycode 221 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XFilterEvent returns: False KeyPress event, serial 34, synthetic NO, window 0x1200001, root 0x123, subw 0x0, time 1653200, (-509,794), root:(455,814), state 0x0, keycode 221 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XmbLookupString gives 0 bytes: XFilterEvent returns: False KeyRelease event, serial 34, synthetic NO, window 0x1200001, root 0x123, subw 0x0, time 1653200, (-509,794), root:(455,814), state 0x0, keycode 221 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XFilterEvent returns: False KeyPress event, serial 34, synthetic NO, window 0x1200001, root 0x123, subw 0x0, time 1654000, (-509,794), root:(455,814), state 0x0, keycode 221 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XmbLookupString gives 0 bytes: XFilterEvent returns: False KeyRelease event, serial 34, synthetic NO, window 0x1200001, root 0x123, subw 0x0, time 1654000, (-509,794), root:(455,814), state 0x0, keycode 221 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XFilterEvent returns: False MappingNotify event, serial 34, synthetic NO, window 0x0, request MappingKeyboard, first_keycode 8, count 248 KeyPress event, serial 34, synthetic NO, window 0x1200001, root 0x123, subw 0x0, time 1654760, (-509,794), root:(455,814), state 0x0, keycode 133 (keysym 0xffeb, Super_L), same_screen YES, XLookupString gives 0 bytes: XmbLookupString gives 0 bytes: XFilterEvent returns: False MappingNotify event, serial 35, synthetic NO, window 0x0, request MappingKeyboard, first_keycode 8, count 248 KeyPress event, serial 35, synthetic NO, window 0x1200001, root 0x123, subw 0x0, time 1654800, (-509,794), root:(455,814), state 0x40, keycode 221 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XmbLookupString gives 0 bytes: XFilterEvent returns: False KeyRelease event, serial 35, synthetic NO, window 0x1200001, root 0x123, subw 0x0, time 1654800, (-509,794), root:(455,814), state 0x40, keycode 221 (keysym 0x0, NoSymbol), same_screen YES, XLookupString gives 0 bytes: XFilterEvent returns: False MappingNotify event, serial 36, synthetic NO, window 0x0, request MappingKeyboard, first_keycode 8, count 248 FocusOut event, serial 36, synthetic NO, window 0x1200001, mode NotifyGrab, detail NotifyAncestor ClientMessage event, serial 37, synthetic YES, window 0x1200001, message_type 0x15c (WM_PROTOCOLS), format 32, message 0x15d (WM_DELETE_WINDOW) ```
It turns out that disabling PEAQ WMI hotkeys fixes it. I disabled PEAQ WMI hotkeys through first checking `xinput list`, to find the id: ``` user@hostname.com:~$ xinput list ⎡ Virtual core pointer id=2 [master pointer (3)] ⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer (2)] ⎜ ↳ Dell Dell KM632 Wireless Keyboard and Mouse id=11 [slave pointer (2)] ⎜ ↳ Dell Dell KM632 Wireless Keyboard and Mouse id=12 [slave pointer (2)] ⎜ ↳ SynPS/2 Synaptics TouchPad id=16 [slave pointer (2)] ⎣ Virtual core keyboard id=3 [master keyboard (2)] ↳ Virtual core XTEST keyboard id=5 [slave keyboard (3)] ↳ Power Button id=6 [slave keyboard (3)] ↳ Video Bus id=7 [slave keyboard (3)] ↳ Video Bus id=8 [slave keyboard (3)] ↳ Sleep Button id=9 [slave keyboard (3)] ↳ Dell Dell KM632 Wireless Keyboard and Mouse id=10 [slave keyboard (3)] ↳ Lenovo EasyCamera: Lenovo EasyC id=13 [slave keyboard (3)] ↳ Ideapad extra buttons id=14 [slave keyboard (3)] ↳ AT Translated Set 2 keyboard id=15 [slave keyboard (3)] ↳ Dell Dell KM632 Wireless Keyboard and Mouse id=18 [slave keyboard (3)] ↳ PEAQ WMI hotkeys id=17 [slave keyboard (3)] ``` In this case, the id is 17. Then, in the .xinitrc, I added `xinput --disable 17`, or the id that is causing trouble, which fixes the problem.
I have the same issue on elementaryOS after latest kernel update. I posted about it [here](https://unix.stackexchange.com/questions/416327/system-keeps-registering-key-presses-i-do-not-press). Using one of the answers, `sudo modprobe -r peaq_wmi`, solved the problem for me. EDIT: Adding `xinput --disable 17` into .xinitr did **not** solve the issue permanently for me, so I run the command above after every boot. I have Lenovo Yoga 500-14IHW on elementaryOS. Also, this bug is not Arch linux related, so please mark it as such, so more people would find the solution for this issue.
This is my JavaScript code to find elements with desired `.text()` but it's not working. ``` var divCollection = getElementByClass("titletrack"); for (var i=0; i<divCollection.length; i++) { if(divCollection[i].text() == title) { findMeText = divCollection[i].text(); alert(findMeText); } } ```
[WORKING FIDDLE](http://jsfiddle.net/pgPgR/1/) Hope this is what you had in mind. This may look complicated and im sure there is a simpler way of doing it. But it works. ``` var divCollection = document.getElementsByClassName("titletrack"); for (var i = 0; i < divCollection[0].childElementCount; i++) { if (divCollection[0].children[i].textContent == "Element 1") { findMeText = divCollection[0].children[i].textContent; alert(findMeText); } } ``` Now you can compare any element of the divCollection with any string that you want. In the fiddle i have used the string "Element 1" to demonstrate the working of the JavaScript.
Try this: ``` var divCollection = document.getElementsByClassName('titletrack'); ``` That is, getElementsByClassName instead of getElementByClass. Something like this would finish the deal: ``` var str = ''; var strSearchingFor = 'foo'; for(var i=0; i < divCollection .length; i++) { str+= " " + divCollection[i].value; if(str == strSearchingFor) { alert("found"); } } ```
I have this following sentence:   > > 横線――HPバーの名で呼ばれる青いそれは、俺の生命の残量を可視化したものだ。 > > > There are a few questions I came up with about this sentence: 1. The first part of the sentence is: `横線――HPバーの名で呼ばれる青いそれ`, my question is how can this sentence be parsed? How does the long `――` change the meaning/parsing of the sentence? 2. At the end of the sentence, it is written: `可視化したもの`. Why is `可視化した` used in past form, while according to the context I'd expect a present-form? Is this perhaps a grammar subject I just don't know yet? Any help is appreciated!
To add to @dainichi's answer, `横線` is probably better translated as "horizontal line", not "side line". Also, the `ーー` could probably be replaced easily by `すなわち` or `言い換えて`. "That horizontal line, that is/in other words, that blue thing called the 'HP Bar', ..."
The horizontal line -the blue one called HP bar- visualizes my remaining life.
I have done a series of logistic regressions for various outcomes, and have been using the `rms` package to calculate Nagelkerke R^2 without any problems until now... When I try and use it in a regression with a binary outcome for obesity (=1) or 'normal' weight (=0), I get a message saying there is an error in my formula and it's unable to fit the model using `lrm.fit`. I have tried coding my outcome as numeric and as a factor but get the same error. I have also tried using a subset of the data, excluding cases that are neither obese or 'normal' weight. That doesn't work either. I have pasted my formula below. (I can't include data as I don't have permission to share it.) I have also pasted the regression output I get using the `glm` function. What am I doing wrong? I was sure there would be a solution for this already posted, but can't find one on Stack Overflow or other forums. (My supervisor has asked me to include pseudo R^2 in my results. I am also including average marginal effects.) Thanks in advance for any help! Code ==== ``` require(rms) logit.obnorm.base <- lrm(obnorm13 ~ wgt9 + gender + birthweight + breastfed + pcgweight + smoked + pcgeducation + income + welfare, data = gui) print(logit.obnorm.base) ``` Error message ============= ``` Error in lrm(obnorm13 ~ wgt9 + gender + birthweight + breastfed + pcgweight + : Unable to fit model using “lrm.fit” ``` Regression output when using `glm` for the regression ===================================================== ``` glm(formula = obnorm13 ~ wgt9 + gender + birthweight + breastfed + pcgweight + smoked + pcgeducation + income + welfare, family = binomial(link = "logit"), data = gui, weights = bdwg01, na.action = na.omit) Deviance Residuals: Min 1Q Median 3Q Max -3.4402 -0.1509 -0.0876 -0.0618 6.2779 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) -5.73687 0.73321 -7.824 5.10e-15 *** wgt92 3.25940 0.20237 16.106 < 2e-16 *** wgt93 6.38153 0.28246 22.593 < 2e-16 *** gender 0.26701 0.17444 1.531 0.125854 birthweight 0.14304 0.15234 0.939 0.347751 breastfed 0.24493 0.19173 1.277 0.201430 pcgweight2 0.35537 0.22073 1.610 0.107401 pcgweight3 1.11191 0.21671 5.131 2.89e-07 *** smoked 0.50183 0.19956 2.515 0.011913 * pcgeducation2 -0.71452 0.21294 -3.356 0.000792 *** pcgeducation3 -0.81295 0.27853 -2.919 0.003515 ** pcgeducation4 -0.88217 0.32623 -2.704 0.006848 ** income -0.01348 0.07976 -0.169 0.865744 welfare 0.11014 0.06298 1.749 0.080290 . --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for binomial family taken to be 1) Null deviance: 2410.1 on 4758 degrees of freedom Residual deviance: 1037.4 on 4745 degrees of freedom (2536 observations deleted due to missingness) AIC: 1048.4 Number of Fisher Scoring iterations: 7 ``` Output from `dput(head(mydata))` ================================ ``` > dput(head(gui)) structure(list(zid01 = c(1000, 2000, 3000, 4000, 5000, 6000), bdwg01 = c(0.222555072843037, 1.95115048656779, 1.08399948558217, 0.697544449190721, 0.910021907765603, 0.278315557267728), gender = c(0, 0, 0, 0, 0, 0), wgt9 = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor"), apcb01 = c(3.4, 3.1, 3.4, 3.3, 3.6, 2.8), smoked = c(1, 1, 0, 0, 1, 1), breastfed = c(0, 0, 0, 0, 1, 0), pcgweight = structure(c(2L, 1L, 1L, 1L, 2L, 2L), .Label = c("1", "2", "3"), class = "factor"), pcgeducation = structure(c(4L, 1L, 4L, 4L, 4L, 2L), .Label = c("1", "2", "3", "4"), class = "factor"), welfare = c(2, 7, 2, 3, 2, 3), adsd59b = c(5, 2, 4, 3, 5, 2), aded08a = c(51, 31, 35, 44, 52, 30), aded08b = c(11, 10, 4, 10, 11, 8), aded08c = c(15, 7, 8, 11, 14, 8), aded08d = c(10, 7, 7, 8, 8, 7), aded08e = c(12, 6, 9, 11, 13, 5), aded08f = c(11, 5, 9, 8, 10, 5), aded08g = c(8, 4, 7, 8, 10, 6), aded10a = c(0, 8, 4, 2, 1, 2), aded10b = c(1, 4, 1, 1, 0, 0), aded10c = c(4, 10, 4, 3, 2, 4), aded10d = c(1, 3, 1, 0, 2, 0), aded10e = c(9, 7, 9, 10, 5, 9), aded10f = c(6, 25, 10, 6, 5, 6), aded11a = c(1.8, 3, 1.2, 1.2, 2.8, 2), aded11b = c(1.4, 5, 1.2, 1.4, 1.2, 1.8), aded11c = c(4.8, 5, 4.8, 5, 5, 4.6), aded11d = c(3.8, 3.4, 4, 4.2, 4.2, 3.6 ), obese13 = c(0, 0, 0, 0, 0, 0), obnorm13 = c(0, 0, 0, 0, 0, 0), xswgt13 = c(0, 0, 0, 0, 0, 0), up = c("0", "0", "0", "0", "0", "0"), down = c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_), obese9 = c(0, 0, 0, 0, 0, 0), obnorm9 = c("0", "0", "0", "0", "0", "0"), xswgt9 = c(0, 0, 0, 0, 0, 0), wgt9.1 = c("1", "1", "1", "1", "1", "1"), income = c(5, 2, 4, 3, 5, 2), birthweight = c(3.4, 3.1, 3.4, 3.3, 3.6, 2.8), PHtotal = c(51, 31, 35, 44, 52, 30), PHbehaviour = c(11, 10, 4, 10, 11, 8), PHintel_school = c(15, 7, 8, 11, 14, 8), PHphys_app = c(10, 7, 7, 8, 8, 7), PHfreedom_anx = c(12, 6, 9, 11, 13, 5), PHpopularity = c(11, 5, 9, 8, 10, 5), PHhappiness = c(8, 4, 7, 8, 10, 6), SDQEmotional = c(0, 8, 4, 2, 1, 2), SDQConduct = c(1, 4, 1, 1, 0, 0), SDQHyperactivity = c(4, 10, 4, 3, 2, 4), SDQPeer_Rel = c(1, 3, 1, 0, 2, 0), SDQProsocial = c(9, 7, 9, 10, 5, 9), SDQTotalDiff = c(6, 25, 10, 6, 5, 6), EASShyness = c(1.8, 3, 1.2, 1.2, 2.8, 2), EASEmotionality = c(1.4, 5, 1.2, 1.4, 1.2, 1.8), EASActivity = c(4.8, 5, 4.8, 5, 5, 4.6), EASSociability = c(3.8, 3.4, 4, 4.2, 4.2, 3.6), factor.wgt9 = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor"), factor.pcged = structure(c(4L, 1L, 4L, 4L, 4L, 2L), .Label = c("1", "2", "3", "4"), class = "factor"), factor.pcgweight = structure(c(2L, 1L, 1L, 1L, 2L, 2L), .Label = c("1", "2", "3"), class = "factor"), orig.wgt9 = c("1", "1", "1", "1", "1", "1"), orig.pcgweight = c(2, 1, 1, 1, 2, 2), orig.pcgeducation = c(4, 1, 4, 4, 4, 2), PHintelschool = c(15, 7, 8, 11, 14, 8)), .Names = c("zid01", "bdwg01", "gender", "wgt9", "apcb01", "smoked", "breastfed", "pcgweight", "pcgeducation", "welfare", "adsd59b", "aded08a", "aded08b", "aded08c", "aded08d", "aded08e", "aded08f", "aded08g", "aded10a", "aded10b", "aded10c", "aded10d", "aded10e", "aded10f", "aded11a", "aded11b", "aded11c", "aded11d", "obese13", "obnorm13", "xswgt13", "up", "down", "obese9", "obnorm9", "xswgt9", "wgt9.1", "income", "birthweight", "PHtotal", "PHbehaviour", "PHintel_school", "PHphys_app", "PHfreedom_anx", "PHpopularity", "PHhappiness", "SDQEmotional", "SDQConduct", "SDQHyperactivity", "SDQPeer_Rel", "SDQProsocial", "SDQTotalDiff", "EASShyness", "EASEmotionality", "EASActivity", "EASSociability", "factor.wgt9", "factor.pcged", "factor.pcgweight", "orig.wgt9", "orig.pcgweight", "orig.pcgeducation", "PHintelschool"), row.names = c(NA, 6L), class = "data.frame") ```
I encountered similar problems and I found a solution [here](http://r.789695.n4.nabble.com/Help-understanding-why-glm-and-lrm-fit-runs-with-my-data-but-lrm-does-not-td4745387.html). The problem could be that the MLE does not converge in a number of steps. I added `maxit=1000` in the arguments and it worked.
Solution ======== The alternative method of calculating R^2 suggested by tmfmnk worked without any problems. I have pasted it here in case it helps others. Thank you everyone for your replies. ``` # Install the DescTools package and open the library install.packages("DescTools") library(DescTools) # Run the baseline logistic regression for obese / no excess weight at 13, including weights summary(logit.obnorm.base <- glm(obnorm13 ~ wgt9 + gender + birthweight + breastfed + pcgweight + smoked + pcgeducation + income + welfare, data = gui, weights = bdwg01, family = binomial(link = "logit"), na.action=na.omit)) # Calculate Nagelkerke R^2 PseudoR2(logit.obnorm.base, which = "Nagelkerke") >Nagelkerke 0.7309776 ```
In the following code, I want to set the opacity only for the background color of the `li` (not the text). However, it is important NOT to use the `rgba` for the background. I'm trying following, but it sets the opacity for the link text as well. **HTML:** ``` <ul> <li><a href="#">Hello World</a></li> </ul> ``` **CSS:** ``` body{ background: red; } ul{ margin: 100px; } li{ padding: 10px; background: #000000; opacity: 0.1; } a{ color: #fff; font-weight: 700; opacity: 1; } ``` **JSFiddle:** <http://jsfiddle.net/2uJhL/>
Old question, but new answer! :) Fortunately, the new versions of Chrome and Firefox support **8 digit colors**. That's really cool, especially when you're developing and testing software. For example: ``` background-color: #ff0000; (Red) ``` If you want a opacity of 0.5, you can do this: ``` background-color: #ff00007f (The 7F is half of FF) ``` So, from now on you won't need to use the `rgba()` if you don't want or have the entire div fade away - because of the `opacity: 0.x` - when you only want the background color a little bit transparent. **But remember that not all browsers support that. So, please test the snippet below on Chrome or Firefox, ok?** Isn't that cool??? ```html <div style="background-color: #ff00003f;">better than [opacity: 0.25]</div> <div style="background-color: #ff00007f;">better than [opacity: 0.50]</div> <div style="background-color: #ff0000bf;">better than [opacity: 0.75]</div> <div style="background-color: #ff0000ff;">better than [opacity: 1.00]</div> ``` Source: <https://css-tricks.com/8-digit-hex-codes/>
The opacity is applied at the content and all children. You can't set a different opacity for the children. However if you don't want to use rgba you can use a png with opacity that you want. And setting a png to your `li` in the background is the best solution in this case
What is the right way to use a class defined in one file and extend it another, in node.js? Currently I have: ``` 'use strict' class BasePageHandler { constructor(app, settings, context) { } } return module.exports; ``` In the 'child' class file I have: ``` 'use strict' var BasePageHandler = require ('./../BasePageHandler.js'); class FrontpagePageHandler extends BasePageHandler { constructor(app, settings, context) { super(app, settings, context); this.settings = settings; this.context = context; } } ``` This fails with the following error: ``` TypeError: Class extends value #<Object> is not a function or null ``` Note, if I have the BasePageHandler in the same file then it works, so it is really when the class is in another file I have an issue. Currently using node 4.4.0.
You need to correctly export your class in`BasePageHandler.js` file: ``` module.exports = BasePageHandler; ```
The accepted answer is technically fine, but really if you're using ES6 then you should go all in and use [ES6 export/import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export). ``` /*jshint esversion: 6 */ class BasePageHandler { constructor(app, settings, context) { } } export default BasePageHandler; ``` and then: ``` /*jshint esversion: 6 */ import BasePageHandler from './../BasePageHandler.js'; class FrontpagePageHandler extends BasePageHandler { constructor(app, settings, context) { super(app, settings, context); this.settings = settings; this.context = context; } } ```
``` <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class VerifyLogin extends CI_Controller { public function __construct() { parent::__construct(); //Model for fetching users in database $this->load->model('user', '', TRUE); } public function index() { //Load method to help verify form credentials $this->load->library('form_validation'); //----------------------------------------------- //Verify Existance of values in login form fields //----------------------------------------------- //Validate existance of username field value $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); //Validate existance of password field value, and if exists then call 'check_database' func $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database'); //If the form validation is false (i.e. Missing form fields) if($this->form_validation->run() == FALSE){ //Redirect back to login page $this->load->view('general-Login'); } //Login Success, goto main-page else{ //Go to main page redirect('Main', 'refresh'); } } function check_database($password) { //Field validation succeeded. Validate against database $username = $this->input->post('username'); //Check the username and password against database $result = $this->user->login($username, $password); //If there is a result if($result){ //will be used for session information $sess_array = array(); foreach ($result as $row){ $sess_array= array( 'id' => $row->id, 'username' => $row->username ); //Session set as logged in $this->session->set_userdata('logged_in', $sess_array); } return true; } //No existance of user or, incorrect password else{ //Send Message of incorrect username or password $this->form_validation->set_message('check_database', 'Invalid Username or Password'); return false; } } } ``` So i have a verifylogin controller that handles the form data from my login page. Database access works great and everything works perfectly until i get to the redirect feature. I try to redirect with refresh and it just gives me a page that says "undefined". Now it will suddenly work when i remove the 'refresh' and just leave the controller name, but i'm trying to figure out why this 'refresh' won't work. I've disabled my `.htaccess` I've tried setting my `$config['uri_protocol']` to `REQUEST_URI`, `AUTO`, and `PATH_INFO` and had no luck. Also, this is my first submission online to anything like a forum so please....be gentle.
Try this one, ``` SELECT a.product_ID, COALESCE(b.user_id,0) `user_id` FROM products a LEFT JOIN liked_items b ON a.product_ID = b.product_ID ``` Sometimes `liked_items.user_id` can be possibly `NULL` so instead of displaying `NULL` in the result list, it can be changed using `COALESCE`. `COALESCE` is a function that can change `NULL` value into your *desired value*. [*Click For Demonstration*](http://sqlfiddle.com/#!2/7e79c/1) =============================================================
If you're using MS SQL Server you can use IsNull like so: ``` SELECT p.product_id, IsNull(li.user_id, 0) FROM products p LEFT JOIN liked_items li ON (p.product_id = li.product_id); ``` If not, Joao or John's answer will do just fine.
I am setting up SVN on a Red Hat Linux machine. My scenario is that I have two projects in the same directory: * `/var/www/svn/proj1` * `/var/www/svn/proj2` My subversion.conf has the following configurations: ``` <Location /svn/proj1> DAV svn SVNPath /var/www/svn/proj1 AuthzSVNAccessFile /etc/svn_proj1-acl-conf AuthType Basic AuthName "Subversion repos" AuthUserFile /etc/svn-auth-conf Require valid-user </Location> <Location /svn/proj2/> DAV svn SVNParentPath /var/www/svn/proj2 SVNListParentPath on AuthzSVNAccessFile /etc/svn_proj2-acl-conf AuthType Basic AuthName "Subversion repos" AuthUserFile /etc/svn-auth-conf Require valid-user </Location> ``` For project1 my URL <http://www.example.com/svn/proj1> works pretty good, but for project2 I need to add trailing slash in the end of URL, <http://www.example.com/svn/proj2/> or else it doesn't return with a user/password window. If I remove the trailing slash from the location directive, ``` <Location /svn/proj2> ``` then it starts giving a `403 Forbidden` error, no matter if I use a slash or not in the browser. I am using it with TortoiseSVN, but project2 isn't working at all. What should I look at in configurations?
Confused. Confused. Confused... But, I'm easily confused... You have two projects. The first one you use: ``` SVNPath /var/www/svn/proj1 ``` and the second you use: ``` SVNParentPath /var/www/svn/proj2 ``` Why is one `SVNPath` and the other `SVNParentPath`? There's a difference. You specify `SVNPath` when you refer to a particular repository. You use `SVNParentPath` when you refer to a directory that contains ***multiple*** repositories. So, exactly what is your setup? I have a feeling that they both should be `SVNPath`. By the way, I notice you have the same user list, but separate `AuthzSVNAccessFile` access files. Are you merely stopping people from committing, or are you preventing people from reading particular files and directories? Normal practice is to allow users to see all files, but to prevent commit access. In that case, you may want to do that outside of Apache httpd, using my [pre-commit hook](https://github.com/qazwart/SVN-Precommit-Kitchen-Sink-Hook). This allows you to do two things: * Turn off directory checking access which speeds up Subversion. * Change commit permissions without restarting Apache httpd. You can then configure both directories in a single configuration: ``` <Location /svn> DAV svn SVNParentPath /var/www/svn SVNListParentPath on AuthType Basic AuthName "Subversion repos" AuthUserFile /etc/svn-auth-conf SVNPathAuthz off Require valid-user </Location> ``` Of course, if you're using AuthzPath to prevent read access, you have to use the `AuthzSVNAccessFile` parameter. But, it makes things more complex, and it slows you down. I usually recommend against it unless users aren't suppose to be able to peek at each other repos (which is quite rare). And, one more thing... Do your users have LDAP or Windows Active Directory accounts? If so, you can use [that](http://httpd.apache.org/docs/2.2/mod/mod_authnz_ldap.html) to determine Subversion repository access: ``` LoadModule authnz_ldap_module modules/authnz_ldap.so <Location /svn> DAV svn SVNParentPath /var/www/svn SVNListParentPath on AuthType basic AuthName "Subversion Repository" AuthBasicProvider ldap AuthzLDAPAuthoritative off AuthLDAPURL "ldap://windomain.mycorp.com:3268/dc=mycorp,dc=com?sAMAccountName" NONE AuthLDAPBindDN "CN=svn_user,OU=Users,DC=mycorp,DC=com" AuthLDAPBindPassword "swordfish" Require ldap-group CN=developers,CN=Users,DC=mycorp,DC=com </Location> ``` This way, if a user has a Windows account (or is in your LDAP database), and that user is in the *developers* group, they automatically have access to your Subversion repositories (note the `SVNParentPath` for both repos and any future ones). This way, you're not constantly adding and subtracting users out of your SVN AUthorization file. Plus, you're not constantly retrieving forgotten passwords. Now, that's all your Windows administrator's responsibility. It's magic. I made your task their job. User doesn't have Subversion access? No longer your problem. More time to play Angry Birds. One more tiny thing: I have a feeling you don't want to place your repository under `/var/www` for the simple reason that might be your document root. If you're not careful, you might be granting direct access to your Subversion repository directory. You're better off putting them elsewhere and changing the `SVNParentPath`.
The `Location` and `SVNParentPath` directive should have the same trailing slash rule: either with or without. So it should be: ``` <Location /svn/proj2/> <--- Here trailing slash (or not) [..] SVNPath /var/www/svn/proj2/ <--- Here same like Location [...] </Location> ```
After looking Snowflake documentation, I found function called `array_intersection(array_1, array_2)` which will return common values between two array, but I need to display array with values which is not present in any one of the array. **Example 1:** Let's say I have following two arrays in my table ``` array_1 = ['a', 'b', 'c', 'd', 'e'] array_2 = ['a', 'f', 'c', 'g', 'e'] ``` My Query: ``` select array_intersection(array_1, array_2) from myTable ``` Current Output: ``` ['a', 'c', 'e'] ``` But I am expecting output as: ``` ['f', 'g'] ``` **Example 2:** Let's say I have following two arrays in my table ``` array_1 = ['u', 'v', 'w', 'x', 'y'] array_2 = ['u', 'v', 'i', 'x', 'k'] ``` My Query: ``` select array_intersection(array_1, array_2) from myTable ``` Current Output: ``` ['u', 'v', 'x'] ``` But I am expecting output as: ``` ['w', 'y', 'i', 'k'] ``` how can this be done in Snowflake? any suggestions?
I'm not sure you need a sequence like the other answer. This works pretty cleanly: ``` with myTable as ( select array_construct('a', 'b', 'c', 'd', 'e') as a1 ,array_construct('a', 'f', 'c', 'g', 'e') as a2 ) SELECT array_agg(coalesce(a1.value,a2.value)) WITHIN GROUP (ORDER BY coalesce(a1.value,a2.value)) as newarray FROM ( SELECT * FROM myTable, lateral flatten(input => a1) a1 ) a1 FULL OUTER JOIN ( SELECT * FROM myTable, lateral flatten(input => a2) a2 ) a2 ON a1.value::varchar = a2.value::varchar WHERE a1.value IS NULL OR a2.value IS NULL ; ```
Snowflake could achieve the desired effect with usage of SQL and array functions: * [ARRAY\_CAT](https://docs.snowflake.com/en/sql-reference/functions/array_cat.html) * [ARRAY\_EXCEPT](https://docs.snowflake.com/en/sql-reference/functions/array_except.html) Query: ``` SELECT arr1, arr2, ARRAY_EXCEPT(arr1, arr2), ARRAY_EXCEPT(arr2, arr1), ARRAY_CAT(ARRAY_EXCEPT(arr1, arr2),ARRAY_EXCEPT(arr2, arr1)) AS array_xor FROM mytable; ``` For sample data: ``` CREATE OR REPLACE TABLE mytable(arr1 ARRAY, arr2 ARRAY) AS SELECT ['a', 'b', 'c', 'd', 'e'], ['a', 'f', 'c', 'g', 'e'] UNION SELECT ['u', 'v', 'w', 'x', 'y'], ['u', 'v', 'i', 'x', 'k']; ``` Output: [![enter image description here](https://i.stack.imgur.com/RZ3XZ.png)](https://i.stack.imgur.com/RZ3XZ.png) --- Second way to achieve the same result is: ``` SELECT arr1, arr2, ARRAY_EXCEPT(ARRAY_DISTINCT(ARRAY_CAT(arr1, arr2)), ARRAY_INTERSECTION(arr1, arr2)) AS array_xor FROM mytable; ``` More at: [Symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) of sets A and B: ``` A ⊕ B = (A \ B) ⋃ (B \ A) or A ⊕ B = (A ⋃ B) \ (A ⋂ B) ```
I'm writing a version of the Unix `expand` utility that replaces tabs with spaces in a file. To do this, I'm reading in each character and testing if it is a tab character. If it is, it replaces the tab with the given amount of spaces, otherwise the character gets printed. My main method goes like ``` int main(int argc, char *argv[]){ FILE *fp; char *help1="-help"; char *help2= "--help"; //int spaces; //number of spaces to replace tabs fp= fopen(argv[1], "rw"); parse_file(fp, 4); fclose(fp); return 0; } ``` the parse\_file method goes like ``` void parse_file(FILE *fp, int spaces) { int i; //loop counter char c; //current character while (c!= EOF) { c= getchar(); //get char from stream if (c=='\t') //if char is a tab { for (i=0; i< spaces; i++) putchar(" "); //replace with spaces } else putchar(c); //otherwise, print the character } ``` } When compiling, I get an integer from pointer without cast warning for `putchar(" ");` and the program hits a segfault when executing. So, my questions: 1- What is the warning "makes integer from pointer without cast" all about? What can I do to resolve it? 2- The code generates a segfault on execution with a text file passed in as an argument. Is there anything in this code that would cause that?
1. You're calling `putchar` on a string (`" "`), but it wants a `char` argument (`' '`). (Actually an `int`, but only passing a `char` is safe.) 2. The segfault is probably due to the `fclose` on `fp`, which may be `NULL`. You should check the return value from `fopen`. The reason you only notice after `parse_file` is that it doesn't touch `fp` at all (it reads from `stdin` and writes to `stdout`). To use the stream `fp`, you should use `getc(fp)` and `putc(fp)` instead. (That still won't work because you'd overwrite the stream with more data than you're reading from it, so you'll get garbage out.) In fact, the program is sure to segfault when no command line argument is given. Either `fopen` segfaults because it is handed the null pointer `argv[1]`, or it returns a null pointer itself. When writing these kinds of programs, please adhere to the Unix philosophy and write them as [filters](https://secure.wikimedia.org/wikipedia/en/wiki/Filter_%28Unix%29): read from `stdin`, write to `stdout`. Don't modify a file in-place if you don't have to.
In C string literals are of type `char *`, a pointer to some area containing string characters. `" "` is a string literal, not a character. Use `' '` when you need a single character
Let $(a\_{n})\_{n}$ be a sequence of non zero real numbers such that the series $$\sum\_{n=1}^{\infty} a{\_{n}}$$ converges absolutely. Let $f:\mathbf{R}\rightarrow\mathbf{R}$ be a function with the property that $$\lim\_{x\to 0} f(x)/x$$ exists and is finite. Show that $$\sum\_{n=1}^{\infty} f(a{\_{n}})$$ converges absolutely.
Note that the convergence of $\sum\_{n=1}^{\infty} a{\_{n}}$ implies $$\lim\_{n\to\infty}a\_n= 0$$ Hence $$\lim\_{x\to 0} f(x)/x= \lim\_{n\to \infty} f(a\_n)/a\_n= l$$ for $\varepsilon= |l|+1>0$ there exists N such that for $n>N$ we have $$||f(a\_n)/a\_n|-|l||\le|f(a\_n)/a\_n-l|<|l|+1\implies |f(a\_n)|\le (2|l|+1)|a\_n|$$ that is $$\sum\_{n=N}^{\infty}|f(a\_n)|\le(2|l|+1) \sum\_{n=N}^{\infty}|a\_n|<\infty\ $$
Hint: Denote the limit of $f(x)/x$ as $L$ whenever $x\rightarrow 0$. Try to argue that $\left|f(a\_{n})\right|<(|L|+1)|a\_{n}|$ for large $n$.
I want to get data from DB and add string to theme and put them in another query . When I run code I've got this error : > > Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or > access violation: 1064 You have an error in your SQL syntax; check the > manual that corresponds to your MySQL server version for the right > syntax to use near ''goldhyipPID', 'goldhyipPayStatus', > programName,'goldhyipLastPayout') VALUES ('1' at line 1 in > C:\wamp64\www\allmonitors\test.php on line 69 > > > ``` <?php set_time_limit(3600); require_once 'fetchdetails/func.php'; require_once 'config.php'; $stmt = $conn->prepare("SELECT * FROM `monitors`"); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($result as $monitor) { $monitorName = $monitor['monitorName']; $monitorNamePID = $monitorName . 'PID'; $monitorNameLastPayout = $monitorName . 'LastPayout'; $monitorNamePayStatus = $monitorName . 'PayStatus'; $siteURL = $monitor['monitorurl']; $pattern1GetPID = $monitor['monitorPatternGetPID']; $patternLastPayOut = $monitor['monitorPatternLastPayout']; $patternPStatus = $monitor['monitorPatternPayStatus']; $patterndetailsurl = $monitor['monitorDetailsLink']; $patterngotositesurl = $monitor['monitorPatternGoSite']; $content = getPageContent($siteURL); preg_match_all($pattern1GetPID, $content, $matches, PREG_SET_ORDER, 0); foreach ($matches as $pid) { $id = $pid[1]; $detailsurl = $patterndetailsurl . $id; $gositesurl = $patterngotositesurl . $id; $details = getPageContent($detailsurl); preg_match_all($patternPStatus, $details, $status); $payingStatusNumber = $status[1][0]; if ($payingStatusNumber == 4) { $payingStatus = 'Not Paying'; } elseif ($payingStatusNumber == 3) { $payingStatus = 'Problem'; } elseif ($payingStatusNumber == 2) { $payingStatus = 'Waiting'; } elseif ($payingStatusNumber == 1) { $payingStatus = 'Paying'; } preg_match_all($patternLastPayOut, $details, $payout); if (isset($payout[1][0])) { $payoutdate = $payout[1][0]; } else { $payoutdate = ' Not Set'; }; $stmt2 = $conn->prepare('SELECT * FROM programs where :monitorNamePID=:id'); $stmt2->bindParam('monitorNamePID', $monitorNamePID); $stmt2->bindParam('id', $id); $stmt2->execute(); $numofupdates = $stmt2->rowCount(); if ($numofupdates >= 1) { $stmt3 = $conn->prepare("UPDATE programs SET :monitorNamePayStatus=:payingstatus , :monitorNameLastPayout=:goldhyiplastpayout WHERE :monitorNamePID=:goldhyippid "); $stmt3->bindParam('monitorNamePayStatus', $monitorNamePayStatus); $stmt3->bindParam('monitorNameLastPayout', $monitorNameLastPayout); $stmt3->bindParam('monitorNamePID', $monitorNamePID); $stmt3->bindParam('payingstatus', $payingStatus); $stmt3->bindParam('goldhyiplastpayout', $payoutdate); $stmt3->bindParam('goldhyippid', $id); $stmt3->execute(); echo 'P ID Updated : ' . $id . '<br>'; } else { $siteAddress = get_redirect_final_host_url($gositesurl); echo $siteAddress; $stmt3 = $conn->prepare('INSERT INTO programs (:monitorNamePID, :monitorNamePayStatus, programName,:monitorNameLastPayout) VALUES (:goldhyippid, :payingstatus, :progname, :goldhyiplastpayout)'); $stmt3->bindParam('monitorNamePID', $monitorNamePID); $stmt3->bindParam('monitorNamePayStatus', $monitorNamePayStatus); $stmt3->bindParam('monitorNameLastPayout', $monitorNameLastPayout); $stmt3->bindParam('goldhyippid', $id); $stmt3->bindParam('payingstatus', $payingStatus); $stmt3->bindParam('progname', $siteAddress); $stmt3->bindParam('goldhyiplastpayout', $payoutdate); $stmt3->execute(); echo 'P ID inserted : ' . $id . '<br>'; } } echo "Fetching $siteURL Done <br>"; } ``` I took details from sql, and add string to them, use in PDO query. When I write column name its ok but when I use Variable I got error.
Try this: ``` def functionOne(textFile): textFileVar = open(textFile, 'r') def splitKeyword(argument): keywordList = [] for line in argument: keywordList.append(line.strip().split(',')) return keywordList output = splitKeyword(textFileVar) print(output[1][0]) return output results = functionOne("text1.txt") print(results) ``` look at `return keywordList` in `splitKeyword` function. it returns the value(`keywordList`). but in other scopes you can not access that variable, so you need to store that in something.
keywordlist is a local variable to the function splitKeyword which return it so you can directly use this function and reduce the code. ``` def functionOne(textFile): textFileVar = open(textFile, 'r') def splitKeyword(argument): keywordList = [] for line in argument: keywordList.append(line.strip().split(',')) return keywordList print(splitKeyword(textFileVar)) results = functionOne("text1.txt") print(results) ```
I have been using "usleep" to stop a thread during some milliseconds and I have checked that is stopping more time than expected. I am sure I am doing something wrong, I am not an expert in Swift, but I don't understand it because it is very easy to check. For example: ``` DispatchQueue.global(qos: .background).async { let timeStart: Int64 = Date().toMillis() usleep(20 * 1000) // 20 ms let timeEnd: Int64 = Date().toMillis() let timeDif = timeEnd - timeStart print("start: \(timeStart), end: \(timeEnd), dif: \(timeDif)") } ``` The result: ``` start: 1522712546115, end: 1522712546235, dif: 120 ``` If I execute the same in the main thread: ``` start: 1522712586996, end: 1522712587018, dif: 22 ``` I think the way I generate the thread is wrong for stopping it. How could I generate a thread that works good with usleep? Thanks
A couple of thoughts: 1. The responsiveness to `usleep` is a function of the [Quality of Service](https://developer.apple.com/documentation/dispatch/dispatchqos.qosclass) of the queue. For example, doing thirty 20ms `usleep` calls on the five queue types, resulting in the following average and standard deviations (measured in ms): ``` QoS mean stdev ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐ ‐‐‐‐‐ background 99.14 28.06 utility 74.12 23.66 default 23.88 1.83 userInitiated 22.09 1.87 userInteractive 20.99 0.29 ``` The higher the quality of service, the closer to 20 ms it got, and with a lower standard deviation. 2. If you want accurate time measurements, you should avoid using `Date` and/or [`CFAbsoluteTimeGetCurrent()`](https://developer.apple.com/documentation/corefoundation/1543542-cfabsolutetimegetcurrent?language=occ). As the documentation warns us: > > Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock. > > > You can use a `mach_time` based value, such as conveniently returned by [`CACurrentMediaTime()`](https://developer.apple.com/documentation/quartzcore/1395996-cacurrentmediatime?language=occ), to avoid this problem. For example: ``` let start = CACurrentMediaTime() // do something let elapsed = CACurrentMediaTime() - start ``` 3. If you need even higher accuracy, see Apple [Technical Q&A #2169](https://developer.apple.com/library/content/technotes/tn2169/_index.html).
I, too, get times around 120 ms when sleeping a thread on a background queue: ``` import Foundation DispatchQueue.global(qos: .background).async { let timeStart = Date() usleep(20 * 1000) // 20 ms let timeEnd = Date() let timeDif = timeEnd.timeIntervalSince(timeStart) * 1000 print("start: \(timeStart), end: \(timeEnd), dif: \(timeDif)") exit(0) } CFRunLoopRun() ``` outputs: ``` start: 2018-04-03 00:10:54 +0000, end: 2018-04-03 00:10:54 +0000, dif: 119.734048843384 ``` However, with default QoS, my results are consistently closer to 20 ms: ``` import Foundation DispatchQueue.global(qos: .default).async { let timeStart = Date() usleep(20 * 1000) // 20 ms let timeEnd = Date() let timeDif = timeEnd.timeIntervalSince(timeStart) * 1000 print("start: \(timeStart), end: \(timeEnd), dif: \(timeDif)") exit(0) } CFRunLoopRun() start: 2018-04-03 00:12:15 +0000, end: 2018-04-03 00:12:15 +0000, dif: 20.035982131958 ``` So it appears that the `.background` QoS is causing the behavior you are seeing. Although I don't have direct knowledge of why this would be, it doesn't seem too far-fetched to speculate that the OS may be somewhat more lax about waking up sleeping threads that are marked with a background QoS. Indeed, this is what [Apple's documentation](https://developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/PrioritizeWorkWithQoS.html) has to say about it: > > A quality of service (QoS) class allows you to categorize work to be performed by NSOperation, NSOperationQueue, NSThread objects, dispatch queues, and pthreads (POSIX threads). By assigning a QoS to work, you indicate its importance, and the system prioritizes it and schedules it accordingly. For example, the system performs work initiated by a user sooner than background work that can be deferred until a more optimal time. In some cases, system resources may be reallocated away from the lower priority work and given to the higher priority work. > > > The possibility for your background work to be "deferred until a more optimal time" seems a plausible explanation of the behavior you're seeing.
I have the following code: ``` <div style='width: 200px; border: 1px solid black;'> <div style='display: inline-block; width: 70px; border: 1px solid green;'> asdfasdf<br />asdf </div> <div style='display: inline-block; width: 70px; border: 1px solid green;'> asdfasdf<br />were </div> </div> ``` This displays just fine in Firefox and Chrome, but in Internet Explorer 8, it does not. They have layout, so that isn't the problem, and the widths are small enough that it fits on one line. If I use `<span>`s instead, it does work; however, I would really like to know why `<div>`s don't work in IE.
`display: inline-block; *zoom: 1; *display: inline;` you can add inline-block for other browser but for IE you can add style with \*. it only works in ie
Changing the doc type worked for IE ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> ```
Hi guys I am trying to get a basic emulator running to display Hello World but the emulator appears but the phone never switches on. Please help me. ``` D:\Installed_Softwares\AndroidSDK\tools\emulator.exe -netdelay none -netspeed full -avd Nexus_5_API_24_2 ERROR: resizing partition e2fsck failed with exit code 9 emulator: WARNING: userdata partition is resized from 513 M to 800 M RegGetValueW failed 2 The system cannot find the file specified. RegGetValueW failed 2 The system cannot find the file specified. RegGetValueW failed 2 The system cannot find the file specified. Hax is enabled Hax ram_size 0x60000000 HAX is working and emulator runs in fast virt mode. emulator: Listening for console connections on port: 5554 emulator: Serial number of this emulator (for ADB): emulator-5554 ``` Will be glad to provide more information as needed.
`glClear` affects the output buffers. So it is part of rendering. If you want to clear as part of your rendering, put `glClear` inside your `render` function. You have it inside `update`. I suspect that whomever is calling `render` and `update` (LWJGL, presumably?) doesn't guarantee any particular ordering to them. So each time you're asked to update you're stomping on top of the last thing you rendered. Updates: * adjust internal state, usually partly as a function of time. Renders: * capture current state visually.
It is not very clear in my question, but the answer is that I cleared the screen, swapped buffers, rendered, etc. Which doesn't work. ``` glClear(...); glfwSwapBuffers(...); ...render... ``` This is how it is currently, and this doesn't work. ``` glClear(...); ...render... glfwSwapBuffers(...); ``` This is how I do it now, and it works fine.
I have this route in a laravel 4 app: ``` Route::controller('about','AboutController'); ``` When I go to `http://website/about/imprint` I get the imprint, but when I go to `http://website/about/imprint/12345` , (which is not used in the controller) I get the imprint as well. It does not throw an error. Is this a problem? Should I somehow catch it and show a 404 error, or does it not matter? I can even go to `http://website/about/imprint/7/7/7/7` for example, without getting an error message. the `AboutController` looks so: ``` <?php class AboutController extends BaseController { public function getIndex() { return View::make('about'); } public function getImprint() { return View::make('imprint'); } public function getDatenschutz() { return View::make('datenschutz'); } } ```
> > **Swift 3** > > > ``` func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)! selectedCell.contentView.backgroundColor = UIColor.darkGray } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)! selectedCell.contentView.backgroundColor = UIColor.clear } ```
Swift 4 ``` func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedCell = tableView.cellForRow(at: indexPath)! as! LeftMenuCell selectedCell.contentView.backgroundColor = UIColor.blue } ``` If you want to unselect the previous cell, also you can use the different logic for this ``` var tempcheck = 9999 var lastrow = IndexPath() var lastcolor = UIColor() func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tempcheck == 9999 { tempcheck = 0 let selectedCell = tableView.cellForRow(at: indexPath)! as! HealthTipsCell lastcolor = selectedCell.contentView.backgroundColor! selectedCell.contentView.backgroundColor = UIColor.blue lastrow = indexPath } else { let selectedCelllasttime = tableView.cellForRow(at: lastrow)! as! HealthTipsCell selectedCelllasttime.contentView.backgroundColor = lastcolor let selectedCell = tableView.cellForRow(at: indexPath)! as! HealthTipsCell lastcolor = selectedCell.contentView.backgroundColor! selectedCell.contentView.backgroundColor = UIColor.blue lastrow = indexPath } } ```
I am using Entity Framework Code First in my ASP.NET MVC application. One of my classes has several columns that are added together. I am storing these columns as computed columns in the tables by running an alter table script in the database initializer. Let's say the class looks like: ``` public class Bond { public decimal ParAmountOfIssuance { get; set; } public decimal AccruedInterest { get; set; } public decimal Premium { get; set; } public decimal OriginalIssueDiscount { get; set; } } ``` The alter script is something like: ``` alter table Bonds add TotalSources as (ParAmountOfIssuance + AccruedInterest + Premium - OriginalIssueDiscount) ``` I want the `Total Sources` column to be available for viewing in the web app. What's the best way to accomplish this? The `[DatabaseGenerated(DatabaseGeneratedOption.Computed)]` attribute doesn't work because EF Code First creates the table from the class before the alter script is ran. Any suggestions are welcome.
This is [definitely not supported](http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/a6d182bd-5027-4793-bfd9-ef88a44ec6bc) - defining `Computed` option on custom property will throw exception. Code first = logic in code. If you need custom computed properties use database first. The only database logic supported by code first is identity column and timestamp. The problem is that you need the column to be marked as computed but creating database will not allow that. If the column is not marked as computed it will be updatable = EF will generate update statements trying to update this column which will fail in the database.
I'm doing computed columns in CF (WinForms) like that (I don't know if it's the best): This is one Entity: ``` public class Result { public int ResultId { get; set; } public int StudentId { get; set; } public Student Student { get; set; } public float Arabic { get; set; } public float English { get; set; } public float Math { get; set; } public float Science { get; set; } public float Total { get; set; } } ``` This is Form2: ``` private void Form2_Load(object sender, EventArgs e) { Model1 model = new Model1();//Model1 : DbContext model.Database.CreateIfNotExists(); model.Database.ExecuteSqlCommand("alter table Results drop column Total; alter table Results add Total AS (Arabic + English + Math + Science)"); var r1 = (from s in model.Students join r in model.Results on s.StudentId equals r.StudentId select new { s.StudentName, r.Arabic, r.English, r.Science, r.Math, r.Total }).ToList(); dataGridView1.DataSource = r1; } ```
Alright, this has been on my mind for a while now. I'm in the process of creating a reusable corporate namespace(class library) for all common middle-tier objects. This assembly can then be referenced by any of our developers during the development phase of their project. Here's my question. Is it more acceptable to create a single assembly which consists of all our middle-tier logic or to break this functionality up into smaller assemblies? **Example: Single Assembly(namespace examples)** System System.IO System.IO.RegEx System.Net System.Net.Mail System.Security System.Web - **AssemblyFull.dll** **Example: Multiple Assemblies** System.IO System.IO.Reg - **Compiles to AssemblyIO.dll** System.Net System.Net - **Compiles to AssemblyNet.dll** In the past I've done this using both methods but I'm wondering what everyone else does and why? I'm not looking for any code examples, I just want to know what other developers have doing? Thanks in advance.
As a general rule, I use to separate assemblies if they are not explicit coupled. For example if you have a low level Networking API, and other API for FTP related operations, probably the later depends upon the former; but for the API user, your developers; there is no need to have both in a single assembly; maybe one project does not require the FTP API, so they only need to include the core "Net" assembly. You can separate APIs in order to be the more atomic as possible and avoid developers to include a big assembly when their will use only a small part of it. The down side of this approach is that if the developer needs the FTP assembly they also need to include the Net one; so you have to find a way to manage those dependencies that reduces the complexity for developers. I use [Maven (from Apache)](http://maven.apache.org/) when doing Java applications but by this date I do not know a good [maven-like alternative for .NET](https://stackoverflow.com/questions/729545/why-is-there-no-need-for-maven-in-net). But if your are building a few APIs for your company, with a Wiki site or other light weigh documentation tool you can address this problem.
I dont think their is a right answer for this but I tend to use a common naming approach for all of our libraries. I have a library that handles a lot of the middle-tier functionality, sort of like common tasks that most apps would use. Web.CreditCard Web.CreditCard.Authorization Web.CreditCard.Charge Web.CreditCard.Batch Web.Store.Order Web.Store.Entities Web.Store.Cart Web.Store.Auth Web.User.Auth.OpenID Web.User.Auth.OAuth Web.User.Account Web.User.Preferences So it don't matter which type of project your building you can reuse them and identify them really quick. Some of them have their own interfaces and can be inherited and overloaded to add more functionality depending on the project requirements.
I need to calculate checksums of quite large files (gigabytes). This can be accomplished using the following method: ``` private byte[] calcHash(string file) { System.Security.Cryptography.HashAlgorithm ha = System.Security.Cryptography.MD5.Create(); FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read); byte[] hash = ha.ComputeHash(fs); fs.Close(); return hash; } ``` However, the files are normally written just beforehand in a buffered manner (say writing 32mb's at a time). I am so convinced that I saw an override of a hash function that allowed me to calculate a MD5 (or other) hash at the same time as writing, ie: calculating the hash of one buffer, then feeding that resulting hash into the next iteration. Something like this: (pseudocode-ish) ``` byte [] hash = new byte [] { 0,0,0,0,0,0,0,0 }; while(!eof) { buffer = readFromSourceFile(); writefile(buffer); hash = calchash(buffer, hash); } ``` hash is now sililar to what would be accomplished by running the calcHash function on the entire file. Now, I can't find any overrides like that in the.Net 3.5 Framework, am I dreaming ? Has it never existed, or am I just lousy at searching ? The reason for doing both writing and checksum calculation at once is because it makes sense due to the large files.
I like the answer above but for the sake of completeness, and being a more general solution, refer to the `CryptoStream` class. If you are already handling streams, it is easy to wrap your stream in a `CryptoStream`, passing a `HashAlgorithm` as the `ICryptoTransform` parameter. ``` var file = new FileStream("foo.txt", FileMode.Open, FileAccess.Write); var md5 = MD5.Create(); var cs = new CryptoStream(file, md5, CryptoStreamMode.Write); while (notDoneYet) { buffer = Get32MB(); cs.Write(buffer, 0, buffer.Length); } System.Console.WriteLine(BitConverter.ToString(md5.Hash)); ``` You might have to close the stream before getting the hash (so the `HashAlgorithm` knows it's done).
Hash algorithms are expected to handle this situation and are typically implemented with 3 functions: `hash_init()` - Called to allocate resources and begin the hash. `hash_update()` - Called with new data as it arrives. `hash_final()` - Complete the calculation and free resources. Look at <http://www.openssl.org/docs/crypto/md5.html> or <http://www.openssl.org/docs/crypto/sha.html> for good, standard examples in C; I'm sure there are similar libraries for your platform.
React hooks makes it possible to use all React features such as component state and lifecycle methods without class declarations (just function components). This reduces boilerplate, duplication and negotiates the use of bug-prone `this` keyword. Further it makes it easy to isolate and share common state-management logic across unrelated components, thanks to function composition. However, hooks doesn't replace Redux by it's purpose of centralized and predictable state container. Is it possible to connect React function components to Redux, as I want to embrace the functions only paradigm of future React and still use Redux?
Sending a message **to** a device require that you call the Firebase Cloud Messaging API and specify the FCM Server Key. As its name implies, this key should only be used on a trusted environment, such as your development machine, a server that you control, or an environment like Cloud Functions. The reason this is required is that anyone who has you FCM server key can send messages to all users of your app. The simplest way to get started is to simply run a `curl` command or something like that, calling the [*legacy* FCM REST API](https://firebase.google.com/docs/cloud-messaging/http-server-ref). See an example of that here: [How can I send a Firebase Cloud Messaging notification without use the Firebase Console?](https://stackoverflow.com/questions/37371990/how-can-i-send-a-firebase-cloud-messaging-notification-without-use-the-firebase) To send to a topic, make sure the `to` value is something like `"/topics/your_topic"`. For a more production level, you'll probably want to introduce a server, or use Cloud Functions. Sending a message then becomes a multi-step process like: 1. The client that wants to send a message, writes that messages to a database, or calls an API. 2. This write operation triggers your server, or Cloud Functions, which validates the request (determining that this user is authorized to send this message). 3. The server-side code then [calls the Firebase Admin API to send a message to a topic](https://firebase.google.com/docs/cloud-messaging/send-message#send_messages_to_topics). For one example of this, see this [folder in the `functions-samples` repo](https://github.com/firebase/functions-samples/tree/master/fcm-notifications). Also see: * my old [Sending notifications between Android devices with Firebase Database and Cloud Messaging](https://firebase.googleblog.com/2016/08/sending-notifications-between-android.html) blog post * [How to send Device to device notification by using FCM without using XMPP or any other script.?](https://stackoverflow.com/questions/38432243/how-to-send-device-to-device-notification-by-using-fcm-without-using-xmpp-or-any) * [How to send one to one message using Firebase Messaging](https://stackoverflow.com/questions/37990140/how-to-send-one-to-one-message-using-firebase-messaging) * [How to send device to device messages using Firebase Cloud Messaging?](https://stackoverflow.com/questions/37435750/how-to-send-device-to-device-messages-using-firebase-cloud-messaging)
According to [firebase\_messaging readme](https://pub.dev/packages/firebase_messaging) page, in the last section, you can not send a cloud message using the flutter `firebase_messaging` library read the [Sending Message](https://pub.dev/packages/firebase_messaging#sending-messages). To subscribe a user to a topic: ``` FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); _firebaseMessaging.subscribeToTopic("MyTopic"); ``` This will subscribe that device to the topic `MyTopic`. You can also unsubscribe by: ``` _firebaseMessaging.unsubscribeFromTopic("MyTopic"); ```
I have 3 tables guest\_user\_info,pg\_company,user\_profile. In guest\_user\_info have 2 columns: ``` g_uid | company_id ``` In pg\_company have 2 columns: ``` company_id | user_id ``` In user\_profile have 2 columns: ``` id |user_email ``` Here i want to get `user_email` from `user_profile.i` have `g_uid` value (in `guest_user_info` table).i want company\_id from guest\_user\_info and get the company\_id and match with `pg_company` table,there i can get user\_id.then match with that `user_id` with id in `user_profile` table.at last i need `user_email` from `user_profile` table
> > Is there a way in CSS to check if the `btn-primary` class exists inside of `stepwizard__step` and if it does, to change the color of `stepwizard__step-text` to red? > > > Yes, but only if `stepwizard__step-text` comes *after* the `btn-primary`. This is because rules only go down the DOM tree, never to parent elements or predecessors. The rules can be built as follows: 1. Select a `.btn-primary` inside `.stepwizard__step`... ``` .stepwizard__step .btn-primary ``` 2. ...and target a `.stepwizard__step-text` coming [right after it](https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors). ``` .stepwizard__step .btn-primary + .stepwizard__step-text ``` If there can be elements between the `.btn-primary` and `.stepwizard__step-text`, use a [`~`](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_selectors) instead of a `+` in the last selector. This is the [general sibling selector](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_selectors). Your example would then become something like the following. ```css .stepwizard__step .btn-primary ~ .stepwizard__step-text { color: red; } ``` ```html <div class="stepwizard__step"> <a class="btn btn-primary stepwizard_btn">1</a> <p class="stepwizard__step-text">Payment</p> </div> ```
You can do this: ```css .btn-primary+p.stepwizard__step-text { color: red; } ``` ```html <div class="stepwizard__step"> <a class="btn btn-primary stepwizard_btn">1</a> <p class="stepwizard__step-text">Payment</p> </div> ``` Hope it works for your use!
I'm trying to join multiple tables in q ``` a b c key | valuea key | valueb key | valuec 1 | xa 1 | xb 2 | xc 2 | ya 2 | yb 4 | wc 3 | za ``` The expected result is ``` key | valuea | valueb | valuec 1 | xa | xb | 2 | ya | yb | xc 3 | za | | 4 | | | wc ``` The can be acheieved simply with ``` (a uj b) uj c ``` BUT does anyone know how i can do it in functional form? I don't know how many tables i actually have I need basically a function that will go over the list and smash any number of keyed tables together... ``` f:{[x] x uj priorx}; f[] each (a;b;c;d;e...) ``` Can anyone help? or suggest anything? Thanks!
I also have this problem because the version of Facebook's SDK I am using is not updated. So if you are using it too, just try to use the updated version of Facebook's SDK v3.21.1, and that warning is solved.
I had this issue, I am using ffmpeg lib and .so files, I resolved issue by below steps: First, I use Android Studio. So, if you're using Eclipse, try to find your own way. The cause of the issue is the libavformat.so file which is using OpenSSL 1.0.2d. We need to update it. But, just updating libavformat.so will cause crashing, so we need to update all relating lib (javacv and javacpp). * Download javacv-1.2-bin.zip and javacpp-1.2.3-bin.zip from <https://github.com/bytedeco/javacv> and <https://github.com/bytedeco/javacpp> * Extract them and copy `ffmpeg.jar`, `javacpp.jar`, `javacv.jar` and `opencv.jar` to `[yourproject]\libs`. * Extract `ffmpeg-android-arm.jar` and `opencv-android-arm.jar` (find them after extracting `javacv-1.2-bin.zip`), you will collect new version of .so files. * Replace the old files in `[yourproject]\src\main\jniLibs\armeabi-v7a` with new version (just almost .so files will be replaced, not all of them) * Sometimes, you need to copy `javacpp-presets-1.2.pom` file to `[yourproject]\libs`, too. You can search it on Google. * Modify the module `build.gradle` of your project ``` apply plugin: 'com.android.library' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { minSdkVersion 14 targetSdkVersion 23 } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/services/javax.annotation.processing.Processor' pickFirst 'META-INF/maven/org.bytedeco.javacpp-presets/opencv/pom.properties' pickFirst 'META-INF/maven/org.bytedeco.javacpp-presets/opencv/pom.xml' pickFirst 'META-INF/maven/org.bytedeco.javacpp-presets/ffmpeg/pom.properties' pickFirst 'META-INF/maven/org.bytedeco.javacpp-presets/ffmpeg/pom.xml' pickFirst 'META-INF/maven/org.bytedeco.javacpp-presets/ffmpeg/pom.xml' pickFirst 'META-INF/maven/org.bytedeco.javacpp-presets/1.2/javacpp-presets-1.2.pom.xml' pickFirst 'META-INF/maven/org.bytedeco.javacpp-presets/org.bytedeco.javacpp-presets-1.2.pom.xml' } } configurations { all*.exclude group: 'org.bytedeco', module: 'javacpp-presets' } repositories { mavenCentral() } dependencies { compile 'com.android.support:support-v4:23.2.1' compile files('libs/opencv.jar') //1.2 compile files('libs/javacv.jar') //1.2 compile files('libs/javacpp.jar') //1.2.3 compile files('libs/ffmpeg.jar') //1.2 } ``` * Clean project and rebuild. Reference- [**kieukhuongthinh's**](https://github.com/sourab-sharma/TouchToRecord/issues/23) comment
I've spilled 5-10 mL of liquid on my Macbook Pro (13 inch, early 2015) some hours ago. I purchased this laptop a few months ago. It has 16 GB of RAM and 512 GB storage, though this is probably irrelevant. The liquid came in contact with the trackpad (including the edges of it). I did not turn it off. Rather, I ran the Apple Diagnostics Test and it came out fine. Several hours later, I ran the diagnostics test again and it was fine. The laptop, including the trackpad, is functioning normally at this moment. > > What is the likelihood that the laptop, particularly the trackpad, will develop problems in the future? > > > Also, > > Is it worth the time to go to an Apple Store and get this checked out? > > > Normally, I wouldn't even ask; I'd take it to the Apple Store just in case. However, I am very busy this weekend and a visit to the Apple Store will take a good 2 hours of my time, at the very least. Resassurance from experts on this site will give me peace of mind. Moreover, I would also appreciate a comment from people who know a thing or two about the hardware of this laptop model regarding how 'water protected' the trackpad structure is. I am, again, mainly worried about liquid having leaked through its edges.
OK, having wrecked a couple of Macbooks myself because someone spilled liquid into them, I'll tell you what to expect: First, power it off and remove the battery if you can (but I don't think you can with your model) and prop it up so any liquid can run out. Give it about a day for the liquid to dry. Or better yet, get it to a repair shop if you can. They'll know how to take it apart and dry it out. Note that it's important to *remove* the liquid and not dry it in place. A hot-air hair dryer would not help; you could just as well air-dry it yourself. Jets of compressed air that actually blow the water out of the machine would be better. Otherwise if you have a teeny-tiny phillips-head screwdriver, and the guts to do it, dismantle it yourself and pat everything dry that you can reach. Keep *very* good track of which screw came from where. The bad news: ------------- After the liquid dries, the residue remains on the circuit boards. It will almost certainly contain sugars or other corrosive chemicals. These will slowly eat away at the circuitry. So you *think* you dodged a bullet with the spilled drink, but in about three years you will start to experience unexplained flakiness. I spent about $400 replacing parts in mine before I remembered the mocha someone spilled in it three years prior and realized that I would certainly have to replace the motherboard itself. The good news: -------------- In your case it was just water, and just a little bit, and not on the motherboard. There's a good chance that you *did* dodge a bullet. And in any event, you have probably another three years to start saving your pennies for a replacement.
If you spill water on your MacBook or MacBook Pro - if you have an air purifier, target it to the keyboard/screen where the liquid is until it's dry. I put my MacBook Pro in an upside-down v-shape over a towel and then positioned my air purifier a few inches away from the keyboard/screen - in 5-10 mins my computer was working just fine! Right after I spilled a 1/2 glass of ice water on it I could not even turn it on! I think an air purifier works much, much better than a fan - I think the air purifier just sucks the water right out in literally minutes! If you have a high quality air purifier, it can save your Mac Book!
I have a df where column 'elements' looks like this: [![enter image description here](https://i.stack.imgur.com/13p35.png)](https://i.stack.imgur.com/13p35.png) How can I split each word using this as separator "|" then send each word as key avoiding duplicates? I used this but it's not working: ``` for row in df.elements.itertuples(): for l in row.elements.split("|"): list_elem.send_keys(l) ```
If `id` is the only column name in common, you can take advantage of the `USING` clause: ``` spark.sql("select * from tbl1 join tbl2 using (id) ") ``` The `using` clause matches columns that have the same name in both tables. When using `select *`, the column appears only once.
```scala val joined = spark .sql("select * from tbl1") .join( spark.sql("select * from tbl2"), Seq("id"), "inner" // optional ) ``` `joined` should have only one `id` column. Tested with Spark 2.4.8
I built a basic Windows Form app. I want to make it so that my program deletes itself after a date of my choosing. Specifically, when someone clicks on the .exe to run it, and if it's after a certain date, the .exe is deleted. Is this possible? If yes, how do I do this? I think my code would look something like this: ``` DateTime expiration = new DateTime(2013, 10, 31) //Oct. 31, 2013 If (DateTime.Today > expiration) { //command to self-delete } else { //proceed normally } ```
This works, runs a commandline operation to delete yourself. ``` Process.Start( new ProcessStartInfo() { Arguments = "/C choice /C Y /N /D Y /T 3 & Del \"" + Application.ExecutablePath +"\"", WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, FileName = "cmd.exe" }); ```
It cannot delete itself while it is running, because its executable and library files will be locked. You could write a second program that takes in a process ID as an argument, waits for that process to die, and then deletes the first program. Embed that as a resource in your main application, then extract it to `%TEMP%`, run, and exit. This technique is usually used in combination with automatic updaters, and it's definitely not fool-proof.
I try to add a little triangle as the current page indicator under the list item of my navbar with class "active" using ::after. However, 1. The alignment of the triangle may not be center for all list items due to the length differences. ![Triangle is not center to the element](https://i.stack.imgur.com/4hkOl.jpg) 2. The website should be responsive. When I resize the window screen, list items are compacted and enlarge the width of the list. Again, due to the length differences of list items, part of the triangle will be covered if it is under a short list item as the "::after" ignores the padding space. ![Small triangle for short list item when resizing the screen](https://i.stack.imgur.com/CncJZ.jpg) Here's the code snippet: ```css nav { display: block; } ul { display: table; text-align: center; background-color: red; margin-bottom: 5%; width: 100%; padding-left: 0; margin-bottom: 0; list-style: none; } li { display: table-cell; float: none; padding: 5px 0; vertical-align: middle; position: relative } li.active::after { content: ""; width: 0; height: 0; position: absolute; right: 40%; border-style: solid; border-width: 15px 10px 0 10px; border-color: red transparent transparent transparent; } ``` ```html <nav> <ul> <li>xxxxxxxxxxxxxxxxxx</li> <li>xxxx</li> <li>xxxx</li> <li class="active">xxxx</li> <li>xxxx</li> <li>xxxx</li> <li>xxxx</li> </ul> </nav> ``` Is there any solution for that?
I found an answer to this [here](https://gist.github.com/cerisier/118c06d1a0147d1fb898218b57ba82a3/) such that my initialization script now looks like this: ``` #!/bin/bash # Install tools apt-get -y install python3 python-dev build-essential python3-pip easy_install3 -U pip # Install requirements pip3 install --upgrade google-cloud==0.27.0 pip3 install --upgrade google-api-python-client==1.6.2 pip3 install --upgrade pytz==2013.7 # Setup python3 for Dataproc echo "export PYSPARK_PYTHON=python3" | tee -a /etc/profile.d/spark_config.sh /etc/*bashrc /usr/lib/spark/conf/spark-env.sh echo "export PYTHONHASHSEED=0" | tee -a /etc/profile.d/spark_config.sh /etc/*bashrc /usr/lib/spark/conf/spark-env.sh echo "spark.executorEnv.PYTHONHASHSEED=0" >> /etc/spark/conf/spark-defaults.conf ```
You can also use the Conda init action to setup Python 3 and optionally install pip/conda packages: <https://github.com/GoogleCloudPlatform/dataproc-initialization-actions/tree/master/conda>. Something like: `gcloud dataproc clusters create foo --initialization-actions \ gs://dataproc-initialization-actions/conda/bootstrap-conda.sh,gs://dataproc-initialization-actions/conda/install-conda-env.sh`
I wanted to know if I can pass back individual parameters from a php script to be stored in dfferent JS variables on the page I'm working on, while also returning generated html code from the php script along with those parameters. Basically I would like to return some data like this from php using ajax: ``` $valid = "true"; $access = "false"; $htmlcontent="lorem ipsum<br/>some more text<b>bold</b>"; ``` And all of this should go into equivalent javascript variables on my page, using ajax, so that I can contruct my response on the page using this data...
Add the data to an array and `json_encode` then: ``` $ret = array(); $ret["valid"] = "true"; $ret["access"] = "false"; $ret["htmlcontent"] ="lorem ipsum<br/>some more text<b>bold</b>"; echo json_encode($ret); ``` And in your client side: ``` $.ajax({ url:"your_script.php", success:function(resp) { var json = jQuery.parseJSON(resp) alert(json.valid) } }) ```
Just let PHP print them directly as JS variables. It also saves your client one HTTP request. ``` <script> var valid = <?= $valid ?>; var access = <?= $access ?>; var htmlcontent = <?= json_encode($htmlcontent) ?>; </script> ```
I am attempting to list the List's items but I get repeatedly displayed the first row of the List. The List should contain three different product rows. Instead, ListView shows the same, first row three times. I create list like this: ``` List<ProductsNumber> ProductsNumberList = new List<ProductsNumber>(); ProductsNumber _ProductsNumber = new ProductsNumber(); for (int i= 0; i <= otherlist.Count - 1; i++) { _ProductsNumber.ProdId = otherlist[i].ProdName.ToString(); _ProductsNumber.ProductsNumber = (DB_ProductList.Where(Product => Product.ProdId == otherlist[i].ProdName)).Count(); ProductsNumberList.Add(_ProductsNumber); } //listView listBox.ItemsSource = ProductsNumberList;//Binding data to LISTBOX ``` And here is the class used to populate List: ``` public class ProductsNumber { public string ProdId { get; set; } public int ProductsNumber { get; set; } } ``` If you are interested: ``` otherlist ``` works just fine when I list it in listview. DB\_ProductList is defined like this: ``` ReadAllProductsList dbproduct = new ReadAllProductsList(); DB_ProductList = dbdproduct.GetAllProducts(); List<Product> ProductList = new List<Product>(); ProductList = DB_ProductList.ToList(); ``` and it works well too. Anyway, I get correct ProductNumber in ListView. It's the ProdId that gives me problems. I get indeed correct number of iterations in ListView, but they all are the same. ListView should list all Products, and not repeat the same one. Any clue? I am guessing that when populating List the same record is inserted three times. But why?
There are many ways you can achieve this. I would just give you the direct solution (as I'm sure someone else will), but I think there's a lot of benefit in figuring it out yourself with the right guidance, especially given that you are "new", as you claim. :) **Here is one approach you can take**: Create a "store" of answers in memory to check against * When someone checks a checkbox, check that question and answer against the store. * If the question in the store contains an answer that was selected, we have a winner. Otherwise, we have a loser. Example: ``` var questions = { "question1": ["answer1", "answer2"], "question2": ["answer1", "answer3", "answer3"] }; function selectAnswer(question, selectedAnswer) { if (questions[question]) { var found = false; questions[question].forEach(function (answer) { if (answer === selectedAnswer) { found = true; } }); if (found) { // Do something } return found; } } console.log(selectAnswer("question1", "answer1")) // true console.log(selectAnswer("question1", "answer4")) // false ``` Now you can expand on that function by making it take in an argument of a list of answers instead of just one answer, and you can check all answers against the store for a particular question. OR, you can use that one function against each answer that was selected for a given question. That works as well. That should achieve what you want! :) --- If all fails and you still need help, feel free to leave a comment and I'll cook something up for your specific environment (Angular, etc.).
Solved with the following: ``` var superbag = function(sup, sub) { sup.sort(); sub.sort(); var i, j; for (i=0,j=0; i<sup.length && j<sub.length;) { if (sup[i] < sub[j]) { ++i; } else if (sup[i] == sub[j]) { ++i; ++j; } else { // sub[j] not in sup, so sub not subbag return false; } } // make sure there are no elements left in sub return j == sub.length;} var contains = function(needle) { // Per spec, the way to identify NaN is that it is not equal to itself var findNaN = needle !== needle; var indexOf; if(!findNaN && typeof Array.prototype.indexOf === 'function') { indexOf = Array.prototype.indexOf; } else { indexOf = function(needle) { var i = -1, index = -1; for(i = 0; i < this.length; i++) { var item = this[i]; if((findNaN && item !== item) || item === needle) { index = i; break; } } return index; }; } return indexOf.call(this, needle) > -1;}; ```
I'm having some problems with JRTPLIB c++ win32 version, compiling in visual studio2010.(http://research.edm.uhasselt.be/~jori/page/index.php?n=CS.Jrtplib). I've emailed the author but have yet to received a reply. The problem I am experiencing is this: ``` error C1083: Cannot open include file: 'rtpconfig_unix.h': No such file or directory c:\users\johan-bar\desktop\developer tools\3rd party software\jrtplib-3.8.1\src\rtpconfig.h ``` The two .h files I have are these: MAIN.h: ``` enter code here #include <WinSock2.h> #include <Windows.h> #include <WindowsX.h> #include <stdlib.h> #include <string> #include <Richedit.h> #include "jrtlibtest.h" #include "resource.h" ``` jrtlibtest.h: ``` #include "rtpsession.h" ``` So I reason that I need to #include windows.h in jrtlibtest.h for it to recognise WIN32 to be defined (so it does not include unix .h files) but that in turn gives me about 100 redifinition errors. I am unsure how to solve this problem and I can't find any information on the library homepage itself or on the internet. Has anyone else encountered this problem? Cheers
Include ws2\_32.lib in your project. Had the same problem. (And remove if you already include it, wsock32.lib and winsock.h header file to avoid colissions)
What are the redefinition errors? If they are from winsock, removing winsock2.h from your includes might help.
I have a view on angular just like this: [![enter image description here](https://i.stack.imgur.com/JimWN.png)](https://i.stack.imgur.com/JimWN.png) And this is my dashboard.component.ts: ``` export class DashboardComponent implements OnInit { tablePresetColumns; tablePresetData; ngOnInit() { this.tablePresetColumns = [{id: 1,content: 'Username'},{id: 2,content: 'Status'}]; this.tablePresetData = [[{id: 1,content: 'john.doe@random.com'},{id: 2,content: 'Busy'}],[{id: 1,content: 'test2@random.com'},{id: 2,content: 'overload'}]]; } } ``` And this is the way i call the table on dashboard.component: ``` <div eds-tile class="xl-4" style="height: 700px"> <eds-tile-title>User on Shift</eds-tile-title> <eds-table [columns]="tablePresetColumns" [data]="tablePresetData" [modes]="['compact', 'dashed']"></eds-table> </div> ``` eds-table: ``` selector: 'eds-table', template: "<table class=\"table\" [ngClass]=\"modes\">\n <thead *ngIf=\"columns\">\n <tr>\n <th *ngFor=\"let col of columns\">\n {{col.content}}\n </th>\n </tr>\n </thead>\n <tbody>\n <tr *ngFor=\"let row of data\">\n <td *ngFor=\"let cell of row\">\n {{cell.content}}\n </td>\n </tr>\n </tbody>\n</table>\n", ``` What should I do, if I want to give some color on Status, I mean there are conditions when status Busy, the text Color change green, or Idle change Yellow, and Overload change into Red. Help me, guys... Thanks,
You can use the below ``` <td *ngFor="let cell of row" [ngStyle]="{'color': (cell.content === 'Busy') ? 'green' : (cell.content === 'overload') ? 'red' : (cell.content === 'idle') ? 'yellow' : ''}">{{cell.content}} </td> ``` The condition should be on `cell.content` but not on `row.content`
``` <table class="table" [ngClass]="modes"> <thead *ngIf="columns"> <tr> <th *ngFor="let col of columns"> {{col.content}} </th> </tr> </thead> <tbody> <tr *ngFor="let row of data"> <td [ngClass]="cell.content.toLowerCase()" *ngFor="let cell of row"> {{cell.content}} </td> </tr> </tbody> </table> ``` and in css define class for each type of status. ``` .busy { color: red; /* other css property you want to add */ } .idle { color: red; /* other css property you want to add */ } .overload { color: red; /* other css property you want to add */ } ``` here is [stackblitz](https://stackblitz.com/edit/angular-qrakqc) and in my end it is working fine. I attached this screenshot just for FYI. [![enter image description here](https://i.stack.imgur.com/o6sXM.png)](https://i.stack.imgur.com/o6sXM.png)
i am using magento 1.5 and have strange problem in the category edit and product edit page in admin, the subcategory tree for one category is not showing i have write the custom code to find the subcategory for that particular category and its not showing any subcategory using that code, but when i have checked in the database all the subcategories for that particular category is available. in simple words the subcategories tree for one category is not showing in category edit and product edit page in admin. Thanks, Jeet
I can assure you that Zachary Schuessler solution works perfectly in 1.7.0.2. I am just posting so it can help future questions. 1- I got this problem after i removed alot of products from a under Root category using "Catalog/Manage Categories" and deselecting the products in "Category Products" Tab. 2- The pattern category was **Hardware**, and inside i had several subcategories, the expand "+" sign just disappeared and as so all subcategories in backend, all fine in frontend. 3- Did as Zachary Schuessler said and looking at database at **Hardware** category ID, "children\_count" column in "catalog\_category\_entity" i had a value of "-20". 4- Edited the value to "20" and all was fine again in backend. Note: This also happened to me once when i moved a subcategory from one category and moved it inside other different category. Cheers!
Here is an SQL statement to update all the children counts if they become out of sync from moving categories around. Had this issue occur for us when the server crashed halfway through moving a category inside another one. ``` UPDATE catalog_category_entity a INNER JOIN (SELECT parent_id, count(entity_id) totalChildren FROM catalog_category_entity GROUP BY parent_id) b ON a.entity_id=b.parent_id SET a.children_count = b.totalChildren; ```
Different Data structures are used according to requirement but how would I know which data structure should I use? I just want to know how to choose an appropriate data structure ? Thanks
This flowchart is for the STL in C++, but you could implement any of the data structures supported by the STL containers in C. * List is a linked list * Vector is a dynamic array * Deque is something like a list of dynamic arrays -- sort of splits the difference. * Queue and Priority queue are like they say (usually queue is implemented in terms of deque, priority queue is usually implemented in terms of a heap inside a vector or deque) * Set/Map/Multiset/Multimap are all implemented using some form of balanced binary tree. Update 2016: Apparently the image I used to link to here has been link-rotted, but you can see several equivalent images over at this question: [In which scenario do I use a particular STL container?](https://stackoverflow.com/questions/471432/in-which-scenario-do-i-use-a-particular-stl-container)
Not what you are looking for, but it **depends**. It depends on the data that you are storing, any constraints on accessing that data, do you need to be able to look things up really fast? Does it need to maintain any kind of sort on the data? Will you be sorting it later? Even when you choose a data structure (Linked List, Map, Set) there a numerous variants among them that might further drive your decision. My rule of thumb is this: Go with the simplest that you can until you know otherwise that you need something more complicated.
I've been thinking about batch reads and writes in a RESTful environment, and I think I've come to the realization that I have broader questions about HTTP caching. (Below I use commas (",") to delimit multiple record IDs, but that detail is not particular to the discussion.) I started with this problem: 1. Single `GET` invalidated by batch update ------------------------------------------- ``` GET /farms/123 # get info about Old MacDonald's Farm PUT /farms/123,234,345 # update info on Old MacDonald's Farm and some others GET /farms/123 ``` How does a caching server in between the client and the Farms server know to invalidate its cache of `/farms/123` when it sees the `PUT`? Then I realized this was also a problem: 2. Batch `GET` invalidated by single (or batch) update ------------------------------------------------------ ``` GET /farms/123,234,345 # get info about a few farms PUT /farms/123 # update Old MacDonald's Farm GET /farms/123,234,345 ``` How does the cache know to invalidate the multiple-farm `GET` when it sees the PUT go by? So I figured that the problem was really just with batch operations. Then I realized that any relationship could cause a similar problem. Let's say a farm has zero or one owners, and an owner can have zero or one farms. 3. Single `GET` invalidated by update to a related record --------------------------------------------------------- ``` GET /farms/123 # get info about Old MacDonald's Farm PUT /farmers/987 # Old MacDonald sells his farm and buys another one GET /farms/123 ``` How does the cache know to invalidate the single GET when it sees the PUT go by? Even if you change the models to be more RESTful, using relationship models, you get the same problem: ``` GET /farms/123 # get info about Old MacDonald's Farm DELETE /farm_ownerships/456 # Old MacDonald sells his farm... POST /farm_ownerships # and buys another one GET /farms/123 ``` In both versions of #3, the first GET should return something like (in JSON): ``` farm: { id: 123, name: "Shady Acres", size: "60 acres", farmer_id: 987 } ``` And the second GET should return something like: ``` farm: { id: 123, name: "Shady Acres", size: "60 acres", farmer_id: null } ``` But it can't! Not even if you use `ETag`s appropriately. You can't expect the caching server to inspect the contents for `ETag`s -- the contents could be encrypted. And you can't expect the server to notify the caches that records should be invalidated -- caches don't register themselves with servers. So are there headers I'm missing? Things that indicate a cache should do a `HEAD` before any `GET`s for certain resources? I suppose I could live with double-requests for every resource if I can tell the caches which resources are likely to be updated frequently. And what about the problem of one cache receiving the `PUT` and knowing to invalidate its cache and another not seeing it?
HTTP protocol supports a request type called "If-Modified-Since" which basically allows the caching server to ask the web-server if the item has changed. HTTP protocol also supports "Cache-Control" headers inside of HTTP server responses which tell cache servers what to do with the content (such as never cache this, or assume it expires in 1 day, etc). Also you mentioned encrypted responses. HTTP cache servers cannot cache SSL because to do so would require them to decrypt the pages as a "man in the middle." Doing so would be technically challenging (decrypt the page, store it, and re-encrypt it for the client) and would also violate the page security causing "invalid certificate" warnings on the client side. It is technically possible to have a cache server do it, but it causes more problems than it solves, and is a bad idea. I doubt any cache servers actually do this type of thing.
In re: [SoapBox](https://stackoverflow.com/questions/433195/im-confused-about-http-caching#433206)'s answer: 1. I think `If-Modified-Since` is the two-stage `GET` I suggested at the end of my question. It seems like an OK solution where the content is large (i.e. where the cost of doubling the number of requests, and thus the overhead is overcome by the gains of not re-sending content. That isn't true in my example of Farms, since each Farm's information is short.) 2. It is perfectly reasonable to build a system that sends encrypted content over an unencrypted (HTTP) channel. Imagine the scenario of a Service Oriented Architecture where updates are infrequent and `GET`s are (a) frequent, (b) need to be *extremely* fast, and (c) must be encrypted. You would build a server that requires a `FROM` header (or, equivalently, an API key in the request parameters), and sends back an asymmetrically-encrypted version of the content for the requester. Asymmetric encryption is slow, but if properly cached, beats the combined SSL handshake (asymmetric encryption) and symmetric content encryption. Adding a cache in front of this server would dramatically speed up `GET`s. 3. A caching server could reasonably cache HTTPS GETs for a short period of time. My bank might put a cache-control of about 5 minutes on my account home page and recent transactions. I'm not terribly likely to spend a long time on the site, so sessions won't be very long, and I'll probably end up hitting my account's main page several times while I'm looking for that check I recently sent of to [SnorgTees](http://www.snorgtees.com/).
I understand that react doesn't update state immediately then can someone tell me how i can log this state synchronously as my state is not a boolean and this answer didn't help me [setState doesn't update the state immediately](https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately). Also i don't understand why after clicking on prev button it increments the value first and then it decrements ``` class A extends Component { constructor(props) { super(props); this.state = { value: 1 } } handleNext() { this.setState(prevState => ({ value: prevState.value + 1 })); console.log(this.state.value); } handlePrev() { if(this.state.value > 1) { this.setState(prevState => ({ value: prevState.value - 1 })); } console.log(this.state.value); } render() { <Button bsStyle="primary" id="prev" onClick={() => this.handlePrev()}>Prev</Button> <Button bsStyle="primary" id="next" onClick={() => this.handleNext()}>Next</Button> } ```
`setState` takes a callback as its second argument. ``` handleNext() { this.setState(prevState => ({ value: prevState.value + 1 }),() => console.log('updated', this.state.value)); } ```
You code is fine, try printing `this.state.value` in your render function. Example: ``` class A extends Component { constructor(props) { super(props); this.state = { value: 1, }; } handleNext() { this.setState(prevState => ({ value: prevState.value + 1, })); } handlePrev() { if (this.state.value > 1) { this.setState(prevState => ({ value: prevState.value - 1, })); } } render() { const { value } = this.state; return ( <div> <h2>{ value }</h2> <button id="prev" onClick={() => this.handlePrev()}>Prev</button> <button id="next" onClick={() => this.handleNext()}>Next</button> </div> ); } } ``` It seems like your `handlePrev` is incrementing then decrementing because you're constantly printing the previous state. So when you decrement you are printing the result of the previous increment. ``` |---------------------|-------------------------| | Current State | Your console.log | |---------------------|-------------------------| | 1 | | init |---------------------|-------------------------| | 2 | 1 | increment |---------------------|-------------------------| | 3 | 2 | increment |---------------------|-------------------------| | 2 | 3 | decrement |---------------------|-------------------------| ```
Here's a problem. I have my models: ``` class Collection < ActiveRecord::Base has_many :collection_ownerships has_many :items has_many :users, :through => :collection_ownerships validates :title, presence: true, length: { maximum: 25 } validates :description, length: { maximum: 100 } end class Item < ActiveRecord::Base belongs_to :collection has_many :item_ownerships, :dependent => :destroy accepts_nested_attributes_for :item_ownerships validates :name, :presence => true, length: { maximum: 50 } validates :collection, :presence => true end class ItemOwnership < ActiveRecord::Base belongs_to :item belongs_to :user validates :user, :presence => true validates :item, :presence => true end ``` Here is my controller code: ``` before_filter(:except => :toggle_item_owned_state) do @collection = current_user.collections.find(params[:collection_id]) end def new @item = @collection.items.new @item_ownership = @item.item_ownerships.build(:owned => true, :user => current_user, :item => @item) end def create @item = @collection.items.new(item_params) @item_ownership = @item.item_ownerships.build(:owned => false, :user => current_user, :item => @item) if @item.save redirect_to collection_items_path(@collection) else flash.now[:alert] = "There was a problem saving this item." render "new" end end ``` I have a couple of controller tests: ``` describe 'POST#create' do context "with bad data" do it "should not create a new record for 'items'" do expect { post :create, :collection_id => batman_collection.id, :item => { :name => '', :item_ownership_attributes => { :owned => '1'} } }.to change(Item,:count).by(0) end it "should not create new record 'item_ownerships'" do expect { post :create, :collection_id => batman_collection.id, :item => { :name => 'item_name', :item_ownership_attributes => { :owned => '1'} } }.to change(ItemOwnership,:count).by(0) end end end ``` When I run my tests, the second one fails: ``` 1) ItemsController authenticated user POST#create with bad data should not create new record 'item_ownerships' Failure/Error: expect { post :create, :collection_id => batman_collection.id, expected #count to have changed by 0, but was changed by 1 # ./spec/controllers/items_controller_spec.rb:62:in `block (5 levels) in <top (required)>' ``` And ultimately this reflects in the view as well. Now, when I look in the db, I don't see the record created. I assume this his happening because somehow Count is reflecting the count of objects in memory, not in the db. How can I get a handle on the situation. The problem manifests itself in that when the form is submitted for populating the validation fails for Item, however, multiple instances of ItemOwnership end up showing up on form. Thanks
The error is probably that you are sending through a blocked port. The default port for `sendmail` is 25. If you are at a place where you don't control the servers, try asking a tech guy what server you need to set it as. Here's the command to do so. Add it before the `sendmail()` command `sendmail_options(smtpPort="25")` Change 25 to whatever port your tech guy tells you to.
Try using mailR (<https://cran.r-project.org/web/packages/mailR/index.html>) that supports SMTP authentication.
I'm using this terrible API for a client. It packages HTML/JS to an iPad app. I'm using iScroll but it interferes with the built-in scrolling mechanism. They've provided some code to disable their scrolling, but it only works when loaded after all other scripts have loaded (so the API says). My code structure ``` <head> <script src="scripts1.js"></script> <script src="scripts2.js"></script> <script src="scripts3.js"></script> </head> <body> <script> //some page specific code </script> </body> ``` I'm using some jQuery, but their API is in plain JavaScript. How do I execute their code at the very end? I tried putting it at the end of of the page, but that didn't work. Not sure if using timeout is appropriate?
You can use [JQuery.getScript](http://api.jquery.com/jQuery.getScript/) and in the success function get other scripts. It should look something like this: ``` $.getScript('scriptss1.js', function() { $.getScript('scriptss2.js', function() { $.getScript('scripts3.js', function() { }); }); }); ```
another option would be to add the defer attribute ``` <script src="scripts1.js" defer="defer"></script> <script src="scripts2.js" defer="defer"></script> <script src="scripts3.js" defer="defer"></script> ``` see <http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#attr-script-defer>
I am creating a form and for what ever reason, when using a `bindOnLoad` with a remote CFC, my default value doesn't seem to appear. Here is the cfselect: ``` <cfselect name="edcs" id="edcs" multiple="false" bind="cfc:Components.requestSearch.getEDCs()" bindonload="true" value="edc_nm" display="edc_nm"> <option name="">Select an EDC</option> </cfselect> ``` And here is the function: ``` <cffunction name="getEDCs" access="remote" returntype="query"> <cfscript> var queryService = new Query(); queryService.setDatasource("#APPLICATION.db2system#"); queryService.setName("getEDCs"); queryService.setUserName("#APPLICATION.db2logon#"); queryService.setPassword("#APPLICATION.db2pass#"); queryService.setSQL( "select distinct rtrim(edc_nm) as edc_nm from #APPLICATION.db2owner#.pms_account"); var result = queryService.execute(); var edcs = result.getResult(); return("#edcs#"); </cfscript> </cffunction> ``` So, when the page loads I see the `<option ...>` value displayed for a split second and then the list gets populated, and the `Select an ECD` disappears. I need to have a choice for a null value, which is what the option is for. What am I doing wrong? Thanks. Addition: According to the CF10 docs, I should be able to use the `<option>` html tag. <http://help.adobe.com/en_US/ColdFusion/10.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7afe.html>
I've run across this issue with CFSELECTs and binding CFCs. I have also been unable to add an `<option></option>` tag with a bound CFSELECT. The best way would be to create the query and force the result to have the desired input on the top. For example: ``` SELECT distinct rtrim(edc_nm) as edc_nm_display, rtrim(edc_nm) as edc_nm_value FROM #APPLICATION.db2owner#.pms_account UNION SELECT 'Select an EDC' as edc_nm_display, '0' as edc_nm_value FROM dual ORDER BY 2 ``` This will return your query with 'Select an EDC' on the top. Also, as a check, I believe `<option name="">Select an EDC</option>` should be `<option value="">Select an EDC</option>`. I hope that helps.
The query will need to return that value. Try adding it as a UNION statement.
How do I fetch data from db using select query in a function? Example ``` function ec_select_query($student, $row = '', $fields=array()) { $qry = "SELECT * FROM student"; $qry = mysql_query($qry); while($row = mysql_fetch_assoc($qry)){} return $row; } ```
If you want to return all rows then first save it in an array in while loop then return this array. ``` function ec_select_query($student,$row='',$fields=array()) { $qry = "SELECT * FROM student"; $qry = mysql_query($qry); $result = array(); while($row = mysql_fetch_assoc($qry)) { $result[] = $row; } return $result; } ```
This code might help you : ``` function ec_select_query($student,$row='',$fields=array()) { $q = "SELECT * FROM student"; $q = mysql_query($qry); while($row = mysql_fetch_array($qry)) { return $row; } } ```
In a iPython notebook, I have a while loop that listens to a Serial port and `print` the received data in real time. What I want to achieve to only show the latest received data (i.e only one line showing the most recent data. no scrolling in the cell output area) What I need(i think) is to clear the old cell output when I receives new data, and then prints the new data. I am wondering how can I clear old data programmatically ?
You can use [`IPython.display.clear_output`](http://ipython.org/ipython-doc/dev/api/generated/IPython.display.html#IPython.display.clear_output) to clear the output of a cell. ``` from IPython.display import clear_output for i in range(10): clear_output(wait=True) print("Hello World!") ``` At the end of this loop you will only see one `Hello World!`. Without a code example it's not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell's output and print the buffer again.
**Simple**, if you want to clear the output of that current cell only just use this at the end of that cell ``` from IPython.display import clear_output clear_output(wait=False) ```
I'm writing a program in C, that is supposed to read arrays of doubles from files of arbitrary length. How to stop it at EOF? I've tried using feof, but then read the discussions: [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) [How does C handle EOF?](https://stackoverflow.com/questions/15859041/how-does-c-handle-eof) Then again they concern strings, not numbers. So when reading a file of the form "4 23.3 2 1.2", how to state the loop condition, so that my array A has all the numbers from the file and nothing more (also the iterator N = length of A)? Here's the part of my code with feof, which produces one entry too many in A. The reallocation part is based on <http://www.cplusplus.com/reference/cstdlib/realloc/> example. ``` int N = 0; double *A = NULL; double *more_space; double buff = 0; FILE *data; data = fopen(data.dat,"r"); while(feof(data) == 0) { fscanf(data, "%lg", &buff); more_space = realloc(A, (N+1)*sizeof(double)); A = more_space; A[N] = buff; N++; } ```
The return value of fscanf is -1 when you hit eof (or other problems) so try `while(fscanf(…) >= 0)` for your outer loop. (Whether you accept a zero return value or not depends on how you want to handle bad data -- as other posters have pointed out, you will get 0 if no numbers are converted. I like using the 'greater than or equals' test (instead of testing for `==1`) because it doesn't break if you change the scanf format to, say, read two items from the input line. On the other hand, you could argue that it's better to verify that you always read exactly the correct number of arguments, and it's better to have your program 'fail fast' as soon as you change the number of scant arguments, than to have some mysterious failure later on, if you get bad input. It's a matter of style, and whether this is throwaway code for an assignment, or production code..
During the scan, save the results of `fscanf()` ``` int cnt; double d; while ((cnt = fscanf("%f", &d)) == 1) { more_space = realloc(A, (N+1)*sizeof(double)); if (more_space == NULL) Handle_MemoryError(); A = more_space; A[N] = buff; N++; } if (cnt == 0) Handle_BadDataError(); ```
In our code in a lot of places, I keep seeing this... ``` containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":childView])) containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":childView])) ``` It just seems redundant to me. I'm wondering if there's a way to combine the formats into a single string; something like this... ``` containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|;V:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":childView])) ``` So is something like this possible?
For sorry you can't use this , but you can try something like this ``` let rr = UIView() rr.backgroundColor = UIColor.red self.view.addSubview(rr) rr.translatesAutoresizingMaskIntoConstraints = false ["H:|-100-[rr]-100-|","V:|-100-[rr]-100-|"].forEach{NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: $0, options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["rr":rr]))} ```
No, unfortunately the syntax doesn't permit this - see the grammar in [the docs](https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage.html) Specifically, the line `<orientation> H|V` means that the value of `orientation` can be `H` or `V` but not both. A good alternative for programmatic autolayout is to use an open source DSL library - two popular examples of which are [Cartography](https://github.com/robb/Cartography) and [Snapkit](https://github.com/SnapKit) I've used both and found them much less fiddly than VFL, and much less verbose than the underlying Apple API
I am looking for a word or phrase for wanting someone to fail, but only to teach them a lesson. It's not easy to explain. For example, when you tell a child, "Don't run down the hill or you will fall," but they continue anyway. To prevent them from doing this in the future on a bigger hill with a much more harsh outcome, you want them to fall so the lesson can be learned.
***once bitten, twice shy*** > > Once hurt, one is doubly cautious in the future. This seemingly old observation, presumably alluding to an animal biting someone, was first recorded in 1894. > > > [The American Heritage® Idioms Dictionary](http://idioms.thefreedictionary.com/Once+bitten,+twice+shy) > > > Variations: [***once burned, twice shy***](http://cprouvost.free.fr/fun/A%20Lire/0198606087.pdf) (or ***wary*** or ***warned***.) > > > ***The burned hand teaches best. After that, advice about fire goes to the heart*** (J.R.R. Tolkien) > > [The Two Towers: Being the Second Part of The Lord of the Rings](https://books.google.fr/books?id=12e8PJ2T7sQC&pg=PA584&lpg=PA584&dq=%22burned+hand+teaches+best.+after+that%22&source=bl&ots=JZ2CPJ0qzP&sig=tBzLDnmvEQ0ar6hJO46jlNNBfts&hl=fr&sa=X&ved=0ahUKEwjFsPHG-8fMAhWDcBoKHZgNCdEQ6AEIIjAD#v=onepage&q=%22burned%20hand%20teaches%20best.%20after%20that%22&f=false) > > >
What about "CORRECTIONAL SUFFERANCE"? I wish him to undergo this correctional sufferance so that he may not falter again. It is no reprisal but revisionary.

ministack-preferences-hf_dpo

this is the mlabonne/ministack-preferences dataset simply renamed for ease of use with trl/axolotl

  • also, I took this opportunity to create a nomic topic model with embeddings/etc created on the prompt column, it's fun to play with
Downloads last month
0