Monitoring the Full Disclosure mailinglist
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
Under what circumstances can I call findViewById with an Options Menu / Action Bar item?
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
I am receiving warning in Facebook Application using PHP SDK
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
How much should a function trust another function
Such debugging is part of the development process and should not be the issue at runtime.
Methods don't trust other methods. They all trust you. That is the process of developing. Fix all bugs. Then methods don't have to "trust". There should be no doubt.
So, write it as it should be. Do not make methods check wether other methods are working correctly. That should be tested by the developer when they wrote that function. If you suspect a method to be not doing what you want, debug it.
PHP array value passes to next row
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
programming a servo thru a barometer
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
conflicting types for 'outchar'
In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:
#include <stdio.h> #include <stdlib.h> void outchar(char ch); int main() { outchar('A'); outchar('B'); outchar('C'); return 0; } void outchar(char ch) { printf("%c", ch); }
Also, you should be specifying the return type of every function. I added that for you.
How can I convert this one line of ActionScript to C#?
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
Uninitialized Constant MessagesController
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
Adding a UISegmentedControl to UITableView
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
How to implement a simple scenario the OO way
You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.
Embed ruby within URL : Middleman Blog
<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %> <i class="fa fa-facebook"> Facebook Share </i> <%end%>
I am assuming that current_article_url
is http://0.0.0.0:4567/link_to_title
How to make a variable accessible outside a function?
Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID
before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.
You have to nest the requests:
$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ obj = name; // sID is only now available! sID = obj.id; console.log(sID); });
Clean up your code!
- Put the second request into a function
- and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
- Remove sID and obj variables -
name.id
is sufficient unless you really need the other variables outside the function.
$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ // We don't need sID or obj here - name.id is sufficient console.log(name.id); doSecondRequest(name.id); }); /// TODO Choose a better name function doSecondRequest(sID) { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){ console.log(stats); }); }
Hapy New Year :)
Jquery assiging class to th in a table
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
Fiddle
How to use a global array in C#?
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
Crop image to specified size and picture location
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
How do I get some variable from another class in Java?
Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.
Better solution without exluding fields from Binding
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
How to correctly write async method?
To get the behavior you want you need to wait for the process to finish before you exit Main()
. To be able to tell when your process is done you need to return a Task
instead of a void
from your function, you should never return void
from a async
function unless you are working with events.
A re-written version of your program that works correctly would be
class Program { static void Main(string[] args) { Debug.WriteLine("Calling DoDownload"); var downloadTask = DoDownloadAsync(); Debug.WriteLine("DoDownload done"); downloadTask.Wait(); //Waits for the background task to complete before finishing. } private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync("http://www.google.com/"); Debug.WriteLine(txt); } }
Because you can not await
in Main()
I had to do the Wait()
function instead. If this was a application that had a SynchronizationContext I would do await downloadTask;
instead and make the function this was being called from async
.
this in equals method
this
is the current Object instance. Whenever you have a non-static method, it can only be called on an instance of your object.
Titlecase all entries into a form_for text field
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
How to do perspective fixing?
The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.
The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.
Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.
Ruby - ignore "exit" in code
loop { begin Bar.new rescue SystemExit p $! #: #<SystemExit: exit> end }
This will print #<SystemExit: exit>
in an infinite loop, without ever exiting.
Keep placeholder text in UITextField on input in IOS
Instead of using the placeholder text, you'll want to set the actual text
property of the field to MM/YYYY, set the delegate of the text field and listen for this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // update the text of the label }
Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.
python variable NameError
Initialize tSize to
tSize = ""
before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.
Pass PDO prepared statement to variables
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
AngularJs directive not updating another directive's scope
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
Where do I put a single filter that filters methods in two controllers in Rails
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
Passing multiple values for same variable in stored procedure
You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.
Split Function Works Great when you are getting One String
containing multiple values but when you are passing Multiple values you need to do something like this....
TABLE TYPE
CREATE TYPE dbo.TYPENAME AS TABLE ( arg int ) GO
Stored Procedure to Accept That Type Param
CREATE PROCEDURE mainValues @TableParam TYPENAME READONLY AS BEGIN SET NOCOUNT ON; --Temp table to store split values declare @tmp_values table ( value nvarchar(255) not null); --function splitting values INSERT INTO @tmp_values (value) SELECT arg FROM @TableParam SELECT * FROM @tmp_values --<-- For testing purpose END
EXECUTE PROC
Declare a variable of that type and populate it with your values.
DECLARE @Table TYPENAME --<-- Variable of this TYPE INSERT INTO @Table --<-- Populating the variable VALUES (331),(222),(876),(932) EXECUTE mainValues @Table --<-- Stored Procedure Executed
Result
╔═══════╗ ║ value ║ ╠═══════╣ ║ 331 ║ ║ 222 ║ ║ 876 ║ ║ 932 ║ ╚═══════╝
grep's at sign caught as whitespace
After some time with Google I asked on the ask ubuntu chat room.
A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:
grep -P "(^|\s)abc(\s|$)"
gives the result I was looking for. -P is an experimental implementation of perl regexps.
grepping for abc
and then using filters like grep -v '@abc'
(this is far from perfect...) should also work, but my patch does something similar.
Hide Signs that Meteor.js was Used
The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.
That being said, I suggest looking at buildwith.com
You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.
Gradle - Move a folder from ABC to XYZ
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
C# - insert values from file into two arrays
var Text = File.ReadAllLines("Path"); foreach (var i in Text) { var SplitText = i.Split().Where(x=> x.Lenght>1).ToList(); //@Array1 add SplitText[0] //@Array2 add SpliteText[1] }
Implement specialization in ER diagram
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
Comparing a variable with a string python not working when redirecting from bash script
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
getting " (1) no such column: _id10 " error
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
Accessing AppDelegate from framework?
If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?
Xml Parsing in C#
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
Does the target directory for a git clone have to match the repo name?
Yes, it is possible:
git clone https://github.com/pitosalas/st3_packages Packages
You can specify the local root directory when using git clone.
<directory>
The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo
for /path/to/repo.git
and foo
for host.xz:foo/.git
).
Cloning into an existing directory is only allowed if the directory is empty.
As Chris comments, you can then rename that top directory.
Git only cares about the .git
within said top folder, which you can get with various commands:
git rev-parse --show-toplevel git rev-parse --git-dir
When to create variables (memory management)
I've heard that you must set a variable to 'null' once you're done using it so the garbage collector can get to it (if it's a field var).
This is very rarely a good idea. You only need to do this if the variable is a reference to an object which is going to live much longer than the object it refers to.
Say you have an instance of Class A and it has a reference to an instance of Class B. Class B is very large and you don't need it for very long (a pretty rare situation) You might null
out the reference to class B to allow it to be collected.
A better way to handle objects which don't live very long is to hold them in local variables. These are naturally cleaned up when they drop out of scope.
If I were to have a variable that I won't be referring to agaon, would removing the reference vars I'm using (and just using the numbers when needed) save memory?
You don't free the memory for a primitive until the object which contains it is cleaned up by the GC.
Would that take more space than just plugging '5' into the println method?
The JIT is smart enough to turn fields which don't change into constants.
Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory
Use a memory profiler instead of chasing down 4 bytes of memory. Something like 4 million bytes might be worth chasing if you have a smart phone. If you have a PC, I wouldn't both with 4 million bytes.
OS X Sprite Kit Game Optimal Default Window Size
You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.
Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.
You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.
The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.
You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.
Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.
But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).
You should provide @2x images for the Retina Macbook Pro and future Retina Macs.
How to get parameter value for date/time column from empty MaskedTextBox
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
How to create a showdown.js markdown extension
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
Parse error: syntax error, unexpected [
Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "]
with array("title" => "Welcome ")
Please help me convert this script to a simple image slider
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
http://jsfiddle.net/RmF57/
String method cannot be found in a main class method
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
Intermediate language used in scalac?
The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/
You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.
Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?
Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.
Warp \ bend effect on a UIView?
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
Why there is this "clear" class before footer?
A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:
.clear { height: 50px; width: 25px; }
Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both;
attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:
.clear { clear: both; }
Generic XSLT Search and Replace template
Here's one way in XSLT 2
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"','''')"/> </xsl:template> </xsl:stylesheet>
Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:variable name="apos">'</xsl:variable> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"',$apos)"/> </xsl:template> </xsl:stylesheet>
Are all Spring Framework Java Configuration injection examples buggy?
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
Use NSInteger as array index
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
Zipping a file in bash fails
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
Read input from a JOptionPane.showInputDialog box
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
strange error in my Animation Drawable
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
Two Page Login with Spring Security 3.2.x
There should be three pages here:
- Initial login page with a form that asks for your username, but not your password.
- You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
- A page after that that displays the security image and asks for the password.
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
How do I hide the PHP explode delimiter from submitted form results?
You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.
$fh = fopen("employees.txt", "r"); if ($fh) { while (($line = fgets($fh)) !== false) { $line = trim($line); echo "<option value='".$line."'>".$line."</option>"; } } else { // error opening the file, do something }
Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?
And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.
Problems with installation of Google App Engine SDK for php in OS X
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
How is VIP swapping + CNAMEs better than IP swapping + A records?
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
Access And/Or exclusions
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
Querying date field in MongoDB with Mongoose
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
Uploading into folder in FTP?
The folder is part of the URL you set when you create request
: "ftp://www.contoso.com/test.htm"
. If you use "ftp://www.contoso.com/wibble/test.htm"
then the file will be uploaded to a folder named wibble
.
You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory
to make the wibble
folder if it doesn't already exist.
Getting all files in directory with ajax
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
how to put image in a bundle and pass it to another activity
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
Call japplet from jframe
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
FragmentActivity to Fragment
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
Real time face detection OpenCV, Python
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
vagrant primary box defined but commands still run against all boxes
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
500 Error on AppHarbor but downloaded build works on my machine
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
Are these methods thread safe?
It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.
Laravel 4 with Sentry 2 add user to a group on Registration
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
Drag and drop menuitems
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
make UITableViewCell selectable only while editing
Have you tried setting the selection properties of your tableView like this:
tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES;
If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
in your UITableView delegate. The documentation states:
Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You can have this method return nil in cases where you don't want the selection to happen.
Rails 2.3.4 Persisting Model on Validation Failure
In your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?
From the docs:
_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.
So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.
Edit: Further reading led me here:
http://www.analyticsmarket.com/blog/edit-ecommerce-data
Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.
Comparing two joda DateTime instances
DateTime
inherits its equals
method from AbstractInstant
. It is implemented as such
public boolean equals(Object readableInstant) { // must be to fulfil ReadableInstant contract if (this == readableInstant) { return true; } if (readableInstant instanceof ReadableInstant == false) { return false; } ReadableInstant otherInstant = (ReadableInstant) readableInstant; return getMillis() == otherInstant.getMillis() && FieldUtils.equals(getChronology(), otherInstant.getChronology()); }
Notice the last line comparing chronology. It's possible your instances' chronologies are different.
How do I show a message in the foreach loop?
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
xlrd.biffh.XLRDError: Excel xlsx file; not supported
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
Target class controller does not exist - Laravel 8
On a freshly installed laravel 8, in the App/Providers/RouteServices.php
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* @var string
*/
public const HOME = '/home';
/**
* The controller namespace for the application.
*
* When present, controller route declarations will automatically be prefixed with this namespace.
*
* @var string|null
*/
// protected $namespace = 'App\\Http\\Controllers';
uncomment the
protected $namespace = 'App\Http\Controllers';
that should help you run laravel the old fashioned way.
Incase you are upgrading from lower versions of laravel to 8 then you might have to implicitly add the
protected $namespace = 'App\Http\Controllers';
in the RouteServices.php file for it to function the old way.
DevTools failed to load SourceMap: Could not load content for chrome-extension
Right: it has nothing to do with your code. I've found two valid solutions to this warning (not just disabling it). To better understand what a SourceMap is, I suggest you check out this answer, where it explains how it's something that helps you debug:
The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.
First solution: apparently, Mr Heelis was the closest one: you should add the .map file and there are some tools that help you with this problem (Grunt, Gulp and Google closure for example, quoting the answer). Otherwise you can download the .map file from official sites like Bootstrap, jquery, font-awesome, preload and so on.. (maybe installing things like popper or swiper by the npm command in a random folder and copying just the .map file in your js/css destination folder)
Second solution (the one I used): add the source files using a CDN (here all the advantages of using a CDN). Using the Content delivery network (CDN) you can simply add the cdn link, instead of the path to your folder. You can find cdn on official websites (Bootstrap, jquery, popper, etc..) or you can easily search on some websites like cloudflare, cdnjs, etc..
When adding a Javascript library, Chrome complains about a missing source map, why?
In my case I had to remove React Dev Tools from Chrome to stop seeing the strange errors during development of React app using a local Express server with a create-react-app client (which uses Webpack).
In the interest of community I did a sanity check and quit everything - server/client server/Chrome - and then I opened Chrome and reinstalled React Dev Tools... Started things back up and am seeing this funky address and error again:
error TS1086: An accessor cannot be declared in an ambient context in Angular 9
According to your package.json, you're using Angular 8.3, but you've imported angular/cdk v9. You can downgrade your angular/cdk version or you can upgrade your Angular version to v9 by running:
ng update @angular/core @angular/cli
That will update your local angular version to 9. Then, just to sync material, run:
ng update @angular/material
Maven dependencies are failing with a 501 error
For all the corporate coders, ideally,
if you get this error, it means that your code base is still being built from open-source community. You need to over ride the "central" repository with your in house company Maven repository manager.
You can go to your settings.xml and override your central repository URL from http:// to https://
<M2_HOME>/conf/settings.xml
Find the mirrors sections and add the following entry:
<mirror>
<id>other-mirror</id>
<name>Other Mirror Repository</name>
<url>https://other-mirror.repo.other-company.com/maven2</url>
<mirrorOf>central</mirrorOf>
</mirror>
In the URL section, if you were using either http://repo1.maven.org/maven2/ or http://repo.maven.apache.org/maven2/ then
Replace http://repo1.maven.org/maven2/ with https://repo1.maven.org/maven2/
Replace http://repo.maven.apache.org/maven2/ with https://repo.maven.apache.org/maven2/
You need to ideally use your company source control management/repository URL over here. As this will block any contact with open source Maven repository community.
As mentioned in other answers, effective from 15 January 2020, the central Maven repository doesn't support insecure communication over plain HTTP.
IntelliJ: Error:java: error: release version 5 not supported
I add the following code to my pom.xml
file. It solved my problem.
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
Replace specific text with a redacted version using Python
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
Message: Trying to access array offset on value of type null
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
Array and string offset access syntax with curly braces is deprecated
It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.
Let's say you have something like this in your code:
$str = "test";
echo($str{0});
since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:
$str = "test";
echo($str[0]);
Fixing the code in the question will look something like this:
public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
$records = $this->listRecords($zoneID, $type, $name);
if (isset($records->result[0]->id)) {
return $records->result[0]->id;
}
return false;
}
Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error
This is really a set of configurations for your editor to understand Laravel.
If you want to configure it all manually, here is the repo. This is for both VS code and PhpStorm.
Or if you want you can download this package.(I created) recommended to install it globally.
And then just run andylaravel setupIDE
. this will configure everything for you according to the fist repo.
SyntaxError: Cannot use import statement outside a module
Tried with all the methods but nothing worked
I got one reference from git hub.
To use type script imports with nodejs, i installed below packages.
1. npm i typescript
2. npm i ts-node
Won't require type: module in package.json
E:g
{
"name": "my-app",
"version": "0.0.1",
"description": "",
"scripts": {
},
"dependencies": {
"knex": "^0.16.3",
"pg": "^7.9.0",
"ts-node": "^8.1.0",
"typescript": "^3.3.4000"
}
}
What's the net::ERR_HTTP2_PROTOCOL_ERROR about?
For several weeks I was also annoyed by this "bug":
net :: ERR_HTTP2_PROTOCOL_ERROR 200
In my case, it occurred on images generated by PHP.
It was at header()
level, and on this one in particular:
header ('Content-Length:'. Filesize($cache_file));
It did obviously not return the exact size, so I deleted it and everything works fine now.
So Chrome checks the accuracy of the data transmitted via the headers, and if it does not correspond, it fails.
EDIT
I found why content-length
via filesize
was being miscalculated: the GZIP
compression is active on the PHP files, so excluding the file in question will fix the problem. Put this code in the .htaccess
:
SetEnvIfNoCase Request_URI ^ / thumb.php no-gzip -vary
It works and we keep the header Content-length
.
How to resolve the error on 'react-native start'
[Quick Answer]
There are a problem with Metro using some NPM and Node versions.
You can fix the problem changing some code in the file \node_modules\metro-config\src\defaults\blacklist.js
.
Search this variable:
var sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
and change to this:
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
Please note that if you run an npm install or a yarn install you need to change the code again.
Server Discovery And Monitoring engine is deprecated
It is important to run your mongod command and keep the server running. If not, you will still be seeing this error.
I attach you my code:
_x000D_
_x000D_
const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient
const connectionURL = 'mongodb://127.0.0.1:27017'
const databaseName = 'task-manager'
MongoClient.connect(connectionURL, {useNewUrlParser: true, useUnifiedTopology: true}, (error, client) => {
if(error) {
return console.log('Error connecting to the server.')
}
console.log('Succesfully connected.')
})
_x000D_
_x000D_
_x000D_
How to prevent Google Colab from disconnecting?
var startColabHandler = function startColabHandler(interval = 60000, enableConnectButton = false) {
console.log("colabHandler - configure - start: " + new Date());
var colabClick = function colabClick() {
console.log("colabHandler - click - start: " + new Date());
if (enableConnectButton === true) {
var button1 = document.querySelector("#top-toolbar > colab-connect-button").shadowRoot.querySelector("#connect");
if (button1) {
button1.click()
}
}
button2 = document.querySelector("html body colab-dialog.yes-no-dialog paper-dialog div.buttons paper-button#ok");
if (button2) {
button2.click()
}
console.log("colabHandler - click - end: " + new Date());
};
var intervalId = setInterval(colabClick, interval);
window.stopColabHandler = function stopColabHandler() {
console.log("colabHandler - stop - start: " + new Date());
clearInterval(intervalId);
console.log("colabHandler - stop - start: " + new Date());
};
console.log("colabHandler - configure - end: " + new Date());
};
"Permission Denied" trying to run Python on Windows 10
Add the path of python folder in environmental variable and it will work
1.search environmental variable
2.look for system variable section and find variable named path in it
3.double click on path and add new path which directs towards python folder and that's it.
the python folder is usually in
C:\Users["user name"]\AppData\Local\Programs\Python\Python39
"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm
After upgrading lots of packages (Spyder
3 to 4, Keras
and Tensorflow
and lots of their dependencies), I had the same problem today! I cannot figure out what happened; but the (conda-based) virtual environment that kept using Spyder
3 did not have the problem. Although installing tkinter
or changing the backend, via matplotlib.use('TkAgg)
as shown above, or this nice post on how to change the backend, might well resolve the problem, I don't see these as rigid solutions. For me, uninstalling matplotlib
and reinstalling it was magic and the problem was solved.
pip uninstall matplotlib
... then, install
pip install matplotlib
From all the above, this could be a package management problem, and BTW, I use both conda
and pip
, whenever feasible.
Make a VStack fill the width of the screen in SwiftUI
With Swift 5.2 and iOS 13.4, according to your needs, you can use one of the following examples to align your VStack
with top leading constraints and a full size frame.
Note that the code snippets below all result in the same display, but do not guarantee the effective frame of the VStack
nor the number of View
elements that might appear while debugging the view hierarchy.
1. Using frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:)
method
The simplest approach is to set the frame of your VStack
with maximum width and height and also pass the required alignment in frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:)
:
struct ContentView: View {
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
}
.frame(
maxWidth: .infinity,
maxHeight: .infinity,
alignment: .topLeading
)
.background(Color.red)
}
}
As an alternative, if setting maximum frame with specific alignment for your View
s is a common pattern in your code base, you can create an extension method on View
for it:
extension View {
func fullSize(alignment: Alignment = .center) -> some View {
self.frame(
maxWidth: .infinity,
maxHeight: .infinity,
alignment: alignment
)
}
}
struct ContentView : View {
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
}
.fullSize(alignment: .topLeading)
.background(Color.red)
}
}
2. Using Spacer
s to force alignment
You can embed your VStack
inside a full size HStack
and use trailing and bottom Spacer
s to force your VStack
top leading alignment:
struct ContentView: View {
var body: some View {
HStack {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
Spacer() // VStack bottom spacer
}
Spacer() // HStack trailing spacer
}
.frame(
maxWidth: .infinity,
maxHeight: .infinity
)
.background(Color.red)
}
}
3. Using a ZStack
and a full size background View
This example shows how to embed your VStack
inside a ZStack
that has a top leading alignment. Note how the Color
view is used to set maximum width and height:
struct ContentView: View {
var body: some View {
ZStack(alignment: .topLeading) {
Color.red
.frame(maxWidth: .infinity, maxHeight: .infinity)
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
}
}
}
}
4. Using GeometryReader
GeometryReader
has the following declaration:
A container view that defines its content as a function of its own size and coordinate space. [...] This view returns a flexible preferred size to its parent layout.
The code snippet below shows how to use GeometryReader
to align your VStack
with top leading constraints and a full size frame:
struct ContentView : View {
var body: some View {
GeometryReader { geometryProxy in
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
}
.frame(
width: geometryProxy.size.width,
height: geometryProxy.size.height,
alignment: .topLeading
)
}
.background(Color.red)
}
}
5. Using overlay(_:alignment:)
method
If you want to align your VStack
with top leading constraints on top of an existing full size View
, you can use overlay(_:alignment:)
method:
struct ContentView: View {
var body: some View {
Color.red
.frame(
maxWidth: .infinity,
maxHeight: .infinity
)
.overlay(
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
},
alignment: .topLeading
)
}
}
Display:
Presenting modal in iOS 13 fullscreen
The above answers and suggestions are right, below is another version, and efficient way using programmatically.
#1 Created a UIView Extension
#2 Created a Method ()
//#1
extension UIViewController {
//#2
func presentLocal(_ viewControllerToPresent: UIViewController, animated flag:
Bool, completion: (() -> Void)? = nil) {
//Reusing below 2 lines :-)
viewControllerToPresent.modalPresentationStyle = .overCurrentContext
self.present(viewControllerToPresent, animated: flag, completion: completion)
}
}
Invoking as below
let vc = MyViewController()
let nc = UINavigationController(rootViewController: vc)
sourceView.presentLocal(nc, animated: true, completion: nil)
OR
let vc = MyViewController()
sourceView.presentLocal(vc, animated: true, completion: nil)
How to style components using makeStyles and still have lifecycle methods in Material UI?
Hi instead of using hook API, you should use Higher-order component API as mentioned here
I'll modify the example in the documentation to suit your need for class component
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';
const styles = theme => ({
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
},
});
class HigherOrderComponentUsageExample extends React.Component {
render(){
const { classes } = this.props;
return (
<Button className={classes.root}>This component is passed to an HOC</Button>
);
}
}
HigherOrderComponentUsageExample.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(HigherOrderComponentUsageExample);
origin 'http://localhost:4200' has been blocked by CORS policy in Angular7
If your project is .net Core 3.1 API project.
update your Startup.cs in your .net core project to:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:53135",
"http://localhost:4200"
)
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddDbContext<CIVDataContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("CIVDatabaseConnection")));
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(MyAllowSpecificOrigins);
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Why am I getting Unknown error in line 1 of pom.xml?
While I cannot reproduce your error (as none of your team mates can either), I have a suggestion, that might help you.
Have you heard of the Byte Order Mark? As it appears on line 1 it is a likely candidate for your troubles. Maybe you changed a setting somewhere that somehow leads to the error. This quote from the Wikipedia article is particularly relevant I think:
BOM use is optional. Its presence interferes with the use of UTF-8 by software that does not expect non-ASCII bytes at the start of a file but that could otherwise handle the text stream.
How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?
This error comes when you have the previous version of torch like 1.6.0 with torchvision==0.7.0,
you may check yours torch version through this command:
import tensorflow
print(tensorflow.__version__)
this error is already resolved in the newer version of torch.
you can remove this error through making the following change in np.load()
np.load(somepath, allow_pickle=True)
The allow_pickle=True will solve it
What is the incentive for curl to release the library for free?
I'm Daniel Stenberg.
I made curl
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Why do I still work on curl?
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
- I can't speak for my fellow project team members. We all participate in this for our own reasons.
- I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
- There are still bugs to fix and features to add!
- curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
- curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
- I would not do it differently if I could back and do it again.
Am I proud of what we've done?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
For real?
Yeah. For real.
Do I ever get tired? Is it ever done?
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function
Do not use arrow function to create functional components.
Do as one of the examples below:
function MyComponent(props) {
const [states, setStates] = React.useState({ value: '' });
return (
<input
type="text"
value={states.value}
onChange={(event) => setStates({ value: event.target.value })}
/>
);
}
Or
//IMPORTANT: Repeat the function name
const MyComponent = function MyComponent(props) {
const [states, setStates] = React.useState({ value: '' });
return (
<input
type="text"
value={states.value}
onChange={(event) => setStates({ value: event.target.value })}
/>
);
};
If you have problems with "ref"
(probably in loops), the solution is to use forwardRef()
:
// IMPORTANT: Repeat the function name
// Add the "ref" argument to the function, in case you need to use it.
const MyComponent = React.forwardRef( function MyComponent(props, ref) {
const [states, setStates] = React.useState({ value: '' });
return (
<input
type="text"
value={states.value}
onChange={(event) => setStates({ value: event.target.value })}
/>
);
});
How to fix missing dependency warning when using useEffect React Hook?
If you aren't using fetchBusinesses method anywhere apart from the effect, you could simply move it into the effect and avoid the warning
useEffect(() => {
const fetchBusinesses = () => {
return fetch("theURL", {method: "GET"}
)
.then(res => normalizeResponseErrors(res))
.then(res => {
return res.json();
})
.then(rcvdBusinesses => {
// some stuff
})
.catch(err => {
// some error handling
});
};
fetchBusinesses();
}, []);
If however you are using fetchBusinesses outside of render, you must note two things
- Is there any issue with you not passing
fetchBusinesses
as a method when it's used during mount with its enclosing closure?
- Does your method depend on some variables which it receives from its enclosing closure? This is not the case for you.
- On every render, fetchBusinesses will be re-created and hence passing it to useEffect will cause issues. So first you must memoize fetchBusinesses if you were to pass it to the dependency array.
To sum it up I would say that if you are using fetchBusinesses
outside of useEffect
you can disable the rule using // eslint-disable-next-line react-hooks/exhaustive-deps
otherwise you can move the method inside of useEffect
To disable the rule you would write it like
useEffect(() => {
// other code
...
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
React Native Error: ENOSPC: System limit for number of file watchers reached
I encountered this issue on a linuxmint distro. It appeared to have happened when there was so many folders and subfolders/files I added to the /public folder in my app.
I applied this fix and it worked well...
$
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
change directory into the /etc folder:
cd /etc
then run this:
sudo systcl -p
You may have to close your terminal and npm start
again to get it to work.
If this fails i recommend installing react-scripts globally and running your application directly with that.
$
npm i -g --save react-scripts
then instead of npm start
run react-scripts start
to run your application.
How to update core-js to core-js@3 dependency?
With this
npm install --save core-js@^3
you now get the error
"core-js@<3 is no longer maintained and not recommended for usage due to the number of
issues. Please, upgrade your dependencies to the actual version of core-js@3"
so you might want to instead try
npm install --save core-js@3
if you're reading this post June 9 2020.
Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?
Based on responses and comments below, the following was the simple solution for my issue and THIS WORKED. Now my app, Match4app, is fully compatible with latest iOS versions!
- Download Xcode 10.2 from a direct link (not from App Store). (Estimated Size: ~6Gb)
- From the downloaded version just copy/paste the DeviceSupport/12.2 directory into "Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport"
- You can discard the downloaded version now (we just need the small 12.2 directory!)
Updating Anaconda fails: Environment Not Writable Error
If you get this error under Linux when running conda using sudo, you might be suffering from bug #7267:
When logging in as non-root user via sudo, e.g. by:
sudo -u myuser -i
conda seems to assume that it is run as root and raises an error.
The only known workaround seems to be: Add the following line to your ~/.bashrc
:
unset SUDO_UID SUDO_GID SUDO_USER
...or unset the ENV variables by running the line in a different way before running conda.
If you mistakenly installed anaconda/miniconda as root/via sudo this can also lead to the same error, then you might want to do the following:
sudo chown -R username /path/to/anaconda3
Tested with conda 4.6.14.
How to set value to form control in Reactive Forms in Angular
The "usual" solution is make a function that return an empty formGroup or a fullfilled formGroup
createFormGroup(data:any)
{
return this.fb.group({
user: [data?data.user:null],
questioning: [data?data.questioning:null, Validators.required],
questionType: [data?data.questionType, Validators.required],
options: new FormArray([this.createArray(data?data.options:null])
})
}
//return an array of formGroup
createArray(data:any[]|null):FormGroup[]
{
return data.map(x=>this.fb.group({
....
})
}
then, in SUBSCRIBE, you call the function
this.qService.editQue([params["id"]]).subscribe(res => {
this.editqueForm = this.createFormGroup(res);
});
be carefull!, your form must include an *ngIf to avoid initial error
<form *ngIf="editqueForm" [formGroup]="editqueForm">
....
</form>
react hooks useEffect() cleanup for only componentWillUnmount?
function LegoComponent() {
const [lego, setLegos] = React.useState([])
React.useEffect(() => {
let isSubscribed = true
fetchLegos().then( legos=> {
if (isSubscribed) {
setLegos(legos)
}
})
return () => isSubscribed = false
}, []);
return (
<ul>
{legos.map(lego=> <li>{lego}</li>)}
</ul>
)
}
In the code above, the fetchLegos function returns a promise. We can “cancel” the promise by having a conditional in the scope of useEffect, preventing the app from setting state after the component has unmounted.
Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
How to use callback with useState hook in react
you can utilize useCallback hook to do this.
function Parent() {
const [name, setName] = useState("");
const getChildChange = useCallback( (updatedName) => {
setName(updatedName);
}, []);
return <div> {name} :
<Child getChildChange={getChildChange} ></Child>
</div>
}
function Child(props) {
const [name, setName] = useState("");
function handleChange(ele) {
setName(ele.target.value);
props.getChildChange(ele.target.value);
}
function collectState() {
return name;
}
return (<div>
<input onChange={handleChange} value={name}></input>
</div>);
}
How can I solve the error 'TS2532: Object is possibly 'undefined'?
For others facing a similar problem to mine, where you know a particular object property cannot be null, you can use the non-null assertion operator (!) after the item in question.
This was my code:
const naciStatus = dataToSend.naci?.statusNACI;
if (typeof naciStatus != "undefined") {
switch (naciStatus) {
case "AP":
dataToSend.naci.certificateStatus = "FALSE";
break;
case "AS":
case "WR":
dataToSend.naci.certificateStatus = "TRUE";
break;
default:
dataToSend.naci.certificateStatus = "";
}
}
And because dataToSend.naci
cannot be undefined in the switch statement, the code can be updated to include exclamation marks as follows:
const naciStatus = dataToSend.naci?.statusNACI;
if (typeof naciStatus != "undefined") {
switch (naciStatus) {
case "AP":
dataToSend.naci!.certificateStatus = "FALSE";
break;
case "AS":
case "WR":
dataToSend.naci!.certificateStatus = "TRUE";
break;
default:
dataToSend.naci!.certificateStatus = "";
}
}
The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1
The problem is in your pod files deployment target iOS Version not in your project deployment target iOS Version, so you need to change the deployment iOS version for your pods as well to anything higher than 8.0 to do so open your project workspace and do this:
1- Click on pods.
2- Select each project and target and click on build settings.
3- Under Deployment section change the iOS Deployment Target version to anything more than 8.0
(better to try the same project version).
4- Repeat this for every other project in your pods then run the app.
see the photo for details
Flutter Countdown Timer
If all you need is a simple countdown timer, this is a good alternative instead of installing a package. Happy coding!
countDownTimer() async {
int timerCount;
for (int x = 5; x > 0; x--) {
await Future.delayed(Duration(seconds: 1)).then((_) {
setState(() {
timerCount -= 1;
});
});
}
}
Typescript: Type 'string | undefined' is not assignable to type 'string'
As of TypeScript 3.7 you can use nullish coalescing operator ??
. You can think of this feature as a way to “fall back” to a default value when dealing with null or undefined
let name1:string = person.name ?? '';
The ??
operator can replace uses of ||
when trying to use a default value and can be used when dealing with booleans, numbers, etc. where ||
cannot be used.
As of TypeScript 4 you can use ??=
assignment operator as a ??= b
which is an alternative to a = a ?? b;
OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?
Not your code is the problem this is perfectly fine:
gray = cv2.cvtColor(imgUMat, cv2.COLOR_RGB2GRAY)
The problem is that imgUMat is None
so you probably made a mistake when loading your image:
imgUMat = cv2.imread("your_image.jpg")
I suspect you just entered the wrong image path.
Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?
I think it's a version problem, you just have to uninstall the old version of composer, then do a new installation of its new version.
apt remove composer
and follow the steps:
- download the composer from its official release site by making use of the following command.
wget https://getcomposer.org/download/1.6.3/composer.phar
- Before you proceed with the installation, you should rename before you install and make it an executable file.
mv composer.phar composer
chmod +x composer
- Now install the package by making use the following command.
./composer
- The composer has been successfully installed now, make it access globally using the following command.
for Ubuntu 16
mv composer /usr/bin/
for Ubuntu 18
mv composer /usr/local/bin/
JS file gets a net::ERR_ABORTED 404 (Not Found)
As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().
Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static
for the example. Once it's done, add this line in your server code:
app.use("/static", express.static('./static/'));
This will effectively serve every file in your "static" folder via the /static route.
Querying your index.js file in the client thus becomes:
<script src="static/index.js"></script>
Error: Java: invalid target release: 11 - IntelliJ IDEA
Got this same error after updating my Idea and I resolved it as follows:
File >> Project Structure... >> Project
“Project language level:” was set to “11 - Local variable syntax for lambda parameters”
so I changed it to “SDK default (8 - Lambdas, type annotations etc.)” then applied the change
and the error was resolved.
useState set method not reflecting change immediately
// replace
return <p>hello</p>;
// with
return <p>{JSON.stringify(movies)}</p>;
Now you should see, that your code actually does work. What does not work is the console.log(movies)
. This is because movies
points to the old state. If you move your console.log(movies)
outside of useEffect
, right above the return, you will see the updated movies object.
Parsing Query String in node.js
There's also the QueryString module's parse()
method:
var http = require('http'),
queryString = require('querystring');
http.createServer(function (oRequest, oResponse) {
var oQueryParams;
// get query params as object
if (oRequest.url.indexOf('?') >= 0) {
oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));
// do stuff
console.log(oQueryParams);
}
oResponse.writeHead(200, {'Content-Type': 'text/plain'});
oResponse.end('Hello world.');
}).listen(1337, '127.0.0.1');
Git - remote: Repository not found
This message can occur when a repository IS found, but we don't have commit access. Not well-worded!
I received the repo-not-found message after cloning a gitHub repository created for me by my boss. I could clone and commit locally, but could not push commits upstream. The repository owner had not given me write access. Solved by a plea for write access to the repo owner.
JUnit Testing private variables?
I can't tell if you've found some special case code which requires you to test against private fields. But in my experience you never have to test something private - always public. Maybe you could give an example of some code where you need to test private?
C# Interfaces. Implicit implementation versus Explicit implementation
Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo
would be implicitly implemented as:
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
and explicitly as:
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.
MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.
I am sure there are more reasons to use/not use explicit that others will post.
See the next post in this thread for excellent reasoning behind each.
Named parameters in JDBC
Vanilla JDBC only supports named parameters in a CallableStatement
(e.g. setString("name", name)
), and even then, I suspect the underlying stored procedure implementation has to support it.
An example of how to use named parameters:
//uss Sybase ASE sysobjects table...adjust for your RDBMS
stmt = conn.prepareCall("create procedure p1 (@id int = null, @name varchar(255) = null) as begin "
+ "if @id is not null "
+ "select * from sysobjects where id = @id "
+ "else if @name is not null "
+ "select * from sysobjects where name = @name "
+ " end");
stmt.execute();
//call the proc using one of the 2 optional params
stmt = conn.prepareCall("{call p1 ?}");
stmt.setInt("@id", 10);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(1));
}
//use the other optional param
stmt = conn.prepareCall("{call p1 ?}");
stmt.setString("@name", "sysprocedures");
rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(1));
}
Is it possible to override / remove background: none!important with jQuery?
With a <script>
right after the <style>
that applies the !important
things, you should be able to do something like this:
var lastStylesheet = document.styleSheets[document.styleSheets.length - 1];
lastStylesheet.disabled = true;
document.write('<style type="text/css">');
// Call fixBackground for each element that needs fixing
document.write('</style>');
lastStylesheet.disabled = false;
function fixBackground(el) {
document.write('html #' + el.id + ' { background-image: ' +
document.defaultView.getComputedStyle(el).backgroundImage +
' !important; }');
}
This probably depends on what kind of browser compatibility you need, though.
How to round up integer division and have int result in Java?
To round up an integer division you can use
import static java.lang.Math.abs;
public static long roundUp(long num, long divisor) {
int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}
or if both numbers are positive
public static long roundUp(long num, long divisor) {
return (num + divisor - 1) / divisor;
}
Using Apache POI how to read a specific excel column
Okay, from your question, you just simply want to read a particular column. So, while iterating over a row and then on its cells, your can simply check the index of the column.
Iterator<Row> rowIterator = mySheet.iterator(); // Traversing over each row of XLSX file
while (rowIterator.hasNext()) {
Row row = rowIterator.next(); // For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
println "column index"+cell.getColumnIndex()//You will have your columns fixed in Excel file
if(cell.getColumnIndex()==3)//for example of c
{
print "done"
}
}
}
I am using POI 3.12-- 'org.apache.poi:poi:3.12'
Hope it helps. Cheers!
How do I wait for an asynchronously dispatched block to finish?
There’s also SenTestingKitAsync that lets you write code like this:
- (void)testAdditionAsync {
[Calculator add:2 to:2 block^(int result) {
STAssertEquals(result, 4, nil);
STSuccess();
}];
STFailAfter(2.0, @"Timeout");
}
(See objc.io article for details.) And since Xcode 6 there’s an AsynchronousTesting
category on XCTest
that lets you write code like this:
XCTestExpectation *somethingHappened = [self expectationWithDescription:@"something happened"];
[testedObject doSomethigAsyncWithCompletion:^(BOOL succeeded, NSError *error) {
[somethingHappened fulfill];
}];
[self waitForExpectationsWithTimeout:1 handler:NULL];
Which TensorFlow and CUDA version combinations are compatible?
The compatibility table given in the tensorflow site does not contain specific minor versions for cuda and cuDNN. However, if the specific versions are not met, there will be an error when you try to use tensorflow.
For tensorflow-gpu==1.12.0
and cuda==9.0
, the compatible cuDNN
version is 7.1.4
, which can be downloaded from here after registration.
You can check your cuda version using
nvcc --version
cuDNN version using
cat /usr/include/cudnn.h | grep CUDNN_MAJOR -A 2
tensorflow-gpu version using
pip freeze | grep tensorflow-gpu
UPDATE:
Since tensorflow 2.0, has been released, I will share the compatible cuda and cuDNN versions for it as well (for Ubuntu 18.04).
tensorflow-gpu
= 2.0.0
cuda
= 10.0
cuDNN
= 7.6.0
How do you convert Html to plain text?
public static string StripTags2(string html)
{
return html.Replace("<", "<").Replace(">", ">");
}
By this you escape all "<" and ">" in a string. Is this what you want?
How to print out a variable in makefile
This can be done in a generic way and can be very useful when debugging a complex makefile. Following the same technique as described in another answer, you can insert the following into any makefile:
# if the first command line argument is "print"
ifeq ($(firstword $(MAKECMDGOALS)),print)
# take the rest of the arguments as variable names
VAR_NAMES := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS))
# turn them into do-nothing targets
$(eval $(VAR_NAMES):;@:))
# then print them
.PHONY: print
print:
@$(foreach var,$(VAR_NAMES),\
echo '$(var) = $($(var))';)
endif
Then you can just do "make print" to dump the value of any variable:
$ make print CXXFLAGS
CXXFLAGS = -g -Wall
Python socket receive - incoming packets always have a different size
I know this is old, but I hope this helps someone.
Using regular python sockets I found that you can send and receive information in packets using sendto and recvfrom
# tcp_echo_server.py
import socket
ADDRESS = ''
PORT = 54321
connections = []
host = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host.setblocking(0)
host.bind((ADDRESS, PORT))
host.listen(10) # 10 is how many clients it accepts
def close_socket(connection):
try:
connection.shutdown(socket.SHUT_RDWR)
except:
pass
try:
connection.close()
except:
pass
def read():
for i in reversed(range(len(connections))):
try:
data, sender = connections[i][0].recvfrom(1500)
return data
except (BlockingIOError, socket.timeout, OSError):
pass
except (ConnectionResetError, ConnectionAbortedError):
close_socket(connections[i][0])
connections.pop(i)
return b'' # return empty if no data found
def write(data):
for i in reversed(range(len(connections))):
try:
connections[i][0].sendto(data, connections[i][1])
except (BlockingIOError, socket.timeout, OSError):
pass
except (ConnectionResetError, ConnectionAbortedError):
close_socket(connections[i][0])
connections.pop(i)
# Run the main loop
while True:
try:
con, addr = host.accept()
connections.append((con, addr))
except BlockingIOError:
pass
data = read()
if data != b'':
print(data)
write(b'ECHO: ' + data)
if data == b"exit":
break
# Close the sockets
for i in reversed(range(len(connections))):
close_socket(connections[i][0])
connections.pop(i)
close_socket(host)
The client is similar
# tcp_client.py
import socket
ADDRESS = "localhost"
PORT = 54321
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ADDRESS, PORT))
s.setblocking(0)
def close_socket(connection):
try:
connection.shutdown(socket.SHUT_RDWR)
except:
pass
try:
connection.close()
except:
pass
def read():
"""Read data and return the read bytes."""
try:
data, sender = s.recvfrom(1500)
return data
except (BlockingIOError, socket.timeout, AttributeError, OSError):
return b''
except (ConnectionResetError, ConnectionAbortedError, AttributeError):
close_socket(s)
return b''
def write(data):
try:
s.sendto(data, (ADDRESS, PORT))
except (ConnectionResetError, ConnectionAbortedError):
close_socket(s)
while True:
msg = input("Enter a message: ")
write(msg.encode('utf-8'))
data = read()
if data != b"":
print("Message Received:", data)
if msg == "exit":
break
close_socket(s)
Find closest previous element jQuery
I know this is old, but was hunting for the same thing and ended up coming up with another solution which is fairly concise andsimple. Here's my way of finding the next or previous element, taking into account traversal over elements that aren't of the type we're looking for:
var ClosestPrev = $( StartObject ).prevAll( '.selectorClass' ).first();
var ClosestNext = $( StartObject ).nextAll( '.selectorClass' ).first();
I'm not 100% sure of the order that the collection from the nextAll/prevAll functions return, but in my test case, it appears that the array is in the direction expected. Might be helpful if someone could clarify the internals of jquery for that for a strong guarantee of reliability.
Is it possible to preview stash contents in git?
To view a current list of stash:
git stash list
You'll see a list like this:
stash@{0}: WIP on ...
stash@{1}: ...
stash@{2}: ...
...
To view diff on any of those stashes:
git stash show -p stash@{n}
LaTeX "\indent" creating paragraph indentation / tabbing package requirement?
This is kind of a hack but the best solution that I have found is to use a description tag with no \item. This will produce an error from the latex compiler; however, the error does not prevent the pdf from being generated.
\begin{description}
<YOUR TEXT HERE>
\end{description}
- This only worked on windows latex compiler
How can I resolve the error: "The command [...] exited with code 1"?
This builds on the answer from JaredPar... and is for VS2017. The same "Build and Run" options are present in Visual Studio 2017.
I was getting, The command "chmod +x """ exited with code 1
In the build output window, I searched for "Error" and found a few errors in the same general area. I was able to click on a link in the build output, and found that the error involved this entry in the .targets file:
<Target Name="ChmodChromeDriver" BeforeTargets="BeforeBuild" Condition="'$(WebDriverPlatform)' != 'win32'">
<Exec Command="chmod +x "$(ChromeDriverSrcPath)"" />
</Target>
In the build output, I also found a more detailed error message that essentially stated that it couldn't find Selenium.WebDriver.ChromeDriver v2.36 in the packages folder it was looking in. I checked the project's NuGet packages, and version 2.36 was indeed in the list of installed packages. I did find the package files for 2.36, and changed the attributes on the folder, subfolders and files from "Read Only" to "Read/Write". Built, but same failure. Sometimes "updating" to a different version of the package and then updating back to the original can fix this type of error. So I "updated" the reference in Manage NuGet packages to 2.37, built, failed, then "updated" back to 2.36, built, and the build succeeded without the "chmod +x" error message.
The project I was building was based on a Visual Studio Project template for Appium test tooling, template name "Develop_Automated_Test".
Formula to convert date to number
The Excel number for a modern date is most easily calculated as the number of days since 12/30/1899 on the Gregorian calendar.
Excel treats the mythical date 01/00/1900 (i.e., 12/31/1899) as corresponding to 0, and incorrectly treats year 1900 as a leap year. So for dates before 03/01/1900, the Excel number is effectively the number of days after 12/31/1899.
However, Excel will not format any number below 0 (-1 gives you ##########) and so this only matters for "01/00/1900" to 02/28/1900, making it easier to just use the 12/30/1899 date as a base.
A complete function in DB2 SQL that accounts for the leap year 1900 error:
SELECT
DAYS(INPUT_DATE)
- DAYS(DATE('1899-12-30'))
- CASE
WHEN INPUT_DATE < DATE('1900-03-01')
THEN 1
ELSE 0
END
How to Migrate to WKWebView?
WkWebView is much faster and reliable than UIWebview according to the Apple docs.
Here, I posted my WkWebViewController.
import UIKit
import WebKit
class WebPageViewController: UIViewController,UINavigationControllerDelegate,UINavigationBarDelegate,WKNavigationDelegate{
var webView: WKWebView?
var webUrl="http://www.nike.com"
override func viewWillAppear(animated: Bool){
super.viewWillAppear(true)
navigationController!.navigationBar.hidden = false
}
override func viewDidLoad()
{
/* Create our preferences on how the web page should be loaded */
let preferences = WKPreferences()
preferences.javaScriptEnabled = false
/* Create a configuration for our preferences */
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
/* Now instantiate the web view */
webView = WKWebView(frame: view.bounds, configuration: configuration)
if let theWebView = webView{
/* Load a web page into our web view */
let url = NSURL(string: self.webUrl)
let urlRequest = NSURLRequest(URL: url!)
theWebView.loadRequest(urlRequest)
theWebView.navigationDelegate = self
view.addSubview(theWebView)
}
}
/* Start the network activity indicator when the web view is loading */
func webView(webView: WKWebView,didStartProvisionalNavigation navigation: WKNavigation){
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
/* Stop the network activity indicator when the loading finishes */
func webView(webView: WKWebView,didFinishNavigation navigation: WKNavigation){
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
func webView(webView: WKWebView,
decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse,decisionHandler: ((WKNavigationResponsePolicy) -> Void)){
//print(navigationResponse.response.MIMEType)
decisionHandler(.Allow)
}
override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
}
}
Only detect click event on pseudo-element
None of these answers are reliable, and mine wont be much more reliable.
Caveats aside, if you do get into the lucky scenario where the element you're trying to have clicked doesn't have padding (such that all of the "inner" space of the element is completely covered by sub-elements), then you can check the target of the click event against the container itself. If it matches, that means you've clicked a :before or :after element.
Obviously this would not be feasible with both types (before and after) however I have implemented it as a hack/speed fix and it is working very well, without a bunch of position checking, which may be inaccurate depending on about a million different factors.
DateTime to javascript date
This method is working for me:
public sCdateToJsDate(cSDate: any): Date {
// cSDate is '2017-01-24T14:14:55.807'
var datestr = cSDate.toString();
var dateAr = datestr.split('-');
var year = parseInt(dateAr[0]);
var month = parseInt(dateAr[1])-1;
var day = parseInt(dateAr[2].substring(0, dateAr[2].indexOf("T")));
var timestring = dateAr[2].substring(dateAr[2].indexOf("T") + 1);
var timeAr = timestring.split(":");
var hour = parseInt(timeAr[0]);
var min = parseInt(timeAr[1]);
var sek = parseInt(timeAr[2]);
var date = new Date(year, month, day, hour, min, sek, 0);
return date;
}
Python list of dictionaries search
To add just a tiny bit to @FrédéricHamidi.
In case you are not sure a key is in the the list of dicts, something like this would help:
next((item for item in dicts if item.get("name") and item["name"] == "Pam"), None)
Command to get latest Git commit hash from a branch
Try using git log -n 1
after doing a git checkout branchname
. This shows the commit hash, author, date and commit message for the latest commit.
Perform a git pull origin/branchname
first, to make sure your local repo matches upstream.
If perhaps you would only like to see a list of the commits your local branch is behind on the remote branch do this:
git fetch origin
git cherry localbranch remotebranch
This will list all the hashes of the commits that you have not yet merged into your local branch.
Java "lambda expressions not supported at this language level"
Possible Cause #1 (same as the first 3 answers for this question): Project Structure Settings
File > Project Structure > Under Project Settings, go to Project > set Project SDK to 1.8 (with version 65 or above, latest is 112) and set Project Language Level to 8.
File > Project Structure > Under Platform Settings, go to Project > ensure that your JDK home path is set to 1.8 (with version 65 or above, latest is 112).
If the above does not work, check the target bytecode version of your compiler and move on to Possible Cause #2.
Possible Cause #2: Compiler
- File > Settings > Build, Execution, Deployment > Under Compiler, go to Java Compiler > set your Project Bytecode Version to 1.8, as well as all the Target Bytecode Version for your modules. Click Apply and hit OK. Restart your IntelliJ IDE. Lambda expression was accepted in my IDE at this point.
Best wishes :)
Java: Add elements to arraylist with FOR loop where element name has increasing number
I assume Answer
as an Integer data type so in this case, you can easily use Scanner
class for adding the multiple elements(say 50).
private static final Scanner obj = new Scanner(System.in);
private static ArrayList<Integer> arrayList = new ArrayList<Integer>(50);
public static void main(String...S){
for (int i=0;i<50;i++) {
/*Using Scanner class object to take input.*/
arrayList.add(obj.nextInt());
}
/*You can also check the elements of your ArrayList.*/
for (int i=0;i<50;i++) {
/*Using get function for fetching the value present at index 'i'.*/
System.out.print(arrayList.get(i)+" ");
}}
This is a simple and easy method for adding multiple values in an ArrayList using for loop.
As in the above code, I presume the Answer
as Integer it could be String
, Double
, Long
et Cetra. So, in that case, you can use next()
, nextDouble()
, and nextLong()
respectively.
How to hide the title bar for an Activity in XML with existing custom theme
I would like to prefer:-
- AppTheme (Whole app theme)
- AppTheme.NoActionBar (theme without action bar or toolbar)
- AppTheme.NoActionBar.FullScreen (theme without action bar & without status bar)
Theme style like:-
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorDarkPrimary</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="AppTheme">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.NoActionBar.FullScreen" parent="AppTheme.NoActionBar">
<item name="android:windowFullscreen">true</item>
</style>
Also put below code after super.onCreate(savedInstanceState) in onCreate menthod
super.onCreate(savedInstanceState)
this.window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN)
Redirect in Spring MVC
Also note that redirect:
and forward:
prefixes are handled by UrlBasedViewResolver
, so you need to have at least one subclass of UrlBasedViewResolver
among your view resolvers, such as InternalResourceViewResolver
.
split string only on first instance of specified character
Here's one RegExp that does the trick.
'good_luck_buddy' . split(/^.*?_/)[1]
First it forces the match to start from the
start with the '^'. Then it matches any number
of characters which are not '_', in other words
all characters before the first '_'.
The '?' means a minimal number of chars
that make the whole pattern match are
matched by the '.*?' because it is followed
by '_', which is then included in the match
as its last character.
Therefore this split() uses such a matching
part as its 'splitter' and removes it from
the results. So it removes everything
up till and including the first '_' and
gives you the rest as the 2nd element of
the result. The first element is "" representing
the part before the matched part. It is
"" because the match starts from the beginning.
There are other RegExps that work as
well like /_(.*)/ given by Chandu
in a previous answer.
The /^.*?_/ has the benefit that you
can understand what it does without
having to know about the special role
capturing groups play with replace().
How to split string using delimiter char using T-SQL?
For your specific data, you can use
Select col1, col2, LTRIM(RTRIM(SUBSTRING(
STUFF(col3, CHARINDEX('|', col3,
PATINDEX('%|Client Name =%', col3) + 14), 1000, ''),
PATINDEX('%|Client Name =%', col3) + 14, 1000))) col3
from Table01
EDIT - charindex vs patindex
Test
select col3='Clent ID = 4356hy|Client Name = B B BOB|Client Phone = 667-444-2626|Client Fax = 666-666-0151|Info = INF8888877 -MAC333330554/444400800'
into t1m
from master..spt_values a
cross join master..spt_values b
where a.number < 100
-- (711704 row(s) affected)
set statistics time on
dbcc dropcleanbuffers
dbcc freeproccache
select a=CHARINDEX('|Client Name =', col3) into #tmp1 from t1m
drop table #tmp1
dbcc dropcleanbuffers
dbcc freeproccache
select a=PATINDEX('%|Client Name =%', col3) into #tmp2 from t1m
drop table #tmp2
set statistics time off
Timings
CHARINDEX:
SQL Server Execution Times (1):
CPU time = 5656 ms, elapsed time = 6418 ms.
SQL Server Execution Times (2):
CPU time = 5813 ms, elapsed time = 6114 ms.
SQL Server Execution Times (3):
CPU time = 5672 ms, elapsed time = 6108 ms.
PATINDEX:
SQL Server Execution Times (1):
CPU time = 5906 ms, elapsed time = 6296 ms.
SQL Server Execution Times (2):
CPU time = 5860 ms, elapsed time = 6404 ms.
SQL Server Execution Times (3):
CPU time = 6109 ms, elapsed time = 6301 ms.
Conclusion
The timings for CharIndex and PatIndex for 700k calls are within 3.5% of each other, so I don't think it would matter whichever is used. I use them interchangeably when both can work.
Mongoimport of json file
this will work:
$ mongoimport --db databaseName --collection collectionName --file filePath/jsonFile.json
2021-01-09T11:13:57.410+0530 connected to: mongodb://localhost/
2021-01-09T11:13:58.176+0530 1 document(s) imported successfully. 0 document(s) failed to import.
Above I shared the query along with its response
div background color, to change onhover
html code:
<!DOCTYPE html>
<html>
<head><title>this is your web page</title></head>
<body>
<div class = "nicecolor"></div>
</body>
</html>
css code:
.nicecolor {
color:red;
width:200px;
height:200px;
}
.nicecolor:hover {
color:blue;
}
and thats how youll change your div from red to blue by hovering over it.
Generate a sequence of numbers in Python
Write a function that takes a number as an argument and prints the Fibonacci series till that number
def Series(n):
a = 0
b = 1
print(a)
print(b)
S = 0
for i in range(0,n):
if S <= n-1:
S = a + b
print(S)
a = b
b = S
What certificates are trusted in truststore?
Is there any equivalent for the truststore? How can I view the trusted
certificates?
Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)
No other difference
How to get the element clicked (for the whole document)?
event.target
to get the element
window.onclick = e => {
console.log(e.target); // to get the element
console.log(e.target.tagName); // to get the element tag name alone
}
to get the text from clicked element
window.onclick = e => {
console.log(e.target.innerText);
}
How do you dynamically allocate a matrix?
const int nRows = 20;
const int nCols = 10;
int (*name)[nCols] = new int[nRows][nCols];
std::memset(name, 0, sizeof(int) * nRows * nCols); //row major contiguous memory
name[0][0] = 1; //first element
name[nRows-1][nCols-1] = 1; //last element
delete[] name;
Best practice to return errors in ASP.NET Web API
You can use custom ActionFilter in Web Api to validate model:
public class DRFValidationFilters : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
//BadRequest(actionContext.ModelState);
}
}
public override Task OnActionExecutingAsync(HttpActionContext actionContext,
CancellationToken cancellationToken)
{
return Task.Factory.StartNew(() =>
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
});
}
public class AspirantModel
{
public int AspirantId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string AspirantType { get; set; }
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
ErrorMessage = "Not a valid Phone number")]
public string MobileNumber { get; set; }
public int StateId { get; set; }
public int CityId { get; set; }
public int CenterId { get; set; }
[HttpPost]
[Route("AspirantCreate")]
[DRFValidationFilters]
public IHttpActionResult Create(AspirantModel aspirant)
{
if (aspirant != null)
{
}
else
{
return Conflict();
}
return Ok();
}
}
}
Register CustomAttribute class in webApiConfig.cs
config.Filters.Add(new DRFValidationFilters());
MySQL Workbench - Connect to a Localhost
Its Worked for me on Windows
First i installed and started XAMPP Control Panel
Clicked for Start under Actions for MySQL. And below is my Configuration for MySQL (MySQL Workbench 8.0 CE) Connections
And it got connected with Test DataBase
Send file via cURL from form POST in PHP
Here is my solution, i have been reading a lot of post and they was really helpfull, finaly i build a code for small files, with cUrl and Php, that i think its really usefull.
public function postFile()
{
$file_url = "test.txt"; //here is the file route, in this case is on same directory but you can set URL too like "http://examplewebsite.com/test.txt"
$eol = "\r\n"; //default line-break for mime type
$BOUNDARY = md5(time()); //random boundaryid, is a separator for each param on my post curl function
$BODY=""; //init my curl body
$BODY.= '--'.$BOUNDARY. $eol; //start param header
$BODY .= 'Content-Disposition: form-data; name="sometext"' . $eol . $eol; // last Content with 2 $eol, in this case is only 1 content.
$BODY .= "Some Data" . $eol;//param data in this case is a simple post data and 1 $eol for the end of the data
$BODY.= '--'.$BOUNDARY. $eol; // start 2nd param,
$BODY.= 'Content-Disposition: form-data; name="somefile"; filename="test.txt"'. $eol ; //first Content data for post file, remember you only put 1 when you are going to add more Contents, and 2 on the last, to close the Content Instance
$BODY.= 'Content-Type: application/octet-stream' . $eol; //Same before row
$BODY.= 'Content-Transfer-Encoding: base64' . $eol . $eol; // we put the last Content and 2 $eol,
$BODY.= chunk_split(base64_encode(file_get_contents($file_url))) . $eol; // we write the Base64 File Content and the $eol to finish the data,
$BODY.= '--'.$BOUNDARY .'--' . $eol. $eol; // we close the param and the post width "--" and 2 $eol at the end of our boundary header.
$ch = curl_init(); //init curl
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X_PARAM_TOKEN : 71e2cb8b-42b7-4bf0-b2e8-53fbd2f578f9' //custom header for my api validation you can get it from $_SERVER["HTTP_X_PARAM_TOKEN"] variable
,"Content-Type: multipart/form-data; boundary=".$BOUNDARY) //setting our mime type for make it work on $_FILE variable
);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/1.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'); //setting our user agent
curl_setopt($ch, CURLOPT_URL, "api.endpoint.post"); //setting our api post url
curl_setopt($ch, CURLOPT_COOKIEJAR, $BOUNDARY.'.txt'); //saving cookies just in case we want
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); // call return content
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); navigate the endpoint
curl_setopt($ch, CURLOPT_POST, true); //set as post
curl_setopt($ch, CURLOPT_POSTFIELDS, $BODY); // set our $BODY
$response = curl_exec($ch); // start curl navigation
print_r($response); //print response
}
With this we shoud be get on the "api.endpoint.post" the following vars posted
You can easly test with this script, and you should be recive this debugs on the function postFile() at the last row
print_r($response); //print response
public function getPostFile()
{
echo "\n\n_SERVER\n";
echo "<pre>";
print_r($_SERVER['HTTP_X_PARAM_TOKEN']);
echo "/<pre>";
echo "_POST\n";
echo "<pre>";
print_r($_POST['sometext']);
echo "/<pre>";
echo "_FILES\n";
echo "<pre>";
print_r($_FILEST['somefile']);
echo "/<pre>";
}
Here you are it should be work good, could be better solutions but this works and is really helpfull to understand how the Boundary and multipart/from-data mime works on php and curl library,
My Best Reggards,
my apologies about my english but isnt my native language.
How do you create a toggle button?
Try this bit:
input type="button"
data-bind="css:{on:toggleButton, off:toggleButton!=true},value:toggleButton,click: function() { $data.toggleButton(!($data.toggleButton()))}" />
in viewModel
self.toggleButton = ko.observable(false);
Compiling C++ on remote Linux machine - "clock skew detected" warning
Install the Network Time Protocol
This also happened to me when running make
on a Samba SMB CIFS share on a server.
A durable solution consists in installing the ntp
daemon on both the server and the client.
(Please, note that this problem is not solved by running ntpdate
. This would resolve the time difference only temporarily, but not in the future.)
For Ubuntu and Debian-derived systems, simply type the following line at the command line:
$ sudo apt install ntp
Moreover, one will still need to issue the command touch *
once (and only once) in the affected directory to correct the file modification times once and for all.
$ touch *
For more information about the differences between ntp
and ntpdate
, please refer to:
How to validate a file upload field using Javascript/jquery
Building on Ravinders solution, this code stops the form being submitted. It might be wise to check the extension at the server-side too. So you don't get hackers uploading anything they want.
<script>
var valid = false;
function validate_fileupload(input_element)
{
var el = document.getElementById("feedback");
var fileName = input_element.value;
var allowed_extensions = new Array("jpg","png","gif");
var file_extension = fileName.split('.').pop();
for(var i = 0; i < allowed_extensions.length; i++)
{
if(allowed_extensions[i]==file_extension)
{
valid = true; // valid file extension
el.innerHTML = "";
return;
}
}
el.innerHTML="Invalid file";
valid = false;
}
function valid_form()
{
return valid;
}
</script>
<div id="feedback" style="color: red;"></div>
<form method="post" action="/image" enctype="multipart/form-data">
<input type="file" name="fileName" accept=".jpg,.png,.bmp" onchange="validate_fileupload(this);"/>
<input id="uploadsubmit" type="submit" value="UPLOAD IMAGE" onclick="return valid_form();"/>
</form>
JS regex: replace all digits in string
Use
s.replace(/\d/g, "X")
which will replace all occurrences. The g
means global match and thus will not stop matching after the first occurrence.
Or to stay with your RegExp
constructor:
s.replace(new RegExp("\\d", "g"), "X")
How to write data to a JSON file using Javascript
You have to be clear on what you mean by "JSON".
Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]
. This one happens to be an array. If you want to add a new element to the array, just push
it, as in
var arr = [{a: 1}];
arr.push({b: 2});
< [{a: 1}, {b: 2}]
The word JSON may also be used to refer to a string which is encoded in JSON format:
var json = '[{"a": 1}]';
Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse
:
var obj = JSON.parse(json);
Now you can manipulate the object any way you want, including push
as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify
:
var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'
JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse
it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify
, and use another ajax call to send the data to the server for storage or other manipulation.
You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.
Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?
jQuery: get data attribute
This works for me
$('.someclass').click(function() {
$varName = $(this).data('fulltext');
console.log($varName);
});
Executing <script> elements inserted with .innerHTML
Try function eval().
data.newScript = '<script type="text/javascript">//my script...</script>'
var element = document.getElementById('elementToRefresh');
element.innerHTML = data.newScript;
eval(element.firstChild.innerHTML);
This is a real example from a project that i am developing.
Thanks to this post
PHP combine two associative arrays into one array
$array = array(
22 => true,
25 => true,
34 => true,
35 => true,
);
print_r(
array_replace($array, [
22 => true,
42 => true,
])
);
print_r(
array_merge($array, [
22 => true,
42 => true,
])
);
If it is numeric but not sequential associative array, you need to use array_replace
How do I obtain a Query Execution Plan in SQL Server?
You can also do it via powershell using SET STATISTICS XML ON to get the actual plan. I've written it so that it merges multi-statement plans into one plan;
########## BEGIN : SCRIPT VARIABLES #####################
[string]$server = '.\MySQLServer'
[string]$database = 'MyDatabase'
[string]$sqlCommand = 'EXEC sp_ExampleSproc'
[string]$XMLOutputFileName = 'sp_ExampleSproc'
[string]$XMLOutputPath = 'C:\SQLDumps\ActualPlans\'
########## END : SCRIPT VARIABLES #####################
#Set up connection
$connectionString = "Persist Security Info=False;Integrated Security=true;Connection Timeout=0;Initial Catalog=$database;Server=$server"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
#Set up commands
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$command.CommandTimeout = 0
$commandXMLActPlanOn = new-object system.data.sqlclient.sqlcommand("SET STATISTICS XML ON",$connection)
$commandXMLActPlanOff = new-object system.data.sqlclient.sqlcommand("SET STATISTICS XML OFF",$connection)
$connection.Open()
#Enable session XML plan
$result = $commandXMLActPlanOn.ExecuteNonQuery()
#Execute SP and return resultsets into a dataset
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
#Set up output file name and path
[string]$fileNameDateStamp = get-date -f yyyyMMdd_HHmmss
[string]$XMLOutputFilePath = "$XMLOutputPath$XMLOutputFileName`_$fileNameDateStamp.sqlplan"
#Pull XML plans out of dataset and merge into one multi-statement plan
[int]$cntr = 1
ForEach($table in $dataset.Tables)
{
if($table.Columns[0].ColumnName -eq "Microsoft SQL Server 2005 XML Showplan")
{
[string]$fullXMLPlan = $Table.rows[0]."Microsoft SQL Server 2005 XML Showplan"
if($cntr -eq 1)
{
[regex]$rx = "\<ShowPlanXML xmlns\=.{1,}\<Statements\>"
[string]$startXMLPlan = $rx.Match($fullXMLPlan).Value
[regex]$rx = "\<\/Statements\>.{1,}\<\/ShowPlanXML\>"
[string]$endXMLPlan = $rx.Match($fullXMLPlan).Value
$startXMLPlan | out-file -Append -FilePath $XMLOutputFilePath
}
[regex]$rx = "\<StmtSimple.{1,}\<\/StmtSimple\>"
[string]$bodyXMLPlan = $rx.Match($fullXMLPlan).Value
$bodyXMLPlan | out-file -Append -FilePath $XMLOutputFilePath
$cntr += 1
}
}
$endXMLPlan | out-file -Append -FilePath $XMLOutputFilePath
#Disable session XML plan
$result = $commandXMLActPlanOff.ExecuteNonQuery()
$connection.Close()
How do I get the object if it exists, or None if it does not exist?
To make things easier, here is a snippet of the code I wrote, based on inputs from the wonderful replies here:
class MyManager(models.Manager):
def get_or_none(self, **kwargs):
try:
return self.get(**kwargs)
except ObjectDoesNotExist:
return None
And then in your model:
class MyModel(models.Model):
objects = MyManager()
That's it.
Now you have MyModel.objects.get() as well as MyModel.objetcs.get_or_none()
sorting a vector of structs
As others have mentioned, you could use a comparison function, but you can also overload the < operator and the default less<T>
functor will work as well:
struct data {
string word;
int number;
bool operator < (const data& rhs) const {
return word.size() < rhs.word.size();
}
};
Then it's just:
std::sort(info.begin(), info.end());
Edit
As James McNellis pointed out, sort
does not actually use the less<T>
functor by default. However, the rest of the statement that the less<T>
functor will work as well is still correct, which means that if you wanted to put struct data
s into a std::map
or std::set
this would still work, but the other answers which provide a comparison function would need additional code to work with either.
Update span tag value with JQuery
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
docker error - 'name is already in use by container'
The Problem: you trying to create new container while in background container with same name is running and this situation causes conflicts.
The error would be like:
Cannot create continer for service X :Conflict. The name X is already in use by container abc123xyz. You have to remove ot delete (or rename) that container to be able to reuse that name.
Solution rename the service name in docker-compose.yml
or delete the running container and rebuild it again (this solution related to Unix/Linux/macOS systems):
- get all running containers
sudo docker ps -a
- get the specific container id
- stop and remove the duplicated container / force remove it
sudo docker stop <container_id>
sudo docker rm <container_id>
or
sudo docker rm --force <container_id>
How to increase the max upload file size in ASP.NET?
This setting goes in your web.config file. It affects the entire application, though... I don't think you can set it per page.
<configuration>
<system.web>
<httpRuntime maxRequestLength="xxx" />
</system.web>
</configuration>
"xxx" is in KB. The default is 4096 (= 4 MB).
Android draw a Horizontal line between views
It will draw Silver gray colored Line between TextView
& ListView
<TextView
android:id="@+id/textView1"
style="@style/behindMenuItemLabel1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:text="FaceBook Feeds" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#c0c0c0"/>
<ListView
android:id="@+id/list1"
android:layout_width="350dp"
android:layout_height="50dp" />
How to override and extend basic Django admin templates?
Chengs's answer is correct, howewer according to the admin docs not every admin template can be overwritten this way:
https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#overriding-admin-templates
Templates which may be overridden per app or model
Not every template in contrib/admin/templates/admin may be overridden
per app or per model. The following can:
app_index.html
change_form.html
change_list.html
delete_confirmation.html
object_history.html
For those templates that cannot be overridden in this way, you may
still override them for your entire project. Just place the new
version in your templates/admin directory. This is particularly useful
to create custom 404 and 500 pages
I had to overwrite the login.html of the admin and therefore had to put the overwritten template in this folder structure:
your_project
|-- your_project/
|-- myapp/
|-- templates/
|-- admin/
|-- login.html <- do not misspell this
(without the myapp subfolder in the admin)
I do not have enough repution for commenting on Cheng's post this is why I had to write this as new answer.
What exactly does stringstream do?
You entered an alphanumeric and int, blank delimited in mystr
.
You then tried to convert the first token (blank delimited) into an int
.
The first token was RS which failed to convert to int
, leaving a zero for myprice, and we all know what zero times anything yields.
When you only entered int values the second time, everything worked as you expected.
It was the spurious RS that caused your code to fail.
Parse String date in (yyyy-MM-dd) format
I convert String to Date in format ("yyyy-MM-dd") to save into Mysql data base .
String date ="2016-05-01";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date parsed = format.parse(date);
java.sql.Date sql = new java.sql.Date(parsed.getTime());
sql it's my output in date format
What is the point of WORKDIR on Dockerfile?
You can think of WORKDIR
like a cd
inside the container (it affects commands that come later in the Dockerfile, like the RUN
command). If you removed WORKDIR
in your example above, RUN npm install
wouldn't work because you would not be in the /usr/src/app
directory inside your container.
I don't see how this would be related to where you put your Dockerfile (since your Dockerfile location on the host machine has nothing to do with the pwd inside the container). You can put the Dockerfile wherever you'd like in your project. However, the first argument to COPY
is a relative path, so if you move your Dockerfile you may need to update those COPY
commands.
LINQ: Select where object does not contain items from list
I have not tried this, so I am not guarantueeing anything, however
foreach Bar f in filterBars
{
search(f)
}
Foo search(Bar b)
{
fooSelect = (from f in fooBunch
where !(from b in f.BarList select b.BarId).Contains(b.ID)
select f).ToList();
return fooSelect;
}
Difference between Statement and PreparedStatement
nothing much to add,
1 - if you want to execute a query in a loop (more than 1 time), prepared statement can be faster, because of optimization that you mentioned.
2 - parameterized query is a good way to avoid SQL Injection. Parameterized querys are only available in PreparedStatement.
How to read a file into a variable in shell?
You can access 1 line at a time by for loop
#!/bin/bash -eu
#This script prints contents of /etc/passwd line by line
FILENAME='/etc/passwd'
I=0
for LN in $(cat $FILENAME)
do
echo "Line number $((I++)) --> $LN"
done
Copy the entire content to File (say line.sh ) ; Execute
chmod +x line.sh
./line.sh
Extract number from string with Oracle function
This works for me, I only need first numbers in string:
TO_NUMBER(regexp_substr(h.HIST_OBSE, '\.*[[:digit:]]+\.*[[:digit:]]*'))
the field had the following string: "(43 Paginas) REGLAS DE PARTICIPACION"
.
result field: 43
what is difference between success and .done() method of $.ajax
.success()
only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine.
The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected.
promise.done(doneCallback).fail(failCallback)
.done() has only one callback and it is the success callback
Linq Select Group By
You should try it like this:
var result =
from priceLog in PriceLogList
group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
select new {
LogDateTime = dateGroup.Key,
AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
};
Is there a standard sign function (signum, sgn) in C/C++?
In general, there is no standard signum function in C/C++, and the lack of such a fundamental function tells you a lot about these languages.
Apart from that, I believe both majority viewpoints about the right approach to define such a function are in a way correct, and the "controversy" about it is actually a non-argument once you take into account two important caveats:
A signum function should always return the type of its operand, similarly to an abs()
function, because signum is usually used for multiplication with an absolute value after the latter has been processed somehow. Therefore, the major use case of signum is not comparisons but arithmetic, and the latter shouldn't involve any expensive integer-to/from-floating-point conversions.
Floating point types do not feature a single exact zero value: +0.0 can be interpreted as "infinitesimally above zero", and -0.0 as "infinitesimally below zero". That's the reason why comparisons involving zero must internally check against both values, and an expression like x == 0.0
can be dangerous.
Regarding C, I think the best way forward with integral types is indeed to use the (x > 0) - (x < 0)
expression, as it should be translated in a branch-free fashion, and requires only three basic operations. Best define inline functions that enforce a return type matching the argument type, and add a C11 define _Generic
to map these functions to a common name.
With floating point values, I think inline functions based on C11 copysignf(1.0f, x)
, copysign(1.0, x)
, and copysignl(1.0l, x)
are the way to go, simply because they're also highly likely to be branch-free, and additionally do not require casting the result from integer back into a floating point value. You should probably comment prominently that your floating point implementations of signum will not return zero because of the peculiarities of floating point zero values, processing time considerations, and also because it is often very useful in floating point arithmetic to receive the correct -1/+1 sign, even for zero values.
Calling JMX MBean method from a shell script
A little risky, but you could run a curl POST command with the values from the form from the JMX console, its URL and http authentication (if required):
curl -s -X POST --user 'myuser:mypass'
--data "action=invokeOp&name=App:service=ThisServiceOp&methodIndex=3&arg0=value1&arg1=value1&submit=Invoke"
http://yourhost.domain.com/jmx-console/HtmlAdaptor
Beware: the method index may change with changes to the software. And the implementation of the web form could change.
The above is based on source of the JMX service page for the operation you want to perform:
http://yourhost.domain.com/jmx-console/HtmlAdaptor?action=inspectMBean&name=YourJMXServiceName
Source of the form:
form method="post" action="HtmlAdaptor">
<input type="hidden" name="action" value="invokeOp">
<input type="hidden" name="name" value="App:service=ThisServiceOp">
<input type="hidden" name="methodIndex" value="3">
<hr align='left' width='80'>
<h4>void ThisOperation()</h4>
<p>Operation exposed for management</p>
<table cellspacing="2" cellpadding="2" border="1">
<tr class="OperationHeader">
<th>Param</th>
<th>ParamType</th>
<th>ParamValue</th>
<th>ParamDescription</th>
</tr>
<tr>
<td>p1</td>
<td>java.lang.String</td>
<td>
<input type="text" name="arg0">
</td>
<td>(no description)</td>
</tr>
<tr>
<td>p2</td>
<td>arg1Type</td>
<td>
<input type="text" name="arg1">
</td>
<td>(no description)</td>
</tr>
</table>
<input type="submit" value="Invoke">
</form>
C++ - Hold the console window open?
As Thomas says, the cin ignore is a good way.
To always wait for user to press enter (even if exit is used), register a function atexit:
#include <iostream>
void pause()
{ ::std::cout<<"\nPress ENTER to exit.";
::std::cin.sync();
if(::std::cin.get()!='\n')
::std::cin.ignore(0xFFFFFFFF,'\n');
}
int main()
{
atexit(pause);
// whatever
return 0;
}
How to get the function name from within that function?
I know this is a old question but lately I've been facing some similar issue while trying to decorate some React Component's methods, for debugging purposes. As people already said, arguments.caller
and arguments.callee
are forbidden in strict mode which is probably enabled by default in your React transpiling. You can either disable it, or I've been able to come up with another hack, because in React all class functions are named, you can actually do this:
Component.prototype.componentWillMount = function componentWillMount() {
console.log('Callee name: ', this.__proto__.constructor.toString().substr(0,30));
...
}
System.web.mvc missing
The sample mvcmusicstore.codeplex.com opened in vs2015 missed some references, one of them System.web.mvc.
The fix for this was to remove it from the references and to add a reference:
choose Extentions under Assemblies, there you can find and add System.Web.Mvc.
(The other assemblies I added with the nuget packages.)
How to get a .csv file into R?
You can use
df <- read.csv("filename.csv", header=TRUE)
# To loop each column
for (i in 1:ncol(df))
{
dosomething(df[,i])
}
# To loop each row
for (i in 1:nrow(df))
{
dosomething(df[i,])
}
Also, you may want to have a look to the apply
function (type ?apply
or help(apply)
)if you want to use the same function on each row/column
Set a default parameter value for a JavaScript function
To anyone interested in having there code work in Microsoft Edge, do not use defaults in function parameters.
function read_file(file, delete_after = false) {
#code
}
In that example Edge will throw an error "Expecting ')'"
To get around this use
function read_file(file, delete_after) {
if(delete_after == undefined)
{
delete_after = false;
}
#code
}
As of Aug 08 2016 this is still an issue
PHP Constants Containing Arrays?
If you are looking this from 2009, and you don't like AbstractSingletonFactoryGenerators, here are a few other options.
Remember, arrays are "copied" when assigned, or in this case, returned, so you are practically getting the same array every time. (See copy-on-write behaviour of arrays in PHP.)
function FRUITS_ARRAY(){
return array('chicken', 'mushroom', 'dirt');
}
function FRUITS_ARRAY(){
static $array = array('chicken', 'mushroom', 'dirt');
return $array;
}
function WHAT_ANIMAL( $key ){
static $array = (
'Merrick' => 'Elephant',
'Sprague' => 'Skeleton',
'Shaun' => 'Sheep',
);
return $array[ $key ];
}
function ANIMAL( $key = null ){
static $array = (
'Merrick' => 'Elephant',
'Sprague' => 'Skeleton',
'Shaun' => 'Sheep',
);
return $key !== null ? $array[ $key ] : $array;
}
Adding values to specific DataTable cells
I think you can't do that but atleast you can update it. In order to edit an existing row in a DataTable, you need to locate the DataRow you want to edit, and then assign the updated values to the desired columns.
Example,
DataSet1.Tables(0).Rows(4).Item(0) = "Updated Company Name"
DataSet1.Tables(0).Rows(4).Item(1) = "Seattle"
SOURCE HERE
"RangeError: Maximum call stack size exceeded" Why?
Browsers can't handle that many arguments. See this snippet for example:
alert.apply(window, new Array(1000000000));
This yields RangeError: Maximum call stack size exceeded
which is the same as in your problem.
To solve that, do:
var arr = [];
for(var i = 0; i < 1000000; i++){
arr.push(Math.random());
}
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
range() for floats
I don't know a built-in function, but writing one like this shouldn't be too complicated.
def frange(x, y, jump):
while x < y:
yield x
x += jump
As the comments mention, this could produce unpredictable results like:
>>> list(frange(0, 100, 0.1))[-1]
99.9999999999986
To get the expected result, you can use one of the other answers in this question, or as @Tadhg mentioned, you can use decimal.Decimal
as the jump
argument. Make sure to initialize it with a string rather than a float.
>>> import decimal
>>> list(frange(0, 100, decimal.Decimal('0.1')))[-1]
Decimal('99.9')
Or even:
import decimal
def drange(x, y, jump):
while x < y:
yield float(x)
x += decimal.Decimal(jump)
And then:
>>> list(drange(0, 100, '0.1'))[-1]
99.9
Select row on click react-table
Multiple rows with checkboxes and select all using useState()
hooks. Requires minor implementation to adjust to own project.
const data;
const [ allToggled, setAllToggled ] = useState(false);
const [ toggled, setToggled ] = useState(Array.from(new Array(data.length), () => false));
const [ selected, setSelected ] = useState([]);
const handleToggleAll = allToggled => {
let selectAll = !allToggled;
setAllToggled(selectAll);
let toggledCopy = [];
let selectedCopy = [];
data.forEach(function (e, index) {
toggledCopy.push(selectAll);
if(selectAll) {
selectedCopy.push(index);
}
});
setToggled(toggledCopy);
setSelected(selectedCopy);
};
const handleToggle = index => {
let toggledCopy = [...toggled];
toggledCopy[index] = !toggledCopy[index];
setToggled(toggledCopy);
if( toggledCopy[index] === false ){
setAllToggled(false);
}
else if (allToggled) {
setAllToggled(false);
}
};
....
Header: state => (
<input
type="checkbox"
checked={allToggled}
onChange={() => handleToggleAll(allToggled)}
/>
),
Cell: row => (
<input
type="checkbox"
checked={toggled[row.index]}
onChange={() => handleToggle(row.index)}
/>
),
....
<ReactTable
...
getTrProps={(state, rowInfo, column, instance) => {
if (rowInfo && rowInfo.row) {
return {
onClick: (e, handleOriginal) => {
let present = selected.indexOf(rowInfo.index);
let selectedCopy = selected;
if (present === -1){
selected.push(rowInfo.index);
setSelected(selected);
}
if (present > -1){
selectedCopy.splice(present, 1);
setSelected(selectedCopy);
}
handleToggle(rowInfo.index);
},
style: {
background: selected.indexOf(rowInfo.index) > -1 ? '#00afec' : 'white',
color: selected.indexOf(rowInfo.index) > -1 ? 'white' : 'black'
},
}
}
else {
return {}
}
}}
/>
Clear and reset form input fields
Using event.target.reset()
only works for uncontrolled components, which is not recommended. For controlled components you would do something like this:
import React, { Component } from 'react'
class MyForm extends Component {
initialState = { name: '' }
state = this.initialState
handleFormReset = () => {
this.setState(() => this.initialState)
}
render() {
return (
<form onReset={this.handleFormReset}>
<div>
<label htmlFor="name">Name</label>
<input
type="text"
placeholder="Enter name"
name="name"
value={name}
onChange={this.handleInputOnChange}
/>
</div>
<div>
<input
type="submit"
value="Submit"
/>
<input
type="reset"
value="Reset"
/>
</div>
</form>
)
}
}
ContactAdd.propTypes = {}
export default MyForm
Generate HTML table from 2D JavaScript array
This is holmberd answer with a "table header" implementation
function createTable(tableData) {
var table = document.createElement('table');
var header = document.createElement("tr");
// get first row to be header
var headers = tableData[0];
// create table header
headers.forEach(function(rowHeader){
var th = document.createElement("th");
th.appendChild(document.createTextNode(rowHeader));
header.appendChild(th);
});
console.log(headers);
// insert table header
table.append(header);
var row = {};
var cell = {};
// remove first how - header
tableData.shift();
tableData.forEach(function(rowData, index) {
row = table.insertRow();
console.log("indice: " + index);
rowData.forEach(function(cellData) {
cell = row.insertCell();
cell.textContent = cellData;
});
});
document.body.appendChild(table);
}
createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"], ["row 3, cell 1", "row 3, cell 2"]]);
What is the minimum I have to do to create an RPM file?
I often do binary rpm per packaging proprietary apps - also moster as websphere - on linux.
So my experience could be useful also a you, besides that it would better to do a TRUE RPM if you can. But i digress.
So the a basic step for packaging your (binary) program is as follow - in which i suppose the
program is toybinprog with version 1.0, have a conf to be installed in /etc/toybinprog/toybinprog.conf and have a bin to be installed in /usr/bin called tobinprog :
1. create your rpm build env for RPM < 4.6,4.7
mkdir -p ~/rpmbuild/{RPMS,SRPMS,BUILD,SOURCES,SPECS,tmp}
cat <<EOF >~/.rpmmacros
%_topdir %(echo $HOME)/rpmbuild
%_tmppath %{_topdir}/tmp
EOF
cd ~/rpmbuild
2. create the tarball of your project
mkdir toybinprog-1.0
mkdir -p toybinprog-1.0/usr/bin
mkdir -p toybinprog-1.0/etc/toybinprog
install -m 755 toybinprog toybinprog-1.0/usr/bin
install -m 644 toybinprog.conf toybinprog-1.0/etc/toybinprog/
tar -zcvf toybinprog-1.0.tar.gz toybinprog-1.0/
3. Copy to the sources dir
cp toybinprog-1.0.tar.gz SOURCES/
cat <<EOF > SPECS/toybinprog.spec
# Don't try fancy stuff like debuginfo, which is useless on binary-only
# packages. Don't strip binary too
# Be sure buildpolicy set to do nothing
%define __spec_install_post %{nil}
%define debug_package %{nil}
%define __os_install_post %{_dbpath}/brp-compress
Summary: A very simple toy bin rpm package
Name: toybinprog
Version: 1.0
Release: 1
License: GPL+
Group: Development/Tools
SOURCE0 : %{name}-%{version}.tar.gz
URL: http://toybinprog.company.com/
BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root
%description
%{summary}
%prep
%setup -q
%build
# Empty section.
%install
rm -rf %{buildroot}
mkdir -p %{buildroot}
# in builddir
cp -a * %{buildroot}
%clean
rm -rf %{buildroot}
%files
%defattr(-,root,root,-)
%config(noreplace) %{_sysconfdir}/%{name}/%{name}.conf
%{_bindir}/*
%changelog
* Thu Apr 24 2009 Elia Pinto <[email protected]> 1.0-1
- First Build
EOF
4. build the source and the binary rpm
rpmbuild -ba SPECS/toybinprog.spec
And that's all.
Hope this help
Simple regular expression for a decimal with a precision of 2
function DecimalNumberValidation() {
var amounttext = ;
if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
alert('Please enter only numbers into amount textbox.')
}
else
{
alert('Right Number');
}
}
function will validate any decimal number weather number has decimal places or not, it will say "Right Number" other wise "Please enter only numbers into amount textbox." alert message will come up.
Thanks... :)
Calculate relative time in C#
Jeff, because Stack Overflow uses jQuery extensively, I recommend the jquery.timeago plugin.
Benefits:
- Avoid timestamps dated "1 minute ago" even though the page was opened 10 minutes ago; timeago refreshes automatically.
- You can take full advantage of page and/or fragment caching in your web applications, because the timestamps aren't calculated on the server.
- You get to use microformats like the cool kids.
Just attach it to your timestamps on DOM ready:
jQuery(document).ready(function() {
jQuery('abbr.timeago').timeago();
});
This will turn all abbr
elements with a class of timeago and an ISO 8601 timestamp in the title:
<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>
into something like this:
<abbr class="timeago" title="July 17, 2008">4 months ago</abbr>
which yields: 4 months ago. As time passes, the timestamps will automatically update.
Disclaimer: I wrote this plugin, so I'm biased.
SQL Server command line backup statement
Seba Illingworth's code, In case you need time in your file name (it gives 2014-02-21_1035)
echo off
cls
echo -- BACKUP DATABASE --
set /p DATABASENAME=Enter database name:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak
set SERVERNAME=.
echo.
sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
pause
How to use RANK() in SQL Server
You have already grouped by ContenderNum, no need to partition again by it.
Use Dense_rank()and order by totals desc.
In short,
SELECT contendernum,totals, **DENSE_RANK()**
OVER (ORDER BY totals **DESC**)
AS xRank
FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
GROUP BY ContenderNum
) AS a
How to get class object's name as a string in Javascript?
Shog9 is right that this doesn't make all that much sense to ask, since an object could be referred to by multiple variables. If you don't really care about that, and all you want is to find the name of one of the global variables that refers to that object, you could do the following hack:
function myClass() {
this.myName = function () {
// search through the global object for a name that resolves to this object
for (var name in this.global)
if (this.global[name] == this)
return name
}
}
// store the global object, which can be referred to as this at the top level, in a
// property on our prototype, so we can refer to it in our object's methods
myClass.prototype.global = this
// create a global variable referring to an object
var myVar = new myClass()
myVar.myName() // returns "myVar"
Note that this is an ugly hack, and should not be used in production code. If there is more than one variable referring to an object, you can't tell which one you'll get. It will only search the global variables, so it won't work if a variable is local to a function. In general, if you need to name something, you should pass the name in to the constructor when you create it.
edit: To respond to your clarification, if you need to be able to refer to something from an event handler, you shouldn't be referring to it by name, but instead add a function that refers to the object directly. Here's a quick example that I whipped up that shows something similar, I think, to what you're trying to do:
function myConstructor () {
this.count = 0
this.clickme = function () {
this.count += 1
alert(this.count)
}
var newDiv = document.createElement("div")
var contents = document.createTextNode("Click me!")
// This is the crucial part. We don't construct an onclick handler by creating a
// string, but instead we pass in a function that does what we want. In order to
// refer to the object, we can't use this directly (since that will refer to the
// div when running event handler), but we create an anonymous function with an
// argument and pass this in as that argument.
newDiv.onclick = (function (obj) {
return function () {
obj.clickme()
}
})(this)
newDiv.appendChild(contents)
document.getElementById("frobnozzle").appendChild(newDiv)
}
window.onload = function () {
var myVar = new myConstructor()
}
Insert Picture into SQL Server 2005 Image Field using only SQL
For updating a record:
UPDATE Employees SET [Photo] = (SELECT
MyImage.* from Openrowset(Bulk
'C:\photo.bmp', Single_Blob) MyImage)
where Id = 10
Notes:
- Make sure to add the 'BULKADMIN' Role Permissions for the login you are using.
- Paths are not pointing to your computer when using SQL Server Management Studio. If you start SSMS on your local machine and connect to a SQL Server instance on server X, the file C:\photo.bmp will point to hard drive C: on server X, not your machine!
<input type="file"> limit selectable files by extensions
NOTE: This answer is from 2011. It was a really good answer back then, but as of 2015, native HTML properties are supported by most browsers, so there's (usually) no need to implement such custom logic in JS. See Edi's answer and the docs.
Before the file is uploaded, you can check the file's extension using Javascript, and prevent the form being submitted if it doesn't match. The name of the file to be uploaded is stored in the "value" field of the form element.
Here's a simple example that only allows files that end in ".gif" to be uploaded:
<script type="text/javascript">
function checkFile() {
var fileElement = document.getElementById("uploadFile");
var fileExtension = "";
if (fileElement.value.lastIndexOf(".") > 0) {
fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
}
if (fileExtension.toLowerCase() == "gif") {
return true;
}
else {
alert("You must select a GIF file for upload");
return false;
}
}
</script>
<form action="upload.aspx" enctype="multipart/form-data" onsubmit="return checkFile();">
<input name="uploadFile" id="uploadFile" type="file" />
<input type="submit" />
</form>
However, this method is not foolproof. Sean Haddy is correct that you always want to check on the server side, because users can defeat your Javascript checking by turning off javascript, or editing your code after it arrives in their browser. Definitely check server-side in addition to the client-side check. Also I recommend checking for size server-side too, so that users don't crash your server with a 2 GB file (there's no way that I know of to check file size on the client side without using Flash or a Java applet or something).
However, checking client side before hand using the method I've given here is still useful, because it can prevent mistakes and is a minor deterrent to non-serious mischief.
Clear the value of bootstrap-datepicker
I was having similar trouble and the following worked for me:
$('#datepicker').val('').datepicker('update');
Both method calls were needed, otherwise it didn't clear.
How do I kill a VMware virtual machine that won't die?
In some cases you may not be able to suspend, or for that matter take any of the "Power" actions on the VM. You may also already have multiple VMs up and running. Use this process to identify the correct PID to kill.
On Windows 7 - Open Task Manager - Look for processes with the name, "vmware-vmx.exe", note the PIDs.
Switch to the Performance tab and start the "Resource Monitor". Expand the "Disk Activity" panel. Sort the "File" column. Look for the appropriate vmdk file for the VM you want to kill. The "Image" column will have the "vmware-vmx" process listed. Note the PID.
Switch back to the "Processes" tab and kill the PID.
presentViewController and displaying navigation bar
All a [self.navigationController pushViewController:controller animated:YES];
does is animate a transition, and add it to the navigation controller stack, and some other cool navigation bar animation stuffs. If you don't care about the bar animation, then this code should work. The bar does appear on the new controller, and you get an interactive pop gesture!
//Make Controller
DetailViewController *controller = [[DetailViewController alloc] initWithNibName:nil
bundle:[NSBundle mainBundle]];
//Customize presentation
controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
controller.modalPresentationStyle = UIModalPresentationCurrentContext;
//Present controller
[self presentViewController:controller
animated:YES
completion:nil];
//Add to navigation Controller
[self navigationController].viewControllers = [[self navigationController].viewControllers arrayByAddingObject:controller];
//You can't just [[self navigationController].viewControllers addObject:controller] because viewControllers are for some reason not a mutable array.
Edit: Sorry, presentViewController will fill the full screen. You will need to make a custom transition, with CGAffineTransform.translation or something, animate the controller with the transition, then add it to the navigationController's viewControllers.
How do I find the number of arguments passed to a Bash script?
#!/bin/bash
echo "The number of arguments is: $#"
a=${@}
echo "The total length of all arguments is: ${#a}: "
count=0
for var in "$@"
do
echo "The length of argument '$var' is: ${#var}"
(( count++ ))
(( accum += ${#var} ))
done
echo "The counted number of arguments is: $count"
echo "The accumulated length of all arguments is: $accum"
How does strtok() split the string into tokens in C?
you can scan the char array looking for the token if you found it just print new line else print the char.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
int len = strlen(s);
char delim =' ';
for(int i = 0; i < len; i++) {
if(s[i] == delim) {
printf("\n");
}
else {
printf("%c", s[i]);
}
}
free(s);
return 0;
}
Deleting an object in C++
Just an update of James' answer.
Isn't this the normal way to free the memory associated with an object?
Yes. It is the normal way to free memory. But new/delete operator always leads to memory leak problem.
Since c++17 already removed auto_ptr auto_ptr. I suggest shared_ptr or unique_ptr to handle the memory problems.
void test()
{
std::shared_ptr<Object1> obj1(new Object1);
} // The object is automatically deleted when the scope ends or reference counting reduces to 0.
- The reason for removing auto_ptr is that auto_ptr is not stable in case of coping semantics
- If you are sure about no coping happening during the scope, a unique_ptr is suggested.
- If there is a circular reference between the pointers, I suggest having a look at weak_ptr.
Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?
On modern Windows this driver isn't available by default anymore, but you can download as Microsoft Access Database Engine 2010 Redistributable on the MS site. If your app is 32 bits be sure to download and install the 32 bits variant because to my knowledge the 32 and 64 bit variant cannot coexist.
Depending on how your app locates its db driver, that might be all that's needed. However, if you use an UDL file there's one extra step - you need to edit that file. Unfortunately, on a 64bits machine the wizard used to edit UDL files is 64 bits by default, it won't see the JET driver and just slap whatever driver it finds first in the UDL file. There are 2 ways to solve this issue:
- start the 32 bits UDL wizard like this:
C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile C:\path\to\your.udl
. Note that I could use this technique on a Win7 64 Pro, but it didn't work on a Server 2008R2 (could be my mistake, just mentioning)
- open the UDL file in Notepad or another text editor, it should more or less have this format:
[oledb]
; Everything after this line is an OLE DB initstring
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\The\database.mdb;Persist Security Info=False
That should allow your app to start correctly.
Starting a node.js server
Run cmd
and then run node server.js
. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)
Is there any sed like utility for cmd.exe?
sed
(and its ilk) are contained within several packages of Unix commands.
If you don't want to install anything and your system ain't a Windows Server one, then you could use a scripting language (VBScript e.g.) for that. Below is a gross, off-the-cuff stab at it. Your command line would look like
cscript //NoLogo sed.vbs s/(oldpat)/(newpat)/ < inpfile.txt > outfile.txt
where oldpat and newpat are Microsoft vbscript regex patterns. Obviously I've only implemented the substitute command and assumed some things, but you could flesh it out to be smarter and understand more of the sed
command-line.
Dim pat, patparts, rxp, inp
pat = WScript.Arguments(0)
patparts = Split(pat,"/")
Set rxp = new RegExp
rxp.Global = True
rxp.Multiline = False
rxp.Pattern = patparts(1)
Do While Not WScript.StdIn.AtEndOfStream
inp = WScript.StdIn.ReadLine()
WScript.Echo rxp.Replace(inp, patparts(2))
Loop
Removing object from array in Swift 3
For Swift 3, you can use index(where:) and include a closure that does the comparison of an object in the array ($0) with whatever you are looking for.
var array = ["alpha", "beta", "gamma"]
if let index = array.index(where: {$0 == "beta"}) {
array.remove(at: index)
}
How to really read text file from classpath in Java
Somehow the best answer doesn't work for me. I need to use a slightly different code instead.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("SomeTextFile.txt");
I hope this help those who encounters the same issue.
Unable to merge dex
add this in your app/build.gradle. It will work
implementation 'com.android.support:design:27.1.0'
Remove numbers from string sql server
One more approach using Recursive CTE..
declare @string varchar(100)
set @string ='te165st1230004616161616'
;With cte
as
(
select @string as string,0 as n
union all
select cast(replace(string,n,'') as varchar(100)),n+1
from cte
where n<9
)
select top 1 string from cte
order by n desc
**Output:**
test
Android: Pass data(extras) to a fragment
I prefer Serializable
= no boilerplate code. For passing data to other Fragments or Activities the speed difference to a Parcelable
does not matter.
I would also always provide a helper method for a Fragment
or Activity
, this way you always know, what data has to be passed. Here an example for your ListMusicFragment
:
private static final String EXTRA_MUSIC_LIST = "music_list";
public static ListMusicFragment createInstance(List<Music> music) {
ListMusicFragment fragment = new ListMusicFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(EXTRA_MUSIC_LIST, music);
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(...) {
...
Bundle bundle = intent.getArguments();
List<Music> musicList = (List<Music>)bundle.getSerializable(EXTRA_MUSIC_LIST);
...
}
How to get PID of process by specifying process name and store it in a variable to use further?
If you want to kill -9 based on a string (you might want to try kill first) you can do something like this:
ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}'
This will show you what you're about to kill (very, very important) and just pipe it to sh
when the time comes to execute:
ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}' | sh
How to change column datatype from character to numeric in PostgreSQL 8.4
You can try using USING
:
The optional USING
clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A USING
clause must be provided if there is no implicit or assignment cast from old to new type.
So this might work (depending on your data):
alter table presales alter column code type numeric(10,0) using code::numeric;
-- Or if you prefer standard casting...
alter table presales alter column code type numeric(10,0) using cast(code as numeric);
This will fail if you have anything in code
that cannot be cast to numeric; if the USING fails, you'll have to clean up the non-numeric data by hand before changing the column type.
Network usage top/htop on Linux
Also iftop:
display bandwidth usage on an interface
iftop does for network usage what top(1) does for CPU usage. It listens to network traffic on a named interface and displays a table of current bandwidth usage by pairs of hosts. Handy for answering the question "why is our ADSL link so slow?"...
How to POST using HTTPclient content type = application/x-www-form-urlencoded
var params= new Dictionary<string, string>();
var url ="Please enter URLhere";
params.Add("key1", "value1");
params.Add("key2", "value2");
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(dict)).Result;
var tokne= response.Content.ReadAsStringAsync().Result;
}
//Get response as expected
ICommand MVVM implementation
I have written this article about the ICommand interface.
The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param)
is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param))
.
Requires the method to switching event CanExecuteChanged
. It is called from the user interface elements for switching the state CanExecute()
command.
public class ModelCommand : ICommand
{
#region Constructors
public ModelCommand(Action<object> execute)
: this(execute, null) { }
public ModelCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand Members
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute != null ? _canExecute(parameter) : true;
}
public void Execute(object parameter)
{
if (_execute != null)
_execute(parameter);
}
public void OnCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
#endregion
private readonly Action<object> _execute = null;
private readonly Predicate<object> _canExecute = null;
}
What is DOM element?
To find out concept of DOM element it is essential to understand concept of Dynamic HTML and DOM. Everything is started from the time that requirements of all stockholders of web pages are enhanced. They wanted the Web pages that can be more interactive, dynamic and lively. In addition, to reach this goal, developers required the tools and mechanisms that via them the presentation and content of each section of web page can be modified or manipulated. Therefore the concept of Dynamic HTML is created. To understand it, a great definition for Dynamic HTML is accessible in Wikipedia:
Dynamic HTML, or DHTML, is an umbrella term for a collection of
technologies used together to create interactive and animated websites
by using a combination of a static markup language (such as HTML), a
client-side scripting language (such as JavaScript), a presentation
definition language (such as CSS), and the Document Object Model
(DOM).
So, writing standard DHTML web pages are standardized in three fields, including client-side scripting language (such as JavaScript), a presentation definition language (such as CSS) and uniform programming interface(API) to access and modify the Web page (Document Object Model). This activity is performed by W3C and others. Also to solve the problem of cross browser, W3C tried to reach a general consensus (with different browser vendors) about scripts to access and manipulate HTML and XML documents via Document Object Model (DOM) as a standard application programming interface (API).
But the main question is that how they designed the structure of Document Object Model to meet their needs. Their solution was simple but wonderful. They used a hierarchical structure such as tree which at the root of the tree you can find document object, also each node is equivalent of a HTML elements (DOM element). This abstraction of your web page give you a great facility to access any HTML element, style sheets, and ... . To understand it better you can map each indent of your HTML code to each level of DOM tree. Please pay attention to this example:
Your HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>...</p>
<ul>
<li>...</li>
</ul>
<table>
<tr>...</tr>
</table>
</body>
</html>
DOM Structure:
document
| .
<html> .
/ \ .
<head> <body> styleSheets
/ \ \
<p> <ul> <table>
/ \ \
text <li> <tr>
So, each node of this hierarchical structure (DOM tree) refers to a DOM element. To learn more use tis reference
SQL Server 2005 Using CHARINDEX() To split a string
DECLARE @variable VARCHAR(100) = 'LD-23DSP-1430';
WITH Split
AS ( SELECT @variable AS list ,
charone = LEFT(@variable, 1) ,
R = RIGHT(@variable, LEN(@variable) - 1) ,
'A' AS MasterOne
UNION ALL
SELECT Split.list ,
LEFT(Split.R, 1) ,
R = RIGHT(split.R, LEN(Split.R) - 1) ,
'B' AS MasterOne
FROM Split
WHERE LEN(Split.R) > 0
)
SELECT *
FROM Split
OPTION ( MAXRECURSION 10000 );
Flutter - Layout a Grid
There are few named constructors in GridView
for different scenarios,
Constructors
GridView
GridView.builder
GridView.count
GridView.custom
GridView.extent
Below is a example of GridView
constructor:
import 'package:flutter/material.dart';
void main() => runApp(
MaterialApp(
home: ExampleGrid(),
),
);
class ExampleGrid extends StatelessWidget {
List<String> images = [
"https://uae.microless.com/cdn/no_image.jpg",
"https://images-na.ssl-images-amazon.com/images/I/81aF3Ob-2KL._UX679_.jpg",
"https://www.boostmobile.com/content/dam/boostmobile/en/products/phones/apple/iphone-7/silver/device-front.png.transform/pdpCarousel/image.jpg",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgUgs8_kmuhScsx-J01d8fA1mhlCR5-1jyvMYxqCB8h3LCqcgl9Q",
"https://ae01.alicdn.com/kf/HTB11tA5aiAKL1JjSZFoq6ygCFXaw/Unlocked-Samsung-GALAXY-S2-I9100-Mobile-Phone-Android-Wi-Fi-GPS-8-0MP-camera-Core-4.jpg_640x640.jpg",
"https://media.ed.edmunds-media.com/gmc/sierra-3500hd/2018/td/2018_gmc_sierra-3500hd_f34_td_411183_1600.jpg",
"https://hips.hearstapps.com/amv-prod-cad-assets.s3.amazonaws.com/images/16q1/665019/2016-chevrolet-silverado-2500hd-high-country-diesel-test-review-car-and-driver-photo-665520-s-original.jpg",
"https://www.galeanasvandykedodge.net/assets/stock/ColorMatched_01/White/640/cc_2018DOV170002_01_640/cc_2018DOV170002_01_640_PSC.jpg",
"https://media.onthemarket.com/properties/6191869/797156548/composite.jpg",
"https://media.onthemarket.com/properties/6191840/797152761/composite.jpg",
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: GridView(
physics: BouncingScrollPhysics(), // if you want IOS bouncing effect, otherwise remove this line
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),//change the number as you want
children: images.map((url) {
return Card(child: Image.network(url));
}).toList(),
),
);
}
}
If you want your GridView items to be dynamic according to the content, you can few lines to do that but the simplest way to use StaggeredGridView
package. I have provided an answer with example here.
Below is an example for a GridView.count
:
import 'package:flutter/material.dart';
void main() => runApp(
MaterialApp(
home: ExampleGrid(),
),
);
class ExampleGrid extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: GridView.count(
crossAxisCount: 4,
children: List.generate(40, (index) {
return Card(
child: Image.network("https://robohash.org/$index"),
); //robohash.org api provide you different images for any number you are giving
}),
),
);
}
}
Screenshot for above snippet:
Example for a SliverGridView
:
import 'package:flutter/material.dart';
void main() => runApp(
MaterialApp(
home: ExampleGrid(),
),
);
class ExampleGrid extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
primary: false,
slivers: <Widget>[
SliverPadding(
padding: const EdgeInsets.all(20.0),
sliver: SliverGrid.count(
crossAxisSpacing: 10.0,
crossAxisCount: 2,
children: List.generate(20, (index) {
return Card(child: Image.network("https://robohash.org/$index"));
}),
),
),
],
)
);
}
}
VBA setting the formula for a cell
Not sure what isn't working in your case, but the following code will put a formula into cell A1 that will retrieve the value in the cell G2.
strProjectName = "Sheet1"
Cells(1, 1).Formula = "=" & strProjectName & "!" & Cells(2, 7).Address
The workbook and worksheet that strProjectName
references must exist at the time that this formula is placed. Excel will immediately try to evaluate the formula. You might be able to stop that from happening by turning off automatic recalculation until the workbook does exist.
Rearrange columns using cut
For the cut(1)
man page:
Use one, and only one of -b, -c or -f. Each LIST is made up of
one
range, or many ranges separated by commas. Selected input is written
in the same order that it is read, and is written exactly once.
It reaches field 1 first, so that is printed, followed by field 2.
Use awk
instead:
awk '{ print $2 " " $1}' file.txt
Input type DateTime - Value format?
This was a good waste of an hour of my time. For you eager beavers, the following format worked for me:
<input type="datetime-local" name="to" id="to" value="2014-12-08T15:43:00">
The spec was a little confusing to me, it said to use RFC 3339, but on my PHP server when I used the format DATE_RFC3339 it wasn't initializing my hmtl input :( PHP's constant for DATE_RFC3339 is "Y-m-d\TH:i:sP" at the time of writing, it makes sense that you should get rid of the timezone info (we're using datetime-LOCAL, folks). So the format that worked for me was:
"Y-m-d\TH:i:s"
I would've thought it more intuitive to be able to set the value of the datepicker as the datepicker displays the date, but I'm guessing the way it is displayed differs across browsers.
Select top 2 rows in Hive
Yes, here you can use LIMIT
.
You can try it by the below query:
SELECT * FROM employee_list SORT BY salary DESC LIMIT 2
RegEx to exclude a specific string constant
You have to use a negative lookahead assertion.
(?!^ABC$)
You could for example use the following.
(?!^ABC$)(^.*$)
If this does not work in your editor, try this. It is tested to work in ruby and javascript:
^((?!ABC).)*$
Get selected element's outer HTML
I've used Volomike's solution updated by Jessica. Just added a check to see if the element exists, and made it return blank in case it doesn't.
jQuery.fn.outerHTML = function() {
return $(this).length > 0 ? $(this).clone().wrap('<div />').parent().html() : '';
};
Of course, use it like:
$('table#buttons').outerHTML();
C# List<> Sort by x then y
I had an issue where OrderBy and ThenBy did not give me the desired result (or I just didn't know how to use them correctly).
I went with a list.Sort solution something like this.
var data = (from o in database.Orders Where o.ClientId.Equals(clientId) select new {
OrderId = o.id,
OrderDate = o.orderDate,
OrderBoolean = (SomeClass.SomeFunction(o.orderBoolean) ? 1 : 0)
});
data.Sort((o1, o2) => (o2.OrderBoolean.CompareTo(o1.OrderBoolean) != 0
o2.OrderBoolean.CompareTo(o1.OrderBoolean) : o1.OrderDate.Value.CompareTo(o2.OrderDate.Value)));
append new row to old csv file python
I follow this way to append a new line in a .csv file:
pose_x = 1
pose_y = 2
with open('path-to-your-csv-file.csv', mode='a') as file_:
file_.write("{},{}".format(pose_x, pose_y))
file_.write("\n")
Adding space/padding to a UILabel
If you want to add 2px padding around the textRect, just do this:
let insets = UIEdgeInsets(top: -2, left: -2, bottom: -2, right: -2)
label.frame = UIEdgeInsetsInsetRect(textRect, insets)
SessionTimeout: web.xml vs session.maxInactiveInterval()
Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
No, that's not true. The session-timeout
configures a per session timeout in case of inactivity.
Are these methods equivalent? Should I favour the web.xml config?
The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.
Adding div element to body or document in JavaScript
improving the post of @Peter T, by gathering all solutions together at one place.
Element.insertAdjacentHTML()
function myFunction() {
window.document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID" style="color:blue;"> With some data...</div>' );
}
function addElement(){
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'width:100%;height:10%;background:rgb(192,192,192);';
elemDiv.innerHTML = 'Added element with some data';
window.document.body.insertBefore(elemDiv, window.document.body.firstChild);
// document.body.appendChild(elemDiv); // appends last of that element
}
function addCSS() {
window.document.getElementsByTagName("style")[0].innerHTML += ".mycss {text-align:center}";
}
Using XPath
find the position of the Element in the DOM Tree and insert the specified text at a specified position to an XPath_Element. try this code over browser console.
function insertHTML_ByXPath( xpath, position, newElement) {
var element = document.evaluate(xpath, window.document, null, 9, null ).singleNodeValue;
element.insertAdjacentHTML(position, newElement);
element.style='border:3px solid orange';
}
var xpath_DOMElement = '//*[@id="answer-33669996"]/table/tbody/tr[1]/td[2]/div';
var childHTML = '<div id="Yash">Hi My name is <B>\"YASHWANTH\"</B></div>';
var position = 'beforeend';
insertHTML_ByXPath(xpath_DOMElement, position, childHTML);
Convert character to ASCII code in JavaScript
For those that want to get a sum of all the ASCII codes for a string:
'Foobar'
.split('')
.map(x=>x.charCodeAt(0))
.reduce((a,b)=>a+b);
Or, ES6:
[...'Foobar']
.map(char => char.charCodeAt(0))
.reduce((current, previous) => previous + current)
libz.so.1: cannot open shared object file
After checking to which package does the libz.so.1 belongs (http://packages.ubuntu.com/lucid/i386/zlib1g/filelist) you should try to install zlib1g:
sudo apt-get install zlib1g
As pointed by @E-rich, it may be required to add a :i386 suffix to the package name for the package manager correctly identify it:
sudo apt-get install zlib1g:i386
EDIT (for CentOS or other distro that makes use of yum
):
If someone using CentOS (or any other distro that makes use of yum
) that may end up reading this question, @syslogic proposed the following solution in the comments:
yum install zlib.i686
or, for 32-bit binaries:
yum install zlib.i386
INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device
In my case there was no version of the App I could find through device manager or Astro.
What I ended up doing was:
1) Download the latest version of the App from the app store
2) The app was still not visible in device manager until I restarted my device.
3) Remove the app from device manager
4) Run my project again
5) Everything works
Hope this helps someone
How do I use reflection to invoke a private method?
Invokes any method despite its protection level on object instance. Enjoy!
public static object InvokeMethod(object obj, string methodName, params object[] methodParams)
{
var methodParamTypes = methodParams?.Select(p => p.GetType()).ToArray() ?? new Type[] { };
var bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
MethodInfo method = null;
var type = obj.GetType();
while (method == null && type != null)
{
method = type.GetMethod(methodName, bindingFlags, Type.DefaultBinder, methodParamTypes, null);
type = type.BaseType;
}
return method?.Invoke(obj, methodParams);
}
How to create a GUID/UUID in Python
Check this post, helped me a lot. In short, the best option for me was:
import random
import string
# defining function for random
# string id with parameter
def ran_gen(size, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
# function call for random string
# generation with size 8 and string
print (ran_gen(8, "AEIOSUMA23"))
Because I needed just 4-6 random characters instead of bulky GUID.
SQLSTATE[HY000] [2002] Connection refused within Laravel homestead
PROBLEM SOLVED
I had the same problem and fixed just by converting DB_HOST constant in the .env File FROM 127.0.0.1
into localhost
*JUST DO THIS AS GIVEN IN THE BELOW LINE*
DB_HOST = localhost
.
No need to change anything into config/database.php
Don't forget to run
php artisan config:clear
How to use continue in jQuery each() loop?
We can break both a $(selector).each()
loop and a $.each()
loop at a particular iteration by making the callback function return false
. Returning non-false
is the same as a continue statement in a for
loop; it will skip immediately to the next iteration.
return false; // this is equivalent of 'break' for jQuery loop
return; // this is equivalent of 'continue' for jQuery loop
Note that $(selector).each()
and $.each()
are different functions.
References:
Regex to match string containing two names in any order
The expression in this answer does that for one jack
and one james
in any order.
Here, we'd explore other scenarios.
METHOD 1: One jack
and One james
Just in case, two jack
or two james
would not be allowed, only one jack
and one james
would be valid, we can likely design an expression similar to:
^(?!.*\bjack\b.*\bjack\b)(?!.*\bjames\b.*\bjames\b)(?=.*\bjames\b)(?=.*\bjack\b).*$
Here, we would exclude those instances using these statements:
(?!.*\bjack\b.*\bjack\b)
and,
(?!.*\bjames\b.*\bjames\b)
We can also simplify that to:
^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b|.*\bjack\b).*$
If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx engine might step by step consume some sample input strings and would perform the matching process.
RegEx Circuit
jex.im visualizes regular expressions:
Test
_x000D_
_x000D_
const regex = /^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b|.*\bjack\b).*$/gm;
const str = `hi jack here is james
hi james here is jack
hi james jack here is jack james
hi jack james here is james jack
hi jack jack here is jack james
hi james james here is james jack
hi jack jack jack here is james
`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
_x000D_
_x000D_
_x000D_
METHOD 2: One jack
and One james
in a specific order
The expression can be also designed for first a james
then a jack
, similar to the following one:
^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjames\b.*\bjack\b).*$
and vice versa:
^(?!.*\bjack\b.*\bjack\b|.*\bjames\b.*\bjames\b)(?=.*\bjack\b.*\bjames\b).*$
Convert floating point number to a certain precision, and then copy to string
With Python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.
# Option one
older_method_string = "%.9f" % numvar
# Option two
newer_method_string = "{:.9f}".format(numvar)
But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.
For more information on option two, I suggest this link on string formatting from the Python documentation.
And for more information on option one, this link will suffice and has info on the various flags.
Python 3.6 (officially released in December of 2016), added the f
string literal, see more information here, which extends the str.format
method (use of curly braces such that f"{numvar:.9f}"
solves the original problem), that is,
# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"
solves the problem. Check out @Or-Duan's answer for more info, but this method is fast.
How do I get ASP.NET Web API to return JSON instead of XML using Chrome?
Some time has passed since this question was asked (and answered) but another option is to override the Accept header on the server during request processing using a MessageHandler as below:
public class ForceableContentTypeDelegationHandler : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var someOtherCondition = false;
var accHeader = request.Headers.GetValues("Accept").FirstOrDefault();
if (someOtherCondition && accHeader.Contains("application/xml"))
{
request.Headers.Remove("Accept");
request.Headers.Add("Accept", "application/json");
}
return await base.SendAsync(request, cancellationToken);
}
}
Where someOtherCondition
can be anything including browser type, etc. This would be for conditional cases where only sometimes do we want to override the default content negotiation. Otherwise as per other answers, you would simply remove an unnecessary formatter from the configuration.
You'll need to register it of course. You can either do this globally:
public static void Register(HttpConfiguration config) {
config.MessageHandlers.Add(new ForceableContentTypeDelegationHandler());
}
or on a route by route basis:
config.Routes.MapHttpRoute(
name: "SpecialContentRoute",
routeTemplate: "api/someUrlThatNeedsSpecialTreatment/{id}",
defaults: new { controller = "SpecialTreatment" id = RouteParameter.Optional },
constraints: null,
handler: new ForceableContentTypeDelegationHandler()
);
And since this is a message handler it will run on both the request and response ends of the pipeline much like an HttpModule
. So you could easily acknowledge the override with a custom header:
public class ForceableContentTypeDelegationHandler : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var wasForced = false;
var someOtherCondition = false;
var accHeader = request.Headers.GetValues("Accept").FirstOrDefault();
if (someOtherCondition && accHeader.Contains("application/xml"))
{
request.Headers.Remove("Accept");
request.Headers.Add("Accept", "application/json");
wasForced = true;
}
var response = await base.SendAsync(request, cancellationToken);
if (wasForced){
response.Headers.Add("X-ForcedContent", "We overrode your content prefs, sorry");
}
return response;
}
}
How do I publish a UDP Port on Docker?
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs:
https://docs.docker.com/config/containers/container-networking/
(Courtesy of Old Pro in the comments)
Javascript replace with reference to matched group?
"hello _there_".replace(/_(.*?)_/, function(a, b){
return '<div>' + b + '</div>';
})
Oh, or you could also:
"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")
EDIT by Liran H:
For six other people including myself, $1
did not work, whereas \1
did.
How do I get the current date in Cocoa
You must use the following:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:yourDateHere];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[gregorian release];
There is no difference between NSDate* now and NSDate *now, it's just a matter of preference. From the compiler perspective, nothing changes.
Namenode not getting started
hadoop.tmp.dir
in the core-site.xml is defaulted to /tmp/hadoop-${user.name}
which is cleaned after every reboot. Change this to some other directory which doesn't get cleaned on reboot.
Optimum way to compare strings in JavaScript?
You can use the comparison operators to compare strings. A strcmp
function could be defined like this:
function strcmp(a, b) {
if (a.toString() < b.toString()) return -1;
if (a.toString() > b.toString()) return 1;
return 0;
}
Edit Here’s a string comparison function that takes at most min { length(a), length(b) } comparisons to tell how two strings relate to each other:
function strcmp(a, b) {
a = a.toString(), b = b.toString();
for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
if (i === n) return 0;
return a.charAt(i) > b.charAt(i) ? -1 : 1;
}
How to make use of ng-if , ng-else in angularJS
<span ng-if="verifyName.indicator == 1"><i class="fa fa-check"></i></span>
<span ng-if="verifyName.indicator == 0"><i class="fa fa-times"></i></span>
try this code.
here verifyName.indicator value is coming from controller.
this works for me.
Scroll to a specific Element Using html
The above answers are good and correct. However, the code may not give the expected results. Allow me to add something to explain why this is very important.
It is true that adding the scroll-behavior: smooth to the html element allows smooth scrolling for the whole page. However not all web browsers support smooth scrolling using HTML.
So if you want to create a website accessible to all user, regardless of their web browsers, it is highly recommended to use JavaScript or a JavaScript library such as jQuery, to create a solution that will work for all browsers.
Otherwise, some users may not enjoy the smooth scrolling of your website / platform.
I can give a simpler example on how it can be applicable.
_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
// Add smooth scrolling to all links_x000D_
$("a").on('click', function(event) {_x000D_
// Make sure this.hash has a value before overriding default behavior_x000D_
if (this.hash !== "") {_x000D_
// Prevent default anchor click behavior_x000D_
event.preventDefault();_x000D_
// Store hash_x000D_
var hash = this.hash;_x000D_
// Using jQuery's animate() method to add smooth page scroll_x000D_
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area_x000D_
$('html, body').animate({_x000D_
scrollTop: $(hash).offset().top_x000D_
}, 800, function(){_x000D_
// Add hash (#) to URL when done scrolling (default click behavior)_x000D_
window.location.hash = hash;_x000D_
});_x000D_
} // End if_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
<style>_x000D_
#section1 {_x000D_
height: 600px;_x000D_
background-color: pink;_x000D_
}_x000D_
#section2 {_x000D_
height: 600px;_x000D_
background-color: yellow;_x000D_
}_x000D_
</style>
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<h1>Smooth Scroll</h1>_x000D_
<div class="main" id="section1">_x000D_
<h2>Section 1</h2>_x000D_
<p>Click on the link to see the "smooth" scrolling effect.</p>_x000D_
<a href="#section2">Click Me to Smooth Scroll to Section 2 Below</a>_x000D_
<p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>_x000D_
</div>_x000D_
<div class="main" id="section2">_x000D_
<h2>Section 2</h2>_x000D_
<a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
Help needed with Median If in Excel
Assuming your categories are in cells A1:A6 and the corresponding values are in B1:B6, you might try typing the formula =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,""))
in another cell and then pressing CTRL+SHIFT+ENTER
.
Using CTRL+SHIFT+ENTER
tells Excel to treat the formula as an "array formula". In this example, that means that the IF
statement returns an array of 6 values (one of each of the cells in the range $A$1:$A$6
) instead of a single value. The MEDIAN
function then returns the median of these values. See http://www.cpearson.com/excel/arrayformulas.aspx for a similar example using AVERAGE
instead of MEDIAN
.
Convert int to string?
string s = "" + 2;
and you can do nice things like:
string s = 2 + 2 + "you"
The result will be:
"4 you"
How to pass arguments to Shell Script through docker run
With Docker, the proper way to pass this sort of information is through environment variables.
So with the same Dockerfile, change the script to
#!/bin/bash
echo $FOO
After building, use the following docker command:
docker run -e FOO="hello world!" test