Call to undefined function oci_connect()
Things to Make sure
- Whenever you connecting Oracle Database , try to use 32 Bit oracle client libraries, Since XAMP PHP is compiled with 32 Bit(Though you have 64 Bit windows Machine)
Download Oracle Client from Download From here
Paste it in C:\instantclient_12_1
- Then Set the path to above in System Environment Variable
- Then Go to C:\xampp\php\php.ini and uncomment extension=php_oci8_12c.dll
- Then Restart the XAMP and it should work without any Issue.
HashMap with multiple values under the same key
I could not post a reply on Paul's comment so I am creating new comment for Vidhya here:
Wrapper will be a SuperClass
for the two classes which we want to store as a value.
and inside wrapper class, we can put the associations as the instance variable objects for the two class objects.
e.g.
class MyWrapper {
Class1 class1obj = new Class1();
Class2 class2obj = new Class2();
...
}
and in HashMap we can put in this way,
Map<KeyObject, WrapperObject>
WrapperObj will have class variables: class1Obj, class2Obj
How to create a jQuery function (a new jQuery method or plugin)?
In spite of all the answers you already received, it is worth noting that you do not need to write a plugin to use jQuery in a function. Certainly if it's a simple, one-time function, I believe writing a plugin is overkill. It could be done much more easily by just passing the selector to the function as a parameter. Your code would look something like this:
function myFunction($param) {
$param.hide(); // or whatever you want to do
...
}
myFunction($('#my_div'));
Note that the $
in the variable name $param
is not required. It is just a habit of mine to make it easy to remember that that variable contains a jQuery selector. You could just use param
as well.
Python: get key of index in dictionary
You could do something like this:
i={'foo':'bar', 'baz':'huh?'}
keys=i.keys() #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")] #'foo'
However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.
As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.
Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:
d={'i':1, 'j':1}
In that case, it is impossible to know whether you want i
or j
and in fact no answer here will be able to tell you which ('i'
or 'j'
) will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.
Matplotlib discrete colorbar
You can create a custom discrete colorbar quite easily by using a BoundaryNorm as normalizer for your scatter. The quirky bit (in my method) is making 0 showup as grey.
For images i often use the cmap.set_bad() and convert my data to a numpy masked array. That would be much easier to make 0 grey, but i couldnt get this to work with the scatter or the custom cmap.
As an alternative you can make your own cmap from scratch, or read-out an existing one and override just some specific entries.
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
fig, ax = plt.subplots(1, 1, figsize=(6, 6)) # setup the plot
x = np.random.rand(20) # define the data
y = np.random.rand(20) # define the data
tag = np.random.randint(0, 20, 20)
tag[10:12] = 0 # make sure there are some 0 values to show up as grey
cmap = plt.cm.jet # define the colormap
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# force the first color entry to be grey
cmaplist[0] = (.5, .5, .5, 1.0)
# create the new map
cmap = mpl.colors.LinearSegmentedColormap.from_list(
'Custom cmap', cmaplist, cmap.N)
# define the bins and normalize
bounds = np.linspace(0, 20, 21)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
# make the scatter
scat = ax.scatter(x, y, c=tag, s=np.random.randint(100, 500, 20),
cmap=cmap, norm=norm)
# create a second axes for the colorbar
ax2 = fig.add_axes([0.95, 0.1, 0.03, 0.8])
cb = plt.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm,
spacing='proportional', ticks=bounds, boundaries=bounds, format='%1i')
ax.set_title('Well defined discrete colors')
ax2.set_ylabel('Very custom cbar [-]', size=12)
I personally think that with 20 different colors its a bit hard to read the specific value, but thats up to you of course.
Adding a directory to PATH in Ubuntu
Actually I would advocate .profile
if you need it to work from scripts, and in particular, scripts run by /bin/sh instead of Bash. If this is just for your own private interactive use, .bashrc
is fine, though.
Why doesn't wireshark detect my interface?
This is usually caused by incorrectly setting up permissions related to running Wireshark correctly. While you can avoid this issue by running Wireshark with elevated privileges (e.g. with sudo
), it should generally be avoided (see here, specifically here). This sometimes results from an incomplete or partially successful installation of Wireshark. Since you are running Ubuntu, this can be resolved by following the instructions given in this answer on the Wireshark Q&A site. In summary, after installing Wireshark, execute the following commands:
sudo dpkg-reconfigure wireshark-common
sudo usermod -a -G wireshark $USER
Then log out and log back in (or reboot), and Wireshark should work correctly without needing additional privileges. Finally, if the problem is still not resolved, it may be that dumpcap
was not correctly configured, or there is something else preventing it from operating correctly. In this case, you can set the setuid
bit for dumpcap
so that it always runs as root.
sudo chmod 4711 `which dumpcap`
One some distros you might get the following error when you execute the command above:
chmod: missing operand after ‘4711’
Try 'chmod --help' for more information.
In this case try running
sudo chmod 4711 `sudo which dumpcap`
How to set variable from a SQL query?
You can use this, but remember that your query gives 1 result, multiple results will throw the exception.
declare @ModelID uniqueidentifer
Set @ModelID = (select Top(1) modelid from models where areaid = 'South Coast')
Another way:
Select Top(1)@ModelID = modelid from models where areaid = 'South Coast'
If hasClass then addClass to parent
If anyone is using WordPress, you can use something like:
if (jQuery('.dropdown-menu li').hasClass('active')) {
jQuery('.current-menu-parent').addClass('current-menu-item');
}
Exception Error c0000005 in VC++
Exception code c0000005
is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:
- Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
- Reading off the end of an array. This is when you have an array of length
N
and you access elements with index >=N
.
To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.
Key Shortcut for Eclipse Imports
You also can enable this import as automatic operation. In the properties dialog of your Java projects, enable organize imports
via Java Editor
- Save Action
. After saving your Java files, IDE will do organizing imports, formatting code and so on for you.
how to draw directed graphs using networkx in python?
You need to use a directed graph instead of a graph, i.e.
G = nx.DiGraph()
Then, create a list of the edge colors you want to use and pass those to nx.draw
(as shown by @Marius).
Putting this all together, I get the image below. Still not quite the other picture you show (I don't know where your edge weights are coming from), but much closer! If you want more control of how your output graph looks (e.g. get arrowheads that look like arrows), I'd check out NetworkX with Graphviz.
const to Non-const Conversion in C++
Leaving this here for myself,
If I get this error, I probably used const char*
when I should be using char* const
.
This makes the pointer constant, and not the contents of the string.
const char* const
makes it so the value and the pointer is constant also.
Dynamically changing font size of UILabel
This solution works for multiline:
After following several articles, and requiring a function that would automatically scale the text and adjust the line count to best fit within the given label size, I wrote a function myself. (ie. a short string would fit nicely on one line and use a large amount of the label frame, whereas a long strong would automatically split onto 2 or 3 lines and adjust the size accordingly)
Feel free to re-use it and tweak as required. Make sure you call it after viewDidLayoutSubviews
has finished so that the initial label frame has been set.
+ (void)setFontForLabel:(UILabel *)label withMaximumFontSize:(float)maxFontSize andMaximumLines:(int)maxLines {
int numLines = 1;
float fontSize = maxFontSize;
CGSize textSize; // The size of the text
CGSize frameSize; // The size of the frame of the label
CGSize unrestrictedFrameSize; // The size the text would be if it were not restricted by the label height
CGRect originalLabelFrame = label.frame;
frameSize = label.frame.size;
textSize = [label.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize: fontSize]}];
// Work out the number of lines that will need to fit the text in snug
while (((textSize.width / numLines) / (textSize.height * numLines) > frameSize.width / frameSize.height) && (numLines < maxLines)) {
numLines++;
}
label.numberOfLines = numLines;
// Get the current text size
label.font = [UIFont systemFontOfSize:fontSize];
textSize = [label.text boundingRectWithSize:CGSizeMake(frameSize.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:@{NSFontAttributeName : label.font}
context:nil].size;
// Adjust the frame size so that it can fit text on more lines
// so that we do not end up with truncated text
label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width, label.frame.size.width);
// Get the size of the text as it would fit into the extended label size
unrestrictedFrameSize = [label textRectForBounds:CGRectMake(0, 0, label.bounds.size.width, CGFLOAT_MAX) limitedToNumberOfLines:numLines].size;
// Keep reducing the font size until it fits
while (textSize.width > unrestrictedFrameSize.width || textSize.height > frameSize.height) {
fontSize--;
label.font = [UIFont systemFontOfSize:fontSize];
textSize = [label.text boundingRectWithSize:CGSizeMake(frameSize.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:@{NSFontAttributeName : label.font}
context:nil].size;
unrestrictedFrameSize = [label textRectForBounds:CGRectMake(0, 0, label.bounds.size.width, CGFLOAT_MAX) limitedToNumberOfLines:numLines].size;
}
// Set the label frame size back to original
label.frame = originalLabelFrame;
}
Regex for Mobile Number Validation
Satisfies all your requirements if you use the trick told below
Regex: /^(\+\d{1,3}[- ]?)?\d{10}$/
^
start of line
- A
+
followed by \d+
followed by a
or -
which are optional.
- Whole point two is optional.
- Negative lookahead to make sure
0
s do not follow.
- Match
\d+
10 times.
- Line end.
DEMO Added m
ultiline flag in demo to check for all cases
P.S. You really need to specify which language you use so as to use an if
condition something like below:
// true if above regex is satisfied and (&&) it does not (`!`) match `0`s `5` or more times
if(number.match(/^(\+\d{1,3}[- ]?)?\d{10}$/) && ! (number.match(/0{5,}/)) )
jQuery $.ajax(), pass success data into separate function
You can use this keyword to access custom data, passed to $.ajax() function:
$.ajax({
// ... // --> put ajax configuration parameters here
yourCustomData: {param1: 'any value', time: '1h24'}, // put your custom key/value pair here
success: successHandler
});
function successHandler(data, textStatus, jqXHR) {
alert(this.yourCustomData.param1); // shows "any value"
console.log(this.yourCustomData.time);
}
Function Pointers in Java
The Java idiom for function-pointer-like functionality is an an anonymous class implementing an interface, e.g.
Collections.sort(list, new Comparator<MyClass>(){
public int compare(MyClass a, MyClass b)
{
// compare objects
}
});
Update: the above is necessary in Java versions prior to Java 8. Now we have much nicer alternatives, namely lambdas:
list.sort((a, b) -> a.isGreaterThan(b));
and method references:
list.sort(MyClass::isGreaterThan);
How to export settings?
For posterity, this post mentions,
in the latest release of Visual Studio Code (May 2016) it is now possible to list
the installed extension in the command line
code --list-extensions
On Mac, execute something like:
"/Applications/Visual Studio Code.app//Contents/Resources/app/bin/code" --list-extensions
To install, use:
--install-extension <ext> //see 'code --help'
AngularJS resource promise
If you're looking to get promise in resource call, you should use
Regions.query().$q.then(function(){ .... })
Update : the promise syntax is changed in current versions which reads
Regions.query().$promise.then(function(){ ..... })
Those who have downvoted don't know what it was and who first added this promise to resource object. I used this feature in late 2012 - yes 2012.
Align text in JLabel to the right
This can be done in two ways.
JLabel Horizontal Alignment
You can use the JLabel
constructor:
JLabel(String text, int horizontalAlignment)
To align to the right:
JLabel label = new JLabel("Telephone", SwingConstants.RIGHT);
JLabel
also has setHorizontalAlignment
:
label.setHorizontalAlignment(SwingConstants.RIGHT);
This assumes the component takes up the whole width in the container.
Using Layout
A different approach is to use the layout to actually align the component to the right, whilst ensuring they do not take the whole width. Here is an example with BoxLayout
:
Box box = Box.createVerticalBox();
JLabel label1 = new JLabel("test1, the beginning");
label1.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label1);
JLabel label2 = new JLabel("test2, some more");
label2.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label2);
JLabel label3 = new JLabel("test3");
label3.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label3);
add(box);
How to link to a named anchor in Multimarkdown?
If you have headers in the markdown files, you can directly link them in the file.
Markdown Header -
## The Header
this will generate an implicit id #the-header
(replace internal spaces with hyphens and make lowercase).
To navigate to this id, you can create the link like this:
[Link to Header](#the-header)
This is equivalent to:
<a href="#the-header">Link to Header</a>
Please note the reference's name is a lower-case #header
.
Facebook Access Token for Pages
- Go to the Graph API Explorer
- Choose your app from the dropdown menu
- Click "Get Access Token"
- Choose the
manage_pages
permission (you may need the user_events
permission too, not sure)
- Now access the
me/accounts
connection and copy your page's access_token
- Click on your page's id
- Add the page's
access_token
to the GET fields
- Call the connection you want (e.g.:
PAGE_ID/events
)
Replace whitespaces with tabs in linux
I think you can try with awk
awk -v OFS="\t" '$1=$1' file1
or SED if you preffer
sed 's/[:blank:]+/,/g' thefile.txt > the_modified_copy.txt
or even tr
tr -s '\t' < thefile.txt | tr '\t' ' ' > the_modified_copy.txt
or a simplified version of the tr solution sugested by Sam Bisbee
tr ' ' \\t < someFile > someFile
Changing text color onclick
A rewrite of the answer by Sarfraz would be something like this, I think:
<script>
document.getElementById('change').onclick = changeColor;
function changeColor() {
document.body.style.color = "purple";
return false;
}
</script>
You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );
Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc();
the function would actually execute when the handler is being set.
And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)
Regular expression to find two strings anywhere in input
This works for searching files that contain both String1
and String2
(((.|\n)*)String1((.|\n)*)String2)|(((.|\n)*)String2((.|\n)*)String1)
Match any number of characters or line fields
followed by String1
followed by any number of characters or line fields
followed by String2
OR
Match any number of characters or line fields
followed by String2
followed by any number of characters or line fields
followed by String1
How to calculate combination and permutation in R?
If you don't want your code to depend on other packages, you can always just write these functions:
perm = function(n, x) {
factorial(n) / factorial(n-x)
}
comb = function(n, x) {
factorial(n) / factorial(n-x) / factorial(x)
}
Getting Django admin url for an object
I solved this by changing the expression to:
reverse( 'django-admin', args=["%s/%s/%s/" % (app_label, model_name, object_id)] )
This requires/assumes that the root url conf has a name for the "admin" url handler, mainly that name is "django-admin",
i.e. in the root url conf:
url(r'^admin/(.*)', admin.site.root, name='django-admin'),
It seems to be working, but I'm not sure of its cleanness.
CSS Background Image Not Displaying
Well I figured it out that this attribute display image when the full location is provided in it. I simply uploaded that image on my server and linked the location of that image in the background-image:url("xxxxx.xxx"); attribute and it finally worked but if you guys don't have server then try to enter the complete location of the image in the attribute by going in property of that image. Although i was using this attribute in tag of an HTML file but it will surely works on CSS file too. If that method didn't work then try to upload your image on internet like behance, facebook, instagram,etc and inspect the image and copy that location to your attribute.. Hope This will work
What are .dex files in Android?
dex
file is a file that is executed on the Dalvik VM.
Dalvik VM includes several features for performance optimization, verification, and monitoring, one of which is Dalvik Executable (DEX).
Java source code is compiled by the Java compiler into .class
files. Then the dx
(dexer) tool, part of the Android SDK processes the .class
files into a file format called DEX
that contains Dalvik byte code. The dx
tool eliminates all the redundant information that is present in the classes. In DEX
all the classes of the application are packed into one file. The following table provides comparison between code sizes for JVM jar files and the files processed by the dex
tool.
The table compares code sizes for system libraries, web browser applications, and a general purpose application (alarm clock app). In all cases dex tool reduced size of the code by more than 50%.
In standard Java environments each class in Java code results in one .class
file. That means, if the Java source code file has one public class and two anonymous classes, let’s say for event handling, then the java compiler will create total three .class
files.
The compilation step is same on the Android platform, thus resulting in multiple .class
files. But after .class
files are generated, the “dx” tool is used to convert all .class
files into a single .dex
, or Dalvik Executable, file. It is the .dex
file that is executed on the Dalvik VM. The .dex
file has been optimized for memory usage and the design is primarily driven by sharing of data.
How to find the socket connection state in C?
On Windows you can query the precise state of any port on any network-adapter using:
GetExtendedTcpTable
You can filter it to only those related to your process, etc and do as you wish periodically monitoring as needed. This is "an alternative" approach.
You could also duplicate the socket handle and set up an IOCP/Overlapped i/o wait on the socket and monitor it that way as well.
How to extract request http headers from a request using NodeJS connect
To see a list of HTTP request headers, you can use :
console.log(JSON.stringify(req.headers));
to return a list in JSON format.
{
"host":"localhost:8081",
"connection":"keep-alive",
"cache-control":"max-age=0",
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests":"1",
"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"en-US,en;q=0.8,et;q=0.6"
}
Java; String replace (using regular expressions)?
If this is for any general math expression and parenthetical expressions are allowed, it will be very difficult (perhaps impossible) to do this with regular expressions.
If the only replacements are the ones you showed, it's not that hard to do. First strip out *
's, then use capturing like Can Berk Güder showed to handle the ^
's.
Center image using text-align center?
The simplest solution I found was to add this to my img-element:
style="display:block;margin:auto;"
It seems I don't need to add "0" before the "auto" as suggested by others. Maybe that is the proper way, but it works well enough for my purposes without the "0" as well. At least on latest Firefox, Chrome, and Edge.
Random record from MongoDB
Using Python (pymongo), the aggregate function also works.
collection.aggregate([{'$sample': {'size': sample_size }}])
This approach is a lot faster than running a query for a random number (e.g. collection.find([random_int]). This is especially the case for large collections.
How to change color in circular progress bar?
<style name="progressColor" parent="Widget.AppCompat.ProgressBar">
<item name="colorControlActivated">@color/colorPrimary</item>
</style>
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="250dp"
android:theme="@style/progressColor"
android:layout_height="250dp"
android:layout_centerInParent="true" />
jQuery changing font family and font size
If you only want to change the font in the TEXTAREA then you only need to change the changeFont() function in the original code to:
function changeFont(_name) {
document.getElementById("mytextarea").style.fontFamily = _name;
}
Then selecting a font will change on the font only in the TEXTAREA.
ng if with angular for string contains
Do checks like that in a controller function. Your HTML should be easy-to-read markup without logic.
Controller:
angular.module("myApp")
.controller("myController",function(){
var self = this;
self.select = { /* ... */ };
self.showFoo = function() {
//Checks if self.select.name contains the character '?'
return self.select.name.indexOf('?') != -1;
}
});
Page example:
<div ng-app="myApp" ng-controller="myController as vm">
<p ng-show="vm.showFoo()">Bar</p>
</div>
Convert float to double without losing precision
I find converting to the binary representation easier to grasp this problem.
float f = 0.27f;
double d2 = (double) f;
double d3 = 0.27d;
System.out.println(Integer.toBinaryString(Float.floatToRawIntBits(f)));
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d2)));
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d3)));
You can see the float is expanded to the double by adding 0s to the end, but that the double representation of 0.27 is 'more accurate', hence the problem.
111110100010100011110101110001
11111111010001010001111010111000100000000000000000000000000000
11111111010001010001111010111000010100011110101110000101001000
Const in JavaScript: when to use it and is it necessary?
2017 Update
This answer still receives a lot of attention. It's worth noting that this answer was posted back at the beginning of 2014 and a lot has changed since then. ecmascript-6 support is now the norm. All modern browsers now support const
so it should be pretty safe to use without any problems.
Original Answer from 2014
Despite having fairly decent browser support, I'd avoid using it for now. From MDN's article on const
:
The current implementation of const is a Mozilla-specific extension and is not part of ECMAScript 5. It is supported in Firefox & Chrome (V8). As of Safari 5.1.7 and Opera 12.00, if you define a variable with const in these browsers, you can still change its value later. It is not supported in Internet Explorer 6-10, but is included in Internet Explorer 11. The const keyword currently declares the constant in the function scope (like variables declared with var).
It then goes on to say:
const
is going to be defined by ECMAScript 6, but with different semantics. Similar to variables declared with the let statement, constants declared with const will be block-scoped.
If you do use const
you're going to have to add in a workaround to support slightly older browsers.
Why can I not push_back a unique_ptr into a vector?
You need to move the unique_ptr
:
vec.push_back(std::move(ptr2x));
unique_ptr
guarantees that a single unique_ptr
container has ownership of the held pointer. This means that you can't make copies of a unique_ptr
(because then two unique_ptr
s would have ownership), so you can only move it.
Note, however, that your current use of unique_ptr
is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:
std::unique_ptr<int> ptr(new int(1));
In C++14 we have an even better way to do so:
make_unique<int>(5);
Linux command to list all available commands and aliases
Why don't you just type:
seachstr
In the terminal.
The shell will say somehing like
seacrhstr: command not found
EDIT:
Ok, I take the downvote, because the answer is stupid, I just want to know: What's wrong with this answer!!! The asker said:
and see if a command is available.
Typing the command will tell you if it is available!.
Probably he/she meant "with out executing the command" or "to include it in a script" but I cannot read his mind ( is not that I can't regularly it is just that he's wearing a
mind reading deflector )
Change priorityQueue to max priorityqueue
We can do this by creating our CustomComparator class that implements Comparator interface and overriding its compare method. Below is the code for the same :
import java.util.PriorityQueue;
import java.util.Comparator;
public class Main
{
public static void main(String[] args) {
PriorityQueue<Integer> nums = new PriorityQueue<>(new CustomComparator());
nums.offer(21);
nums.offer(1);
nums.offer(8);
nums.offer(2);
nums.offer(-4);
System.out.println(nums.peek());
}
}
class CustomComparator implements Comparator<Integer>{
@Override
public int compare(Integer n1, Integer n2){
int val = n1.compareTo(n2);
if(val > 0)
return -1;
else if(val < 0)
return 1;
else
return 0;
}
}
How to automatically generate a stacktrace when my program crashes
It's important to note that once you generate a core file you'll need to use the gdb tool to look at it. For gdb to make sense of your core file, you must tell gcc to instrument the binary with debugging symbols: to do this, you compile with the -g flag:
$ g++ -g prog.cpp -o prog
Then, you can either set "ulimit -c unlimited" to let it dump a core, or just run your program inside gdb. I like the second approach more:
$ gdb ./prog
... gdb startup output ...
(gdb) run
... program runs and crashes ...
(gdb) where
... gdb outputs your stack trace ...
I hope this helps.
Copy row but with new id
THIS WORKS FOR DUPLICATING ONE ROW ONLY
- Select your ONE row from your table
- Fetch all associative
- unset the ID row (Unique Index key)
- Implode the array[0] keys into the column names
- Implode the array[0] values into the column values
- Run the query
The code:
$qrystr = "SELECT * FROM mytablename WHERE id= " . $rowid;
$qryresult = $this->connection->query($qrystr);
$result = $qryresult->fetchAll(PDO::FETCH_ASSOC);
unset($result[0]['id']); //Remove ID from array
$qrystr = " INSERT INTO mytablename";
$qrystr .= " ( " .implode(", ",array_keys($result[0])).") ";
$qrystr .= " VALUES ('".implode("', '",array_values($result[0])). "')";
$result = $this->connection->query($qrystr);
return $result;
Of course you should use PDO:bindparam and check your variables against attack, etc
but gives the example
additional info
If you have a problem with handling NULL
values, you can use following codes so that imploding
names and values only for whose value is not NULL
.
foreach ($result[0] as $index => $value) {
if ($value === null) unset($result[0][$index]);
}
Create SQLite Database and table
The next link will bring you to a great tutorial, that helped me a lot!
How to SQLITE in C#
I nearly used everything in that article to create the SQLite database for my own C# Application.
Don't forget to download the SQLite.dll, and add it as a reference to your project.
This can be done using NuGet and by adding the dll manually.
After you added the reference, refer to the dll from your code using the following line on top of your class:
using System.Data.SQLite;
You can find the dll's here:
SQLite DLL's
You can find the NuGet way here:
NuGet
Up next is the create script.
Creating a database file:
SQLiteConnection.CreateFile("MyDatabase.sqlite");
SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
sql = "insert into highscores (name, score) values ('Me', 9001)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
m_dbConnection.Close();
After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.
Example on how to use transactions:
using (TransactionScope tran = new TransactionScope())
{
//Insert create script here.
//Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
tran.Complete();
}
Get all Attributes from a HTML element with Javascript/jQuery
Setter and Getter!
(function($) {
// Attrs
$.fn.attrs = function(attrs) {
var t = $(this);
if (attrs) {
// Set attributes
t.each(function(i, e) {
var j = $(e);
for (var attr in attrs) {
j.attr(attr, attrs[attr]);
}
});
return t;
} else {
// Get attributes
var a = {},
r = t.get(0);
if (r) {
r = r.attributes;
for (var i in r) {
var p = r[i];
if (typeof p.nodeValue !== 'undefined') a[p.nodeName] = p.nodeValue;
}
}
return a;
}
};
})(jQuery);
Use:
// Setter
$('#element').attrs({
'name' : 'newName',
'id' : 'newId',
'readonly': true
});
// Getter
var attrs = $('#element').attrs();
How do I center a window onscreen in C#?
Might not be completely relevant to the question. But maybe can help someone.
Center Screen non of the above work for me. Reason was I was adding controls dynamically to the form. Technically when it centered it was correct , based on the form before adding the controls.
So here was my solution. ( Should work with both scenarios )
int x = Screen.PrimaryScreen.Bounds.Width - this.PreferredSize.Width;
int y = Screen.PrimaryScreen.Bounds.Height - this.PreferredSize.Height;
this.Location = new Point(x / 2, y / 2);
So you will notice that I am using "PreferredSize" instead of just using Height / Width.
The preferred size will hold the value of the form after adding the controls. Where Height / Width won't.
Hope this helps someone .
Cheers
java.util.Date to XMLGregorianCalendar
Assuming you are decoding or encoding xml and using JAXB
, then it's possible to replace the dateTime binding entirely and use something else than `XMLGregorianCalendar' for every date in the schema.
In that way you can have JAXB
do the repetitive stuff while you can spend the time on writing awesome code that delivers value.
Example for a jodatime DateTime
: (Doing this with java.util.Date would also work - but with certain limitations. I prefer jodatime and it's copied from my code so I know it works...)
<jxb:globalBindings>
<jxb:javaType name="org.joda.time.LocalDateTime" xmlType="xs:dateTime"
parseMethod="test.util.JaxbConverter.parseDateTime"
printMethod="se.seb.bis.test.util.JaxbConverter.printDateTime" />
<jxb:javaType name="org.joda.time.LocalDate" xmlType="xs:date"
parseMethod="test.util.JaxbConverter.parseDate"
printMethod="test.util.JaxbConverter.printDate" />
<jxb:javaType name="org.joda.time.LocalTime" xmlType="xs:time"
parseMethod="test.util.JaxbConverter.parseTime"
printMethod="test.util.JaxbConverter.printTime" />
<jxb:serializable uid="2" />
</jxb:globalBindings>
And the converter:
public class JaxbConverter {
static final DateTimeFormatter dtf = ISODateTimeFormat.dateTimeNoMillis();
static final DateTimeFormatter df = ISODateTimeFormat.date();
static final DateTimeFormatter tf = ISODateTimeFormat.time();
public static LocalDateTime parseDateTime(String s) {
try {
if (StringUtils.trimToEmpty(s).isEmpty())
return null;
LocalDateTime r = dtf.parseLocalDateTime(s);
return r;
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public static String printDateTime(LocalDateTime d) {
try {
if (d == null)
return null;
return dtf.print(d);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public static LocalDate parseDate(String s) {
try {
if (StringUtils.trimToEmpty(s).isEmpty())
return null;
return df.parseLocalDate(s);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public static String printDate(LocalDate d) {
try {
if (d == null)
return null;
return df.print(d);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public static String printTime(LocalTime d) {
try {
if (d == null)
return null;
return tf.print(d);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public static LocalTime parseTime(String s) {
try {
if (StringUtils.trimToEmpty(s).isEmpty())
return null;
return df.parseLocalTime(s);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
See here:
how replace XmlGregorianCalendar by Date?
If you are happy to just map to an instant based on the timezone+timestamp, and the original timezone is not really relevant, then java.util.Date
is probably fine too.
Redirecting new tab on button click.(Response.Redirect) in asp.net C#
You can use Rout redirecting.
protected void btnNewEntry_Click(object sender, EventArgs e)
{
Response.RedirectToRoute("CMS_1");
}
which requires to define your routing logic in Global.asax file that could be like that:
routes.MapPageRoute("CMS_1", "CMS_1", "~/CMS_1.aspx");
where any request by CMS_1 pattern in application scope will be redirecting to CMS_1.aspx, but in URL shows like www.yoursite.com/CMS_1
Add a new line to the end of a JtextArea
Are you using JTextArea
's append(String)
method to add additional text?
JTextArea txtArea = new JTextArea("Hello, World\n", 20, 20);
txtArea.append("Goodbye Cruel World\n");
Checking if a collection is empty in Java: which is the best method?
You should absolutely use isEmpty()
. Computing the size()
of an arbitrary list could be expensive. Even validating whether it has any elements can be expensive, of course, but there's no optimization for size()
which can't also make isEmpty()
faster, whereas the reverse is not the case.
For example, suppose you had a linked list structure which didn't cache the size (whereas LinkedList<E>
does). Then size()
would become an O(N) operation, whereas isEmpty()
would still be O(1)
.
Additionally of course, using isEmpty()
states what you're actually interested in more clearly.
C# event with custom arguments
You need to declare a custom eventhandler.
public class MyEventArgs: EventArgs
{
...
}
public delegate void MyEventHandler(object sender, MyEventArgs e);
public class MyControl: UserControl
{
public event MyEventHandler MyEvent;
...
}
Connect different Windows User in SQL Server Management Studio (2005 or later)
None of these answers did what I needed:
Login to a remote server using a different domain account than I was logged into on my local machine, and it's a client's domain across a vpn. I don't want to be on their domain!
Instead, on the connect to server dialog, select "Windows Authentication", click the Options button, and then on the Additional Connection Parameters tab, enter
user id=domain\user;password=password
SSMS won't remember, but it will connect with that account.
Entity Framework 6 Code first Default value
Set the default value for the column in table in MSSQL Server, and in class code add attribute, like this:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
for the same property.
How do I call an Angular 2 pipe with multiple arguments?
Extended from : user3777549
Multi-value filter on one set of data(reference to title key only)
HTML
<div *ngFor='let item of items | filtermulti: [{title:["mr","ms"]},{first:["john"]}]' >
Hello {{item.first}} !
</div>
filterMultiple
args.forEach(function (filterobj) {
console.log(filterobj)
let filterkey = Object.keys(filterobj)[0];
let filtervalue = filterobj[filterkey];
myobjects.forEach(function (objectToFilter) {
if (!filtervalue.some(x=>x==objectToFilter[filterkey]) && filtervalue != "") {
// object didn't match a filter value so remove it from array via filter
returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
}
})
});
Converting file size in bytes to human-readable string
My answer might be late, but I guess it will help someone.
Metric prefix:
/**
* Format file size in metric prefix
* @param fileSize
* @returns {string}
*/
const formatFileSizeMetric = (fileSize) => {
let size = Math.abs(fileSize);
if (Number.isNaN(size)) {
return 'Invalid file size';
}
if (size === 0) {
return '0 bytes';
}
const units = ['bytes', 'kB', 'MB', 'GB', 'TB'];
let quotient = Math.floor(Math.log10(size) / 3);
quotient = quotient < units.length ? quotient : units.length - 1;
size /= (1000 ** quotient);
return `${+size.toFixed(2)} ${units[quotient]}`;
};
Binary prefix:
/**
* Format file size in binary prefix
* @param fileSize
* @returns {string}
*/
const formatFileSizeBinary = (fileSize) => {
let size = Math.abs(fileSize);
if (Number.isNaN(size)) {
return 'Invalid file size';
}
if (size === 0) {
return '0 bytes';
}
const units = ['bytes', 'kiB', 'MiB', 'GiB', 'TiB'];
let quotient = Math.floor(Math.log2(size) / 10);
quotient = quotient < units.length ? quotient : units.length - 1;
size /= (1024 ** quotient);
return `${+size.toFixed(2)} ${units[quotient]}`;
};
Examples:
// Metrics prefix
formatFileSizeMetric(0) // 0 bytes
formatFileSizeMetric(-1) // 1 bytes
formatFileSizeMetric(100) // 100 bytes
formatFileSizeMetric(1000) // 1 kB
formatFileSizeMetric(10**5) // 10 kB
formatFileSizeMetric(10**6) // 1 MB
formatFileSizeMetric(10**9) // 1GB
formatFileSizeMetric(10**12) // 1 TB
formatFileSizeMetric(10**15) // 1000 TB
// Binary prefix
formatFileSizeBinary(0) // 0 bytes
formatFileSizeBinary(-1) // 1 bytes
formatFileSizeBinary(1024) // 1 kiB
formatFileSizeBinary(2048) // 2 kiB
formatFileSizeBinary(2**20) // 1 MiB
formatFileSizeBinary(2**30) // 1 GiB
formatFileSizeBinary(2**40) // 1 TiB
formatFileSizeBinary(2**50) // 1024 TiB
Show compose SMS view in Android
I add my SMS method if it can help someone.
Be careful with smsManager.sendTextMessage, If the text is too long, the message does not go away. You have to respect max length depending of encoding.
More information here SMS Manager send mutlipart message when there is less than 160 characters
//TO USE EveryWhere
SMSUtils.sendSMS(context, phoneNumber, message);
//Manifest
<!-- SMS -->
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<receiver
android:name=".SMSUtils"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="SMS_SENT"/>
<action android:name="SMS_DELIVERED"/>
</intent-filter>
</receiver>
//JAVA
public class SMSUtils extends BroadcastReceiver {
public static final String SENT_SMS_ACTION_NAME = "SMS_SENT";
public static final String DELIVERED_SMS_ACTION_NAME = "SMS_DELIVERED";
@Override
public void onReceive(Context context, Intent intent) {
//Detect l'envoie de sms
if (intent.getAction().equals(SENT_SMS_ACTION_NAME)) {
switch (getResultCode()) {
case Activity.RESULT_OK: // Sms sent
Toast.makeText(context, context.getString(R.string.sms_send), Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE: // generic failure
Toast.makeText(context, context.getString(R.string.sms_not_send), Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE: // No service
Toast.makeText(context, context.getString(R.string.sms_not_send_no_service), Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU: // null pdu
Toast.makeText(context, context.getString(R.string.sms_not_send), Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF: //Radio off
Toast.makeText(context, context.getString(R.string.sms_not_send_no_radio), Toast.LENGTH_LONG).show();
break;
}
}
//detect la reception d'un sms
else if (intent.getAction().equals(DELIVERED_SMS_ACTION_NAME)) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, context.getString(R.string.sms_receive), Toast.LENGTH_LONG).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(context, context.getString(R.string.sms_not_receive), Toast.LENGTH_LONG).show();
break;
}
}
}
/**
* Test if device can send SMS
* @param context
* @return
*/
public static boolean canSendSMS(Context context) {
return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
}
public static void sendSMS(final Context context, String phoneNumber, String message) {
if (!canSendSMS(context)) {
Toast.makeText(context, context.getString(R.string.cannot_send_sms), Toast.LENGTH_LONG).show();
return;
}
PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT_SMS_ACTION_NAME), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED_SMS_ACTION_NAME), 0);
final SMSUtils smsUtils = new SMSUtils();
//register for sending and delivery
context.registerReceiver(smsUtils, new IntentFilter(SMSUtils.SENT_SMS_ACTION_NAME));
context.registerReceiver(smsUtils, new IntentFilter(DELIVERED_SMS_ACTION_NAME));
SmsManager sms = SmsManager.getDefault();
ArrayList<String> parts = sms.divideMessage(message);
ArrayList<PendingIntent> sendList = new ArrayList<>();
sendList.add(sentPI);
ArrayList<PendingIntent> deliverList = new ArrayList<>();
deliverList.add(deliveredPI);
sms.sendMultipartTextMessage(phoneNumber, null, parts, sendList, deliverList);
//we unsubscribed in 10 seconds
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
context.unregisterReceiver(smsUtils);
}
}, 10000);
}
}
MySQL SELECT WHERE datetime matches day (and not necessarily time)
NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24'
- it is a performance killer:
- it will calculate
DATE()
for all rows, including those, that don't match
- it will make it impossible to use an index for the query
It is much faster to use
SELECT * FROM tablename
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'
as this will allow index use without calculation.
EDIT
As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read
SELECT * FROM tablename
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'
The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.
How can I remove the top and right axis in matplotlib?
This is the suggested Matplotlib 3 solution from the official website HERE:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
ax = plt.subplot(111)
ax.plot(x, y)
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
plt.show()
finished with non zero exit value
Under Centos7 64 bit the issue is that some 32 bit libraries did not exist. To fix this I need to add:
yum install glibc.i686
yum install zlib.i686
yum install libstdc++.i686
How can I increase the size of a bootstrap button?
bootstrap comes with clas btn-lg
http://getbootstrap.com/components/#btn-dropdowns-sizing
<div class="btn btn-default btn-block">
Active
</div>
but if you want to have the button of the width of your column / container add btn-block
<div class="btn btn-default btn-lg">
Active
</div>
However this will expand to 100% so make surt ethat you will wrap your button in certain amount of columns e.g. then you know its always stays 3 columns until xs screen
<div class="col-sm-3">
<div class="btn btn-default btn-block">
Active
</div>
</div>
How to draw border around a UILabel?
Here are some things you can do with UILabel
and its borders.
Here is the code for those labels:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label3: UILabel!
@IBOutlet weak var label4: UILabel!
@IBOutlet weak var label5: UILabel!
@IBOutlet weak var label6: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// label 1
label1.layer.borderWidth = 1.0
// label 2
label2.layer.borderWidth = 5.0
label2.layer.borderColor = UIColor.blue.cgColor
// label 3
label3.layer.borderWidth = 2.0
label3.layer.cornerRadius = 8
// label 4
label4.backgroundColor = UIColor.cyan
// label 5
label5.backgroundColor = UIColor.red
label5.layer.cornerRadius = 8
label5.layer.masksToBounds = true
// label 6
label6.layer.borderWidth = 2.0
label6.layer.cornerRadius = 8
label6.backgroundColor = UIColor.yellow
label6.layer.masksToBounds = true
}
}
Note that in Swift there is no need to import QuartzCore
.
See also
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
How can I add 1 day to current date?
Inspired by jpmottin in this question, here's the one line code:
_x000D_
_x000D_
var dateStr = '2019-01-01';_x000D_
var days = 1;_x000D_
_x000D_
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));_x000D_
_x000D_
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)_x000D_
document.write('<br />');_x000D_
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
_x000D_
_x000D_
_x000D_
Hope this helps
How to embed YouTube videos in PHP?
You have to ask users to store the 11 character code from the youtube video.
For e.g. http://www.youtube.com/watch?v=Ahg6qcgoay4
The eleven character code is : Ahg6qcgoay4
You then take this code and place it in your database. Then wherever you want to place the youtube video in your page, load the character from the database and put the following code:-
e.g. for Ahg6qcgoay4 it will be :
<object width="425" height="350" data="http://www.youtube.com/v/Ahg6qcgoay4" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/Ahg6qcgoay4" /></object>
What is PEP8's E128: continuation line under-indented for visual indent?
This goes also for statements like this (auto-formatted by PyCharm):
return combine_sample_generators(sample_generators['train']), \
combine_sample_generators(sample_generators['dev']), \
combine_sample_generators(sample_generators['test'])
Which will give the same style-warning. In order to get rid of it I had to rewrite it to:
return \
combine_sample_generators(sample_generators['train']), \
combine_sample_generators(sample_generators['dev']), \
combine_sample_generators(sample_generators['test'])
How to ignore ansible SSH authenticity checking?
Use the parameter named as validate_certs to ignore the ssh validation
- ec2_ami:
instance_id: i-0661fa8b45a7531a7
wait: yes
name: ansible
validate_certs: false
tags:
Name: ansible
Service: TestService
By doing this it ignores the ssh validation process
"Could not find acceptable representation" using spring-boot-starter-web
I had a similar error using spring/jhipster
RESTful service (via Postman
)
The endpoint was something like:
@RequestMapping(value = "/index-entries/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<IndexEntry> getIndexEntry(@PathVariable Long id) {
I was attempting to call the restful
endpoint via Postman
with header Accept: text/plain
but I needed to use Accept: application/json
How to call a method after bean initialization is complete?
To expand on the @PostConstruct
suggestion in other answers, this really is the best solution, in my opinion.
- It keeps your code decoupled from the Spring API (
@PostConstruct
is in javax.*
)
- It explicitly annotates your init method as something that needs to be called to initialize the bean
- You don't need to remember to add the init-method attribute to your spring bean definition, spring will automatically call the method (assuming you register the annotation-config option somewhere else in the context, anyway).
How should I use try-with-resources with JDBC?
I realize this was long ago answered but want to suggest an additional approach that avoids the nested try-with-resources double block.
public List<User> getUser(int userId) {
try (Connection con = DriverManager.getConnection(myConnectionURL);
PreparedStatement ps = createPreparedStatement(con, userId);
ResultSet rs = ps.executeQuery()) {
// process the resultset here, all resources will be cleaned up
} catch (SQLException e) {
e.printStackTrace();
}
}
private PreparedStatement createPreparedStatement(Connection con, int userId) throws SQLException {
String sql = "SELECT id, username FROM users WHERE id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, userId);
return ps;
}
Sort a two dimensional array based on one column
install java8 jdk+jre
use lamda expression to sort 2D array.
code:
import java.util.Arrays;
import java.util.Comparator;
class SortString {
public static void main(final String[] args) {
final String[][] data = new String[][] {
new String[] { "2009.07.25 20:24", "Message A" },
new String[] { "2009.07.25 20:17", "Message G" },
new String[] { "2009.07.25 20:25", "Message B" },
new String[] { "2009.07.25 20:30", "Message D" },
new String[] { "2009.07.25 20:01", "Message F" },
new String[] { "2009.07.25 21:08", "Message E" },
new String[] { "2009.07.25 19:54", "Message R" }
};
// this is applicable only in java 8 version.
Arrays.sort(data, (String[] s1, String[] s2) -> s1[0].compareTo(s2[0]));
// we can also use Comparator.comparing and point to Comparable value we want to use
// Arrays.sort(data, Comparator.comparing(row->row[0]));
for (final String[] s : data) {
System.out.println(s[0] + " " + s[1]);
}
}
}
output
2009.07.25 19:54 Message R
2009.07.25 20:01 Message F
2009.07.25 20:17 Message G
2009.07.25 20:24 Message A
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 21:08 Message E
Read and write to binary files in C?
This is an example to read and write binary jjpg or wmv video file.
FILE *fout;
FILE *fin;
Int ch;
char *s;
fin=fopen("D:\\pic.jpg","rb");
if(fin==NULL)
{ printf("\n Unable to open the file ");
exit(1);
}
fout=fopen("D:\\ newpic.jpg","wb");
ch=fgetc(fin);
while (ch!=EOF)
{
s=(char *)ch;
printf("%c",s);
ch=fgetc (fin):
fputc(s,fout);
s++;
}
printf("data read and copied");
fclose(fin);
fclose(fout);
How to get root access on Android emulator?
I used part of the method from the solutions above; however, they did not work completely. On the latest version of Andy, this worked for me:
On Andy (Root Shell) [To get, right click the HandyAndy icon and select Term Shell]
Inside the shell, run these commands:
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
cd /system/bin
cat sh > su && chmod 4775 su
Then, install SuperSU and install SU binary. This will replace the SU binary we just created.
(Optional)
Remove SuperSU and install Superuser by CWM. Install the su binary again.
Now, root works!
"java.lang.OutOfMemoryError: PermGen space" in Maven build
I have found a solution of git bash command when you try to build war using git mvn clean install for
“java.lang.OutOfMemoryError: PermGen space” in Maven build error come
use below command first
$ export MAVEN_OPTS="-Xmx512m -Xss32m"
then use your mvn command to clean install /build war file
$ mvn clean install
NOTE: you don't need -XX:MaxPermSize argument in MAVEN_OPTS when your are using jdk1.8
Java HotSpot(TM) Client VM warning: ignoring option MaxPermSize=XXXm; support was removed in 8.0
<> And Not In VB.NET
I'm a total noob, I came here to figure out VB's 'not equal to' syntax, so I figured I'd throw it in here in case someone else needed it:
<%If Not boolean_variable%>Do this if boolean_variable is false<%End If%>
How to use Git for Unity3D source control?
Unity also Provide its own Source version control. before unity5 it was unityAsset Server but now its depreciated. and launch a new SVN control system called unity collaborate.but the main problem using unity and any SVN is committing and merging scene . but Non of svn give us way to solve this kind of conflicts or merge scene . so depend upon you which SVN you are familiar with . I am using SmartSVN tool on Mac . and turtle on windows .
Ternary operator in AngularJS templates
Update: Angular 1.1.5 added a ternary operator, so now we can simply write
<li ng-class="$first ? 'firstRow' : 'nonFirstRow'">
If you are using an earlier version of Angular, your two choices are:
(condition && result_if_true || !condition && result_if_false)
{true: 'result_if_true', false: 'result_if_false'}[condition]
item 2. above creates an object with two properties. The array syntax is used to select either the property with name true or the property with name false, and return the associated value.
E.g.,
<li class="{{{true: 'myClass1 myClass2', false: ''}[$first]}}">...</li>
or
<li ng-class="{true: 'myClass1 myClass2', false: ''}[$first]">...</li>
$first is set to true inside an ng-repeat for the first element, so the above would apply class 'myClass1' and 'myClass2' only the first time through the loop.
With ng-class there is an easier way though: ng-class takes an expression that must evaluate to one of the following:
- a string of space-delimited class names
- an array of class names
- a map/object of class names to boolean values.
An example of 1) was given above. Here is an example of 3, which I think reads much better:
<li ng-class="{myClass: $first, anotherClass: $index == 2}">...</li>
The first time through an ng-repeat loop, class myClass is added. The 3rd time through ($index starts at 0), class anotherClass is added.
ng-style takes an expression that must evaluate to a map/object of CSS style names to CSS values. E.g.,
<li ng-style="{true: {color: 'red'}, false: {}}[$first]">...</li>
How to dynamic new Anonymous Class?
You can create an ExpandoObject like this:
IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;
And after casting it to dynamic, those values will look like properties:
dynamic d = expando;
Console.WriteLine(d.Name);
However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:
d.GetType().GetProperty("Name")
Correct way to use get_or_create?
From the documentation get_or_create:
# get_or_create() a person with similar first names.
p, created = Person.objects.get_or_create(
first_name='John',
last_name='Lennon',
defaults={'birthday': date(1940, 10, 9)},
)
# get_or_create() didn't have to create an object.
>>> created
False
Explanation:
Fields to be evaluated for similarity, have to be mentioned outside defaults
. Rest of the fields have to be included in defaults
. In case CREATE event occurs, all the fields are taken into consideration.
It looks like you need to be returning into a tuple, instead of a single variable, do like this:
customer.source,created = Source.objects.get_or_create(name="Website")
Adding null values to arraylist
You can add nulls to the ArrayList
, and you will have to check for nulls in the loop:
for(Item i : itemList) {
if (i != null) {
}
}
itemsList.size();
would take the null
into account.
List<Integer> list = new ArrayList<Integer>();
list.add(null);
list.add (5);
System.out.println (list.size());
for (Integer value : list) {
if (value == null)
System.out.println ("null value");
else
System.out.println (value);
}
Output :
2
null value
5
What characters are valid in a URL?
All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)
Based on this related answer, you are looking at a list that looks like: A-Z
, a-z
, 0-9
, -
, .
, _
, ~
, :
, /
, ?
, #
, [
, ]
, @
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, %
, and =
. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. %
can only be used in conjunction with url encoding as in %20
), the RFC has all of these specifics.
how to run the command mvn eclipse:eclipse
The m2e plugin uses it's own distribution of Maven, packaged with the plugin.
In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows
Once Maven is properly installed (i.e. be sure that MAVEN_HOME
, JAVA_HOME
and PATH
variables are set correctly): you must run mvn eclipse:eclipse
from the directory containing the pom.xml
.
Where can I find error log files?
You can use "lsof" to find open logfiles on your system. lsof just gives you a list of all open files.
Use grep for "log" ... use grep again for "php" (if the filename contains the strings "log" and "php" like in "php_error_log" and you are root user you will find the files without knowing the configuration).
root@lnx-work:~# lsof |grep log
... snip
gmain 12148 12274 user 13r REG 252,1 32768 661814 /home/user/.local/share/gvfs-metadata/home-11ab0393.log
gmain 12148 12274 user 21r REG 252,1 32768 662622 /home/user/.local/share/gvfs-metadata/root-56222fe2.log
gvfs-udis 12246 user mem REG 252,1 55384 790567 /lib/x86_64-linux-gnu/libsystemd-login.so.0.7.1
==> apache 12333 user mem REG 252,1 55384 790367 /var/log/http/php_error_log**
... snip
root@lnx-work:~# lsof |grep log |grep php
**apache 12333 user mem REG 252,1 55384 790367 /var/log/http/php_error_log**
... snip
Also see this article on finding open logfiles:
Find open logfiles on a linux system
What exactly does big ? notation represent?
First let's understand what big O, big Theta and big Omega are. They are all sets of functions.
Big O is giving upper asymptotic bound, while big Omega is giving a lower bound. Big Theta gives both.
Everything that is ?(f(n))
is also O(f(n))
, but not the other way around.
T(n)
is said to be in ?(f(n))
if it is both in O(f(n))
and in Omega(f(n))
.
In sets terminology, ?(f(n))
is the intersection of O(f(n))
and Omega(f(n))
For example, merge sort worst case is both O(n*log(n))
and Omega(n*log(n))
- and thus is also ?(n*log(n))
, but it is also O(n^2)
, since n^2
is asymptotically "bigger" than it. However, it is not ?(n^2)
, Since the algorithm is not Omega(n^2)
.
A bit deeper mathematic explanation
O(n)
is asymptotic upper bound. If T(n)
is O(f(n))
, it means that from a certain n0
, there is a constant C
such that T(n) <= C * f(n)
. On the other hand, big-Omega says there is a constant C2
such that T(n) >= C2 * f(n))
).
Do not confuse!
Not to be confused with worst, best and average cases analysis: all three (Omega, O, Theta) notation are not related to the best, worst and average cases analysis of algorithms. Each one of these can be applied to each analysis.
We usually use it to analyze complexity of algorithms (like the merge sort example above). When we say "Algorithm A is O(f(n))
", what we really mean is "The algorithms complexity under the worst1 case analysis is O(f(n))
" - meaning - it scales "similar" (or formally, not worse than) the function f(n)
.
Why we care for the asymptotic bound of an algorithm?
Well, there are many reasons for it, but I believe the most important of them are:
- It is much harder to determine the exact complexity function, thus we "compromise" on the big-O/big-Theta notations, which are informative enough theoretically.
- The exact number of ops is also platform dependent. For example, if we have a vector (list) of 16 numbers. How much ops will it take? The answer is: it depends. Some CPUs allow vector additions, while other don't, so the answer varies between different implementations and different machines, which is an undesired property. The big-O notation however is much more constant between machines and implementations.
To demonstrate this issue, have a look at the following graphs:
It is clear that f(n) = 2*n
is "worse" than f(n) = n
. But the difference is not quite as drastic as it is from the other function. We can see that f(n)=logn
quickly getting much lower than the other functions, and f(n) = n^2
is quickly getting much higher than the others.
So - because of the reasons above, we "ignore" the constant factors (2* in the graphs example), and take only the big-O notation.
In the above example, f(n)=n, f(n)=2*n
will both be in O(n)
and in Omega(n)
- and thus will also be in Theta(n)
.
On the other hand - f(n)=logn
will be in O(n)
(it is "better" than f(n)=n
), but will NOT be in Omega(n)
- and thus will also NOT be in Theta(n)
.
Symetrically, f(n)=n^2
will be in Omega(n)
, but NOT in O(n)
, and thus - is also NOT Theta(n)
.
1Usually, though not always. when the analysis class (worst, average and best) is missing, we really mean the worst case.
What is the difference between a pandas Series and a single-column DataFrame?
from the pandas doc http://pandas.pydata.org/pandas-docs/stable/dsintro.html
Series is a one-dimensional labeled array capable of holding any data type.
To read data in form of panda Series:
import pandas as pd
ds = pd.Series(data, index=index)
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types.
import pandas as pd
df = pd.DataFrame(data, index=index)
In both of the above index is list
for example: I have a csv file with following data:
,country,popuplation,area,capital
BR,Brazil,10210,12015,Brasile
RU,Russia,1025,457,Moscow
IN,India,10458,457787,New Delhi
To read above data as series and data frame:
import pandas as pd
file_data = pd.read_csv("file_path", index_col=0)
d = pd.Series(file_data.country, index=['BR','RU','IN'] or index = file_data.index)
output:
>>> d
BR Brazil
RU Russia
IN India
df = pd.DataFrame(file_data.area, index=['BR','RU','IN'] or index = file_data.index )
output:
>>> df
area
BR 12015
RU 457
IN 457787
How to use FormData in react-native?
Usage of formdata in react-native
I have used react-native-image-picker
to select photo. In my case after choosing the photp from mobile. I'm storing it's info in component state
. After, I'm sending POST
request using fetch
like below
const profile_pic = {
name: this.state.formData.profile_pic.fileName,
type: this.state.formData.profile_pic.type,
path: this.state.formData.profile_pic.path,
uri: this.state.formData.profile_pic.uri,
}
const formData = new FormData()
formData.append('first_name', this.state.formData.first_name);
formData.append('last_name', this.state.formData.last_name);
formData.append('profile_pic', profile_pic);
const Token = 'secret'
fetch('http://10.0.2.2:8000/api/profile/', {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data",
Authorization: `Token ${Token}`
},
body: formData
})
.then(response => console.log(response.json()))
How to clear the text of all textBoxes in the form?
We had a problem like this some weeks before. If you set a breakpoint and have a deep look into this.Controls
, the problem reveals it's nature: you have to recurse through all child controls.
The code could look like this:
private void CleanForm()
{
traverseControlsAndSetTextEmpty(this);
}
private void traverseControlsAndSetTextEmpty(Control control)
{
foreach(var c in control.Controls)
{
if (c is TextBox) ((TextBox)c).Text = String.Empty;
traverseControlsAndSetTextEmpty(c);
}
}
Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository
This is a nasty one... mysterious error and no clear fix.
update/revert/commit did NOT work in my situation. I hadn't done anything weird - just some svn moves.
What DID work for me was:
svn remove offender
svn commit
cd ..
rm -fR parent
svn up parent
cd parent
svn remove offender again
svn commit
copy offender back in (minus .svn dirs)
svn add
svn commit
Weird to say the least. Basically, the svn remove --force offender
wasn't doing completely removing for some reason. Which is sort of what the error message was saying. Only by removing the parent, then updating the parent, did this become obvious because then the offender reappeared! svn removing offender again then properly removed it.
Java decimal formatting using String.format?
NumberFormat and DecimalFormat are definitely what you want. Also, note the NumberFormat.setRoundingMode()
method. You can use it to control how rounding or truncation is applied during formatting.
Regex that matches integers in between whitespace or start/end of string only
Similar to manojlds but includes the optional negative/positive numbers:
var regex = /^[-+]?\d+$/;
EDIT
If you don't want to allow zeros in the front (023
becomes invalid), you could write it this way:
var regex = /^[-+]?[1-9]\d*$/;
EDIT 2
As @DmitriyLezhnev pointed out, if you want to allow the number 0
to be valid by itself but still invalid when in front of other numbers (example: 0
is valid, but 023
is invalid). Then you could use
var regex = /^([+-]?[1-9]\d*|0)$/
SDK Manager.exe doesn't work
find_java.exe doesn't seem to like the openjdk "java -version" output. I edited find_java.bat like this:
for /f %%a in ('%~dps0\find_java.exe -s') do set java_exe=%%a
set java_exe="C:\Program Files (x86)\AdoptOpenJDK\jdk-8.0.242.08-hotspot\bin\java.exe"
rem ...
for /f %%a in ('%~dps0\find_java.exe -s -w') do set javaw_exe=%%a
set javaw_exe="C:\Program Files (x86)\AdoptOpenJDK\jdk-8.0.242.08-hotspot\bin\javaw.exe"
How to deal with SettingWithCopyWarning in Pandas
To remove any doubt, my solution was to make a deep copy of the slice instead of a regular copy.
This may not be applicable depending on your context (Memory constraints / size of the slice, potential for performance degradation - especially if the copy occurs in a loop like it did for me, etc...)
To be clear, here is the warning I received:
/opt/anaconda3/lib/python3.6/site-packages/ipykernel/__main__.py:54:
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
Illustration
I had doubts that the warning was thrown because of a column I was dropping on a copy of the slice. While not technically trying to set a value in the copy of the slice, that was still a modification of the copy of the slice.
Below are the (simplified) steps I have taken to confirm the suspicion, I hope it will help those of us who are trying to understand the warning.
Example 1: dropping a column on the original affects the copy
We knew that already but this is a healthy reminder. This is NOT what the warning is about.
>> data1 = {'A': [111, 112, 113], 'B':[121, 122, 123]}
>> df1 = pd.DataFrame(data1)
>> df1
A B
0 111 121
1 112 122
2 113 123
>> df2 = df1
>> df2
A B
0 111 121
1 112 122
2 113 123
# Dropping a column on df1 affects df2
>> df1.drop('A', axis=1, inplace=True)
>> df2
B
0 121
1 122
2 123
It is possible to avoid changes made on df1 to affect df2. Note: you can avoid importing copy.deepcopy
by doing df.copy()
instead.
>> data1 = {'A': [111, 112, 113], 'B':[121, 122, 123]}
>> df1 = pd.DataFrame(data1)
>> df1
A B
0 111 121
1 112 122
2 113 123
>> import copy
>> df2 = copy.deepcopy(df1)
>> df2
A B
0 111 121
1 112 122
2 113 123
# Dropping a column on df1 does not affect df2
>> df1.drop('A', axis=1, inplace=True)
>> df2
A B
0 111 121
1 112 122
2 113 123
Example 2: dropping a column on the copy may affect the original
This actually illustrates the warning.
>> data1 = {'A': [111, 112, 113], 'B':[121, 122, 123]}
>> df1 = pd.DataFrame(data1)
>> df1
A B
0 111 121
1 112 122
2 113 123
>> df2 = df1
>> df2
A B
0 111 121
1 112 122
2 113 123
# Dropping a column on df2 can affect df1
# No slice involved here, but I believe the principle remains the same?
# Let me know if not
>> df2.drop('A', axis=1, inplace=True)
>> df1
B
0 121
1 122
2 123
It is possible to avoid changes made on df2 to affect df1
>> data1 = {'A': [111, 112, 113], 'B':[121, 122, 123]}
>> df1 = pd.DataFrame(data1)
>> df1
A B
0 111 121
1 112 122
2 113 123
>> import copy
>> df2 = copy.deepcopy(df1)
>> df2
A B
0 111 121
1 112 122
2 113 123
>> df2.drop('A', axis=1, inplace=True)
>> df1
A B
0 111 121
1 112 122
2 113 123
Cheers!
Convert DateTime to TimeSpan
In case you are using WPF and Xceed's TimePicker (which seems to be using DateTime?) as a timespan picker -as I do right now- you can get the total milliseconds (or a TimeSpan) out of it like so:
var milliseconds = DateTimeToTimeSpan(timePicker.Value).TotalMilliseconds;
TimeSpan DateTimeToTimeSpan(DateTime? ts)
{
if (!ts.HasValue) return TimeSpan.Zero;
else return new TimeSpan(0, ts.Value.Hour, ts.Value.Minute, ts.Value.Second, ts.Value.Millisecond);
}
XAML :
<Xceed:TimePicker x:Name="timePicker" Format="Custom" FormatString="H'h 'm'm 's's'" />
If not, I guess you could just adjust my DateTimeToTimeSpan() so that it also takes 'days' into account or do sth like dateTime.Substract(DateTime.MinValue).TotalMilliseconds
.
Best way to find the intersection of multiple sets?
From Python version 2.6 on you can use multiple arguments to set.intersection()
, like
u = set.intersection(s1, s2, s3)
If the sets are in a list, this translates to:
u = set.intersection(*setlist)
where *a_list
is list expansion
Note that set.intersection
is not a static method, but this uses the functional notation to apply intersection of the first set with the rest of the list. So if the argument list is empty this will fail.
Selecting element by data attribute with jQuery
To select all anchors with the data attribute data-customerID==22
, you should include the a
to limit the scope of the search to only that element type. Doing data attribute searches in a large loop or at high frequency when there are many elements on the page can cause performance issues.
$('a[data-customerID="22"]');
Open Bootstrap Modal from code-behind
This method of opening the Modal would not display the Modal for me. I found this as a work arround.
I removed:
ScriptManager.RegisterStartupScript(this,this.GetType(),"Pop", "openModal();", true);
Than I added an asp:label named lblJavaScript and in code behind call:
lblJavaScript.Text = "<script language=\"JavaScript\">openModal()</script>";
Now the Modal will display.
C++ pointer to objects
No you can not do that, MyClass *myclass
will define a pointer (memory for the pointer is allocated on stack) which is pointing at a random memory location. Trying to use this pointer will cause undefined behavior.
In C++, you can create objects either on stack or heap like this:
MyClass myClass;
myClass.DoSomething();
Above will allocate myClass on stack (the term is not there in the standard I think but I am using for clarity). The memory allocated for the object is automatically released when myClass
variable goes out of scope.
Other way of allocating memory is to do a new
. In that case, you have to take care of releasing the memory by doing delete
yourself.
MyClass* p = new MyClass();
p->DoSomething();
delete p;
Remeber the delete
part, else there will be memory leak.
I always prefer to use the stack allocated objects whenever possible as I don't have to be bothered about the memory management.
Difference between webdriver.get() and webdriver.navigate()
driver.get()
is used to navigate particular URL(website) and wait till page load.
driver.navigate()
is used to navigate to particular URL and does not wait to page load. It maintains browser history or cookies to navigate back or forward.
How to reset the state of a Redux store?
With Redux if have applied the following solution, which assumes I have set an initialState in all my reducers (e.g. { user: { name, email }}). In many components I check on these nested properties, so with this fix I prevent my renders methods are broken on coupled property conditions (e.g. if state.user.email, which will throw an error user is undefined if upper mentioned solutions).
const appReducer = combineReducers({
tabs,
user
})
const initialState = appReducer({}, {})
const rootReducer = (state, action) => {
if (action.type === 'LOG_OUT') {
state = initialState
}
return appReducer(state, action)
}
How to run a stored procedure in oracle sql developer?
Consider you've created a procedure like below.
CREATE OR REPLACE PROCEDURE GET_FULL_NAME like
(
FIRST_NAME IN VARCHAR2,
LAST_NAME IN VARCHAR2,
FULL_NAME OUT VARCHAR2
) IS
BEGIN
FULL_NAME:= FIRST_NAME || ' ' || LAST_NAME;
END GET_FULL_NAME;
In Oracle SQL Developer, you can run this procedure in two ways.
1. Using SQL Worksheet
Create a SQL Worksheet and write PL/SQL anonymous block like this and hit f5
DECLARE
FULL_NAME Varchar2(50);
BEGIN
GET_FULL_NAME('Foo', 'Bar', FULL_NAME);
Dbms_Output.Put_Line('Full name is: ' || FULL_NAME);
END;
2. Using GUI Controls
Expand Procedures
Right click on the procudure you've created and Click Run
In the pop-up window, Fill the parameters and Click OK.
Cheers!
jQuery return ajax result into outside variable
I solved it by doing like that:
var return_first = (function () {
var tmp = $.ajax({
'type': "POST",
'dataType': 'html',
'url': "ajax.php?first",
'data': { 'request': "", 'target': arrange_url, 'method':
method_target },
'success': function (data) {
tmp = data;
}
}).done(function(data){
return data;
});
return tmp;
});
- Be careful 'async':fale javascript will be asynchronous.
How to use "not" in xpath?
None of these answers worked for me for python. I solved by this
a[not(@id='XX')]
Also you can use or condition in your xpath by |
operator. Such as
a[not(@id='XX')]|a[not(@class='YY')]
Sometimes we want element which has no class. So you can do like
a[not(@class)]
Shrinking navigation bar when scrolling down (bootstrap3)
If you are using AngularJS, and you are using Angular Bootstrap : https://angular-ui.github.io/bootstrap/
You can do this so nice like this :
HTML:
<nav id="header-navbar" class="navbar navbar-default" ng-class="{'navbar-fixed-top':scrollDown}" role="navigation" scroll-nav>
<div class="container-fluid top-header">
<!--- Rest of code --->
</div>
</nav>
CSS: (Note here I use padding as bigger nav to shrink without padding you can modify as you want)
nav.navbar {
-webkit-transition: all 0.4s ease;
transition: all 0.4s ease;
background-color: white;
margin-bottom: 0;
padding: 25px;
}
.navbar-fixed-top {
padding: 0;
}
And then add your directive
Directive: (Note you may need to change this.pageYOffset >= 50
from 50 to more or less to fulfill your needs)
angular.module('app')
.directive('scrollNav', function ($window) {
return function(scope, element, attrs) {
angular.element($window).bind("scroll", function() {
if (this.pageYOffset >= 50) {
scope.scrollDown = true;
} else {
scope.scrollDown = false;
}
scope.$apply();
});
};
});
This will do the job nicely, animated and cool way.
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:
x = ["0", "1", "2"]
y = int(x[0]) #accessing the zeroth element
If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:
x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)
If your list elements are not strings, you'll have to convert them to strings before using str.join
:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
Also, as stated above, make sure that you're not returning a nested list.
Get size of folder or file
In Java 8:
long size = Files.walk(path).mapToLong( p -> p.toFile().length() ).sum();
It would be nicer to use Files::size
in the map step but it throws a checked exception.
UPDATE:
You should also be aware that this can throw an exception if some of the files/folders are not accessible. See this question and another solution using Guava.
How to run shell script file using nodejs?
you can go:
var cp = require('child_process');
and then:
cp.exec('./myScript.sh', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a command in your $SHELL.
Or go
cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a file WITHOUT a shell.
Or go
cp.execFile();
which is the same as cp.exec() but doesn't look in the $PATH.
You can also go
cp.fork('myJS.js', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a javascript file with node.js, but in a child process (for big programs).
EDIT
You might also have to access stdin and stdout with event listeners. e.g.:
var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
// handle stdout as `data`
});
How to refer to Excel objects in Access VBA?
First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.
After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:
Dim xlApp as Excel.Application
Let's say you added an Excel Workbook Object in your Form and named it xLObject.
Here is how you Access a Sheet of this Object and change a Range
Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"
(I copied the above from my answer to this question)
Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)
currently unable to handle this request HTTP ERROR 500
I was having "(...) unable to handle this request. http error 500" and found out it was from a require_once that was working locally, on a windows machine, with backslash (\) as separator for directories but when i uploaded to my server it stopped working. I changed it to forward slash (/) and now is ok.
require_once ( 'cards\cards.php' ); // **http error 500**
require_once ( 'cards/cards.php' ); // OK
SVG: text inside rect
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g>
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(145,200,103);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(132,168,86);stop-opacity:1" />
</linearGradient>
</defs>
<rect width="220" height="30" class="GradientBorder" fill="url(#grad1)" />
<text x="60" y="20" font-family="Calibri" font-size="20" fill="white" >My Code , Your Achivement....... </text>
</g>
</svg>
Find in Files: Search all code in Team Foundation Server
In my case, writing a small utility in C# helped.
Links that helped me -
http://pascallaurin42.blogspot.com/2012/05/tfs-queries-searching-in-all-files-of.html
How to list files of a team project using tfs api?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Framework.Client;
using System.IO;
namespace TFSSearch
{
class Program
{
static string[] textPatterns = new[] { "void main(", "exception", "RegisterScript" }; //Text to search
static string[] filePatterns = new[] { "*.cs", "*.xml", "*.config", "*.asp", "*.aspx", "*.js", "*.htm", "*.html",
"*.vb", "*.asax", "*.ashx", "*.asmx", "*.ascx", "*.master", "*.svc"}; //file extensions
static void Main(string[] args)
{
try
{
var tfs = TfsTeamProjectCollectionFactory
.GetTeamProjectCollection(new Uri("http://{tfsserver}:8080/tfs/}")); // one some servers you also need to add collection path (if it not the default collection)
tfs.EnsureAuthenticated();
var versionControl = tfs.GetService<VersionControlServer>();
StreamWriter outputFile = new StreamWriter(@"C:\Find.txt");
var allProjs = versionControl.GetAllTeamProjects(true);
foreach (var teamProj in allProjs)
{
foreach (var filePattern in filePatterns)
{
var items = versionControl.GetItems(teamProj.ServerItem + "/" + filePattern, RecursionType.Full).Items
.Where(i => !i.ServerItem.Contains("_ReSharper")); //skipping resharper stuff
foreach (var item in items)
{
List<string> lines = SearchInFile(item);
if (lines.Count > 0)
{
outputFile.WriteLine("FILE:" + item.ServerItem);
outputFile.WriteLine(lines.Count.ToString() + " occurence(s) found.");
outputFile.WriteLine();
}
foreach (string line in lines)
{
outputFile.WriteLine(line);
}
if (lines.Count > 0)
{
outputFile.WriteLine();
}
}
}
outputFile.Flush();
}
}
catch (Exception e)
{
string ex = e.Message;
Console.WriteLine("!!EXCEPTION: " + e.Message);
Console.WriteLine("Continuing... ");
}
Console.WriteLine("========");
Console.Read();
}
// Define other methods and classes here
private static List<string> SearchInFile(Item file)
{
var result = new List<string>();
try
{
var stream = new StreamReader(file.DownloadFile(), Encoding.Default);
var line = stream.ReadLine();
var lineIndex = 0;
while (!stream.EndOfStream)
{
if (textPatterns.Any(p => line.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0))
result.Add("=== Line " + lineIndex + ": " + line.Trim());
line = stream.ReadLine();
lineIndex++;
}
}
catch (Exception e)
{
string ex = e.Message;
Console.WriteLine("!!EXCEPTION: " + e.Message);
Console.WriteLine("Continuing... ");
}
return result;
}
}
}
Access parent URL from iframe
var url = (window.location != window.parent.location) ? document.referrer: document.location;
I found that the above example suggested previously worked when the script was being executed in an iframe however it did not
retrieve the url when the script was executed outside of an iframe,
a slight adjustment was required:
var url = (window.location != window.parent.location) ? document.referrer: document.location.href;
Check if date is in the past Javascript
_x000D_
_x000D_
$('#datepicker').datepicker().change(evt => {_x000D_
var selectedDate = $('#datepicker').datepicker('getDate');_x000D_
var now = new Date();_x000D_
now.setHours(0,0,0,0);_x000D_
if (selectedDate < now) {_x000D_
console.log("Selected date is in the past");_x000D_
} else {_x000D_
console.log("Selected date is NOT in the past");_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<input type="text" id="datepicker" name="event_date" class="datepicker">
_x000D_
_x000D_
_x000D_
How to crop an image in OpenCV using Python
This code crops an image from x=0,y=0 to h=100,w=200.
import numpy as np
import cv2
image = cv2.imread('download.jpg')
y=0
x=0
h=100
w=200
crop = image[y:y+h, x:x+w]
cv2.imshow('Image', crop)
cv2.waitKey(0)
Preventing multiple clicks on button
Disable pointer events in the first line of your callback, and then resume them on the last line.
element.on('click', function() {
element.css('pointer-events', 'none');
//do all of your stuff
element.css('pointer-events', 'auto');
};
XML string to XML document
This code sample is taken from csharp-examples.net, written by Jan Slama:
To find nodes in an XML file you can use XPath expressions. Method XmlNode.SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.SelectSingleNode finds the first node that matches the XPath string.
XML:
<Names>
<Name>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Name>
<Name>
<FirstName>James</FirstName>
<LastName>White</LastName>
</Name>
</Names>
CODE:
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
}
How to share data between different threads In C# using AOP?
You can't beat the simplicity of a locked message queue. I say don't waste your time with anything more complex.
Read up on the lock statement.
lock
EDIT
Here is an example of the Microsoft Queue object wrapped so all actions against it are thread safe.
public class Queue<T>
{
/// <summary>Used as a lock target to ensure thread safety.</summary>
private readonly Locker _Locker = new Locker();
private readonly System.Collections.Generic.Queue<T> _Queue = new System.Collections.Generic.Queue<T>();
/// <summary></summary>
public void Enqueue(T item)
{
lock (_Locker)
{
_Queue.Enqueue(item);
}
}
/// <summary>Enqueues a collection of items into this queue.</summary>
public virtual void EnqueueRange(IEnumerable<T> items)
{
lock (_Locker)
{
if (items == null)
{
return;
}
foreach (T item in items)
{
_Queue.Enqueue(item);
}
}
}
/// <summary></summary>
public T Dequeue()
{
lock (_Locker)
{
return _Queue.Dequeue();
}
}
/// <summary></summary>
public void Clear()
{
lock (_Locker)
{
_Queue.Clear();
}
}
/// <summary></summary>
public Int32 Count
{
get
{
lock (_Locker)
{
return _Queue.Count;
}
}
}
/// <summary></summary>
public Boolean TryDequeue(out T item)
{
lock (_Locker)
{
if (_Queue.Count > 0)
{
item = _Queue.Dequeue();
return true;
}
else
{
item = default(T);
return false;
}
}
}
}
EDIT 2
I hope this example helps.
Remember this is bare bones.
Using these basic ideas you can safely harness the power of threads.
public class WorkState
{
private readonly Object _Lock = new Object();
private Int32 _State;
public Int32 GetState()
{
lock (_Lock)
{
return _State;
}
}
public void UpdateState()
{
lock (_Lock)
{
_State++;
}
}
}
public class Worker
{
private readonly WorkState _State;
private readonly Thread _Thread;
private volatile Boolean _KeepWorking;
public Worker(WorkState state)
{
_State = state;
_Thread = new Thread(DoWork);
_KeepWorking = true;
}
public void DoWork()
{
while (_KeepWorking)
{
_State.UpdateState();
}
}
public void StartWorking()
{
_Thread.Start();
}
public void StopWorking()
{
_KeepWorking = false;
}
}
private void Execute()
{
WorkState state = new WorkState();
Worker worker = new Worker(state);
worker.StartWorking();
while (true)
{
if (state.GetState() > 100)
{
worker.StopWorking();
break;
}
}
}
How to write a file or data to an S3 object using boto3
In boto 3, the 'Key.set_contents_from_' methods were replaced by
For example:
import boto3
some_binary_data = b'Here we have some data'
more_binary_data = b'Here we have some more data'
# Method 1: Object.put()
s3 = boto3.resource('s3')
object = s3.Object('my_bucket_name', 'my/key/including/filename.txt')
object.put(Body=some_binary_data)
# Method 2: Client.put_object()
client = boto3.client('s3')
client.put_object(Body=more_binary_data, Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt')
Alternatively, the binary data can come from reading a file, as described in the official docs comparing boto 2 and boto 3:
Storing Data
Storing data from a file, stream, or string is easy:
# Boto 2.x
from boto.s3.key import Key
key = Key('hello.txt')
key.set_contents_from_file('/tmp/hello.txt')
# Boto 3
s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb'))
Remove Object from Array using JavaScript
You can use map function also.
someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John",lines:"1,19,26,96"}];
newArray=[];
someArray.map(function(obj, index){
if(obj.name !== "Kristian"){
newArray.push(obj);
}
});
someArray = newArray;
console.log(someArray);
How do I check my gcc C++ compiler version for my Eclipse?
gcc -dumpversion
-dumpversion
Print the compiler version (for example, 3.0
) — and don't do anything else.
The same works for following compilers/aliases:
cc -dumpversion
g++ -dumpversion
clang -dumpversion
tcc -dumpversion
Be careful with automate parsing the GCC output:
- Output of
--version
might be localized (e.g. to Russian, Chinese, etc.)
- GCC might be built with option --with-gcc-major-version-only. And some distros (e.g. Fedora) are already using that
- GCC might be built with option --with-pkgversion. And
--version
output will contain something like Android (5220042 based on r346389c) clang version 8.0.7
(it's real version string)
MVC Razor @foreach
What is the best practice on where the logic for the @foreach should be at?
Nowhere, just get rid of it. You could use editor or display templates.
So for example:
@foreach (var item in Model.Foos)
{
<div>@item.Bar</div>
}
could perfectly fine be replaced by a display template:
@Html.DisplayFor(x => x.Foos)
and then you will define the corresponding display template (if you don't like the default one). So you would define a reusable template ~/Views/Shared/DisplayTemplates/Foo.cshtml
which will automatically be rendered by the framework for each element of the Foos collection (IEnumerable<Foo> Foos { get; set; }
):
@model Foo
<div>@Model.Bar</div>
Obviously exactly the same conventions apply for editor templates which should be used in case you want to show some input fields allowing you to edit the view model in contrast to just displaying it as readonly.
minimize app to system tray
This is the method I use in my applications, it's fairly simple and self explanatory but I'm happy to give more details in answer to your comments.
public Form1()
{
InitializeComponent();
// When window state changed, trigger state update.
this.Resize += SetMinimizeState;
// When tray icon clicked, trigger window state change.
systemTrayIcon.Click += ToggleMinimizeState;
}
// Toggle state between Normal and Minimized.
private void ToggleMinimizeState(object sender, EventArgs e)
{
bool isMinimized = this.WindowState == FormWindowState.Minimized;
this.WindowState = (isMinimized) ? FormWindowState.Normal : FormWindowState.Minimized;
}
// Show/Hide window and tray icon to match window state.
private void SetMinimizeState(object sender, EventArgs e)
{
bool isMinimized = this.WindowState == FormWindowState.Minimized;
this.ShowInTaskbar = !isMinimized;
systemTrayIcon.Visible = isMinimized;
if (isMinimized) systemTrayIcon.ShowBalloonTip(500, "Application", "Application minimized to tray.", ToolTipIcon.Info);
}
What is a difference between unsigned int and signed int in C?
Because it's all just about memory, in the end all the numerical values are stored in binary.
A 32 bit unsigned integer can contain values from all binary 0s to all binary 1s.
When it comes to 32 bit signed integer, it means one of its bits (most significant) is a flag, which marks the value to be positive or negative.
How to access first element of JSON object array?
var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' }
console.log(Object.keys(req)[0]);
Make any Object array (req
), then simply do Object.keys(req)[0]
to pick the first key in the Object array.
How do I manage conflicts with git submodules?
First, find the hash you want to your submodule to reference. then run
~/supery/subby $ git co hashpointerhere
~/supery/subby $ cd ../
~/supery $ git add subby
~/supery $ git commit -m 'updated subby reference'
that has worked for me to get my submodule to the correct hash reference and continue on with my work without getting any further conflicts.
Angular2 dynamic change CSS property
I did this plunker to explore one way to do what you want.
Here I get mystyle
from the parent component but you can get it from a service.
import {Component, View} from 'angular2/angular2'
@Component({
selector: '[my-person]',
inputs: [
'name',
'mystyle: customstyle'
],
host: {
'[style.backgroundColor]': 'mystyle.backgroundColor'
}
})
@View({
template: `My Person Component: {{ name }}`
})
export class Person {}
how do I make a single legend for many subplots with matplotlib?
if you are using subplots with bar charts, with different colour for each bar. it may be faster to create the artefacts yourself using mpatches
Say you have four bars with different colours as r
m
c
k
you can set the legend as follows
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
labels = ['Red Bar', 'Magenta Bar', 'Cyan Bar', 'Black Bar']
#####################################
# insert code for the subplots here #
#####################################
# now, create an artist for each color
red_patch = mpatches.Patch(facecolor='r', edgecolor='#000000') #this will create a red bar with black borders, you can leave out edgecolor if you do not want the borders
black_patch = mpatches.Patch(facecolor='k', edgecolor='#000000')
magenta_patch = mpatches.Patch(facecolor='m', edgecolor='#000000')
cyan_patch = mpatches.Patch(facecolor='c', edgecolor='#000000')
fig.legend(handles = [red_patch, magenta_patch, cyan_patch, black_patch],labels=labels,
loc="center right",
borderaxespad=0.1)
plt.subplots_adjust(right=0.85) #adjust the subplot to the right for the legend
Delete with Join in MySQL
You can also use ALIAS like this it works just used it on my database! t is the table need deleting from!
DELETE t FROM posts t
INNER JOIN projects p ON t.project_id = p.project_id
AND t.client_id = p.client_id
How to open a txt file and read numbers in Java
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
NTFS performance and large volumes of files and directories
When you create a folder with N entries, you create a list of N items at file-system level. This list is a system-wide shared data structure. If you then start modifying this list continuously by adding/removing entries, I expect at least some lock contention over shared data. This contention - theoretically - can negatively affect performance.
For read-only scenarios I can't imagine any reason for performance degradation of directories with large number of entries.
How to specify the port an ASP.NET Core application is hosted on?
When hosted in docker containers (linux version for me), you might get a 'Connection Refused' message. In that case you can use IP address 0.0.0.0 which means "all IP addresses on this machine" instead of the localhost loopback to fix the port forwarding.
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls("http://0.0.0.0:5000/")
.Build();
host.Run();
}
}