Easiest implementation.
<script>
$( ".selectpicker" ).change(function() {
alert( "Handler for .change() called." );
});
</script>
Similar to Ryan Rodemoyer's answer, I found that when the UriTemplate on the Contract is not valid you can get this error. In my case, I was using the same parameter twice. For example:
/Root/{Name}/{Name}
I know its a old question but if you are looking to make the button on c# instead of xaml you can set the CornerRadius
that will round your button.
Button buttonRouded = new Button
{
CornerRadius = 10,
};
Rules:
I suggest you add separate overloaded method and add them to your projects Utility/Utilities class.
To check for Collection be empty or null
public static boolean isEmpty(Collection obj) {
return obj == null || obj.isEmpty();
}
or use Apache Commons CollectionUtils.isEmpty()
To check if Map is empty or null
public static boolean isEmpty(Map<?, ?> value) {
return value == null || value.isEmpty();
}
or use Apache Commons MapUtils.isEmpty()
To check for String empty or null
public static boolean isEmpty(String string) {
return string == null || string.trim().isEmpty();
}
or use Apache Commons StringUtils.isBlank()
To check an object is null is easy but to verify if it's empty is tricky as object can have many private or inherited variables and nested objects which should all be empty. For that All need to be verified or some isEmpty() method be in all objects which would verify the objects emptiness.
Ways to refer to a child in jQuery. I summarized it in the following jQuery:
$(this).find("img"); // any img tag child or grandchild etc...
$(this).children("img"); //any img tag child that is direct descendant
$(this).find("img:first") //any img tag first child or first grandchild etc...
$(this).children("img:first") //the first img tag child that is direct descendant
$(this).children("img:nth-child(1)") //the img is first direct descendant child
$(this).next(); //the img is first direct descendant child
Make sure you have full-text search feature installed.
Create full-text search catalog.
use AdventureWorks
create fulltext catalog FullTextCatalog as default
select *
from sys.fulltext_catalogs
Create full-text search index.
create fulltext index on Production.ProductDescription(Description)
key index PK_ProductDescription_ProductDescriptionID
Before you create the index, make sure:
- you don't already have full-text search index on the table as only one full-text search index allowed on a table
- a unique index exists on the table. The index must be based on single-key column, that does not allow NULL.
- full-text catalog exists. You have to specify full-text catalog name explicitly if there is no default full-text catalog.
You can do step 2 and 3 in SQL Sever Management Studio. In object explorer, right click on a table, select Full-Text index
menu item and then Define Full-Text Index...
sub-menu item. Full-Text indexing wizard will guide you through the process. It will also create a full-text search catalog for you if you don't have any yet.
You can find more info at MSDN
you can also use a hashmap for this
@GetMapping
public HashMap<String, Object> get() {
HashMap<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("results", somePOJO);
return map;
}
As @almenon pointed out, this no longer works and it is not the supported way to get package information in your code. The following raises an exception:
import pip
installed_packages = dict([(package.project_name, package.version)
for package in pip.get_installed_distributions()])
To accomplish this, you can import pkg_resources
. Here's an example:
import pkg_resources
installed_packages = dict([(package.project_name, package.version)
for package in pkg_resources.working_set])
I'm on v3.6.5
A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.
You can modify cookies using document.cookie
.
You can easily find many examples how to modify cookies.
I don't think you can, the only other configuration alternative is to enumerate the paths that you want to be filtered, so instead of /*
you could add some for /this/*
and /that/*
etc, but that won't lead to a sufficient solution when you have alot of those paths.
What you can do is add a parameter to the filter providing an expression (like a regular expression) which is used to skip the filter functionality for the paths matched. The servlet container will still call your filter for those url's but you will have better control over the configuration.
Edit
Now that you mention you have no control over the filter, what you could do is either inherit from that filter calling super
methods in its methods except when the url path you want to skip is present and follow the filter chain like @BalusC proposed, or build a filter which instantiates your filter and delegates under the same circumstances. In both cases the filter parameters would include both the expression parameter you add and those of the filter you inherit from or delegate to.
The advantage of building a delegating filter (a wrapper) is that you can add the filter class of the wrapped filter as parameter and reuse it in other situations like this one.
I was facing the same issue while auto-wiring the class from one of my jar file. I fixed the issue by using @Lazy annotation:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
@Autowired
@Lazy
private IGalaxyCommand iGalaxyCommand;
I had this problem for a while and triggerSave()
didn't work, nor did any of the other methods.
So I found a way that worked for me ( I'm adding this here because other people may have already tried triggerSave and etc... ):
tinyMCE.init({
selector: '.tinymce', // This is my <textarea> class
setup : function(ed) {
ed.on('change', function(e) {
// This will print out all your content in the tinyMce box
console.log('the content '+ed.getContent());
// Your text from the tinyMce box will now be passed to your text area ...
$(".tinymce").text(ed.getContent());
});
}
... Your other tinyMce settings ...
});
When you're submitting your form or whatever all you have to do is grab the data from your selector ( In my case: .tinymce
) using $('.tinymce').text()
.
Since the question delves into if DELETE "should" return 200 vs 204 it is worth considering that some people recommend returning an entity with links so the preference is for 200.
"Instead of returning 204 (No Content), the API should be helpful and suggest places to go. In this example I think one obvious link to provide is to" 'somewhere.com/container/' (minus 'resource') "- the container from which the client just deleted a resource. Perhaps the client wishes to delete more resources, so that would be a helpful link."
http://blog.ploeh.dk/2013/04/30/rest-lesson-learned-avoid-204-responses/
If a client encounters a 204 response, it can either give up, go to the entry point of the API, or go back to the previous resource it visited. Neither option is particularly good.
Personally I would not say 204 is wrong (neither does the author; he says "annoying") because good caching at the client side has many benefits. Best is to be consistent either way.
If key
isn't an int
or float
but a str
ing, you need to convert it to an int
first by doing
key = int(key)
or to a float
by doing
key = float(key)
Otherwise, what you have in your question should work, but
if (key < 1) or (key > 34):
or
if not (1 <= key <= 34):
would be a bit clearer.
android:editable
If set, specifies that this TextView
has an input method. It will be a textual one unless it has otherwise been specified. For TextView
, this is false by default. For EditText
, it is true by default.
Must be a boolean
value, either true
or false
.
This may also be a reference to a resource (in the form @[package:]type:name
) or theme attribute (in the form ?[package:][type:]name
) containing a value of this type.
This corresponds to the global attribute resource symbol editable.
Related Methods
this is the implementation of O(n*lg n) using binary search implementation inside a loop.
#include <iostream>
using namespace std;
bool *inMemory;
int pairSum(int arr[], int n, int k)
{
int count = 0;
if(n==0)
return count;
for (int i = 0; i < n; ++i)
{
int start = 0;
int end = n-1;
while(start <= end)
{
int mid = start + (end-start)/2;
if(i == mid)
break;
else if((arr[i] + arr[mid]) == k && !inMemory[i] && !inMemory[mid])
{
count++;
inMemory[i] = true;
inMemory[mid] = true;
}
else if(arr[i] + arr[mid] >= k)
{
end = mid-1;
}
else
start = mid+1;
}
}
return count;
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
inMemory = new bool[10];
for (int i = 0; i < 10; ++i)
{
inMemory[i] = false;
}
cout << pairSum(arr, 10, 11) << endl;
return 0;
}
I don't know a built-in function, but writing one like this shouldn't be too complicated.
def frange(x, y, jump):
while x < y:
yield x
x += jump
As the comments mention, this could produce unpredictable results like:
>>> list(frange(0, 100, 0.1))[-1]
99.9999999999986
To get the expected result, you can use one of the other answers in this question, or as @Tadhg mentioned, you can use decimal.Decimal
as the jump
argument. Make sure to initialize it with a string rather than a float.
>>> import decimal
>>> list(frange(0, 100, decimal.Decimal('0.1')))[-1]
Decimal('99.9')
Or even:
import decimal
def drange(x, y, jump):
while x < y:
yield float(x)
x += decimal.Decimal(jump)
And then:
>>> list(drange(0, 100, '0.1'))[-1]
99.9
You can also by jquery:
$('#foo')[0].disabled = true;
Working example:
$('#foo')[0].disabled = true;
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input id="foo" placeholder="placeholder" value="value" />
_x000D_
Solution:
declare @dt datetime='2018-03-31 05:16:00.000'
IF (Select (DatePart(DAY,@dt)%7))>0
Select (DatePart(DAY,@dt)/7) +1
ELSE
Select (DatePart(DAY,@dt)/7)
With help of destructuring assignment it can be more readable:
let [first, ...rest] = "good_luck_buddy".split('_')
rest = rest.join('_')
if you inistalled mysql Independently you can stop mysql service if running no one of these answers are worked for me this work for me
You could use SwiftString (https://github.com/amayne/SwiftString) to do this.
"string".length // 6
DISCLAIMER: I wrote this extension
It makes sense that constructors complete their execution in order of derivation. Because a superclass has no knowledge of any subclass, any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the subclass. Therefore, it must complete its execution first.
A simple demonstration:
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is:
Inside A's constructor
Inside B's constructor
Inside C's constructor
If you found this thread and wanted to know how to get the selected option text via event here is sample code:
alert(event.target.options[event.target.selectedIndex].text);
Unless you have GNU awk 4.1.0 or later...
You won't have such an option as sed's -i
option so instead do:
$ awk '{print $0}' file > tmp && mv tmp file
Note: the -i
is not magic, it is also creating a temporary file sed
just handles it for you.
As of GNU awk 4.1.0...
GNU awk
added this functionality in version 4.1.0 (released 10/05/2013). It is not as straight forwards as just giving the -i
option as described in the released notes:
The new -i option (from xgawk) is used for loading awk library files. This differs from -f in that the first non-option argument is treated as a script.
You need to use the bundled inplace.awk
include file to invoke the extension properly like so:
$ cat file
123 abc
456 def
789 hij
$ gawk -i inplace '{print $1}' file
$ cat file
123
456
789
The variable INPLACE_SUFFIX
can be used to specify the extension for a backup file:
$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{print $1}' file
$ cat file
123
456
789
$ cat file.bak
123 abc
456 def
789 hij
I am happy this feature has been added but to me, the implementation isn't very awkish as the power comes from the conciseness of the language and -i inplace
is 8 characters too long i.m.o.
Here is a link to the manual for the official word.
For some reason, neither %autoreload
, nor dreload
seem to work for the situation when you import code from one notebook to another. Only plain Python reload
works:
reload(module)
Based on [1].
I believe it must work but any ways I'm not able to identify. Other approach can be,
<textarea (keyup)="emitWordCount(myModel)" [(ngModel)]="myModel"></textarea>
export class TextEditorComponent {
@Output() countUpdate = new EventEmitter<number>();
emitWordCount(model) {
this.countUpdate.emit(
(model.match(/\S+/g) || []).length);
}
}
list1=['x','y','z','a','b','c','d','e','f','g']
find=raw_input("Enter string to be found")
l=list1.index(find)
list1a=[:l]
list1b=[l:]
I know this is an old post but try using an extension method:
public static IEnumerable<DateTime> Range(this DateTime startDate, DateTime endDate)
{
return Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
}
and use it like this
var dates = new DateTime(2000, 1, 1).Range(new DateTime(2000, 1, 31));
Feel free to choose your own dates, you don't have to restrict yourself to January 2000.
I know this is an old topic but this feature has now been implemented since SQL Server 2017. The parameter you're looking for is FIELDQUOTE= which defaults to '"'. See more on https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql?view=sql-server-2017
This structure (function() {})();
is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. So when you're writing these rows:
(function($) {
// do something
})(jQuery);
this means, that the interpreter will invoke the function immediately, and will pass jQuery
as a parameter, which will be used inside the function as $
.
docker start `docker ps -a | awk '{print $1}'`
This will start up all the containers that are in the 'Exited' state
There were (at time of posting) one or two little typos in the accepted answer above, so here's the cleaned up version. In this example I'm stopping the CPU profiler when receiving Ctrl+C.
// capture ctrl+c and stop CPU profiler
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for sig := range c {
log.Printf("captured %v, stopping profiler and exiting..", sig)
pprof.StopCPUProfile()
os.Exit(1)
}
}()
Should be in
Program Files>Microsoft SQL Server>MSSQL 1.0>MSSQL>BACKUP>
In my case it is
C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup
If you use the gui or T-SQL you can specify where you want it T-SQL example
BACKUP DATABASE [YourDB] TO DISK = N'SomePath\YourDB.bak'
WITH NOFORMAT, NOINIT, NAME = N'YourDB Full Database Backup',
SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO
With T-SQL you can also get the location of the backup, see here Getting the physical device name and backup time for a SQL Server database
SELECT physical_device_name,
backup_start_date,
backup_finish_date,
backup_size/1024.0 AS BackupSizeKB
FROM msdb.dbo.backupset b
JOIN msdb.dbo.backupmediafamily m ON b.media_set_id = m.media_set_id
WHERE database_name = 'YourDB'
ORDER BY backup_finish_date DESC
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
Without doing a full revamp of the default routing (#/ViewName) environment, I was able to do a slight modification of Cody's tip and got it working great.
the controller
.controller('GeneralCtrl', ['$route', '$routeParams', '$location',
function($route, $routeParams, $location) {
...
this.goToView = function(viewName){
$location.url('/' + viewName);
}
}]
);
the view
...
<li ng-click="general.goToView('Home')">HOME</li>
...
What brought me to this solution was when I was attempting to integrate a Kendo Mobile UI widget into an angular environment I was losing the context of my controller and the behavior of the regular anchor tag was also being hijacked. I re-established my context from within the Kendo widget and needed to use a method to navigate...this worked.
Thanks for the previous posts!
This error also occurs if you create a sub or function in a 'Microsoft Excel Object' (like Sheet1, Sheet2, ...) instead to create it in a Module.
For example:
you create with VBA a button and set .OnAction = 'btn_action'
. And Sub btn_action
you placed into the Sheet object instead into a Module.
I had the same problem but none of the solutions above helped. The entries in the .gitmodules and in .git/config were right but the command git submodules update --init --recursive
was doing nothing. I also removed the submodule directory and did run git submodules update --init --recursive
and got the submodule directory back but with exactly the same commit as before.
I found the answer on this page. The command is:git submodule update --remote
if you want to wrap the data in td then you can use the below code
td{
width:60%;
word-break: break-word;
}
What about -mmin
?
find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
-exec rm -f {} \;
From man find:
-mmin n File's data was last modified n minutes ago.
Also, make sure to test this first!
... -exec echo rm -f '{}' \; ^^^^ Add the 'echo' so you just see the commands that are going to get run instead of actual trying them first.
One of the way is Using below sql queries
--Size of All Table Space
--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME
--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)", FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
better to use touchstart
event with .on()
jQuery method:
$(window).load(function() { // better to use $(document).ready(function(){
$('.List li').on('click touchstart', function() {
$('.Div').slideDown('500');
});
});
And i don't understand why you are using $(window).load()
method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready()
method which does not wait for each element on the page to be loaded first.
Years later, but a useful option would be to utilize XPath Axes (https://www.w3schools.com/xml/xpath_axes.asp). More specifically, you are looking to use the descendants axes.
I believe this example would do the trick:
//book[descendant::title[@lang='it']]
This allows you to select all book
elements that contain a child title
element (regardless of how deep it is nested) containing language attribute value equal to 'it'.
I cannot say for sure whether or not this answer is relevant to the year 2009 as I am not 100% certain that the XPath Axes existed at that time. What I can confirm is that they do exist today and I have found them to be extremely useful in XPath navigation and I am sure you will as well.
Just use the apache commons codec library. They have a utility class called DigestUtils
No need to get into details.
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
Note: If you are programming in ASP.NET, you can run the script using ScriptManager.RegisterStartupScript in C#:
ScriptManager.RegisterStartupScript(txtField, txtField.GetType(), txtField.AccessKey, "$('#MainContent_txtField').focus(function() { $(this).select(); });", true );
Or just type the script in the HTML page suggested in the other answers.
Try restarting your computer if you just installed SQL Server and there's no choice in the SQL Server Installation Center to install SQL Server Management Studio.
This choice (see image below) only appeared for me after I installed SQL Server, then restarted my computer:
try..
Dim sortedList = From entry In mylist Order By entry.name Ascending Select entry
mylist = sortedList.ToList
Tried in Hive and got the below output
table1
1,wqe,chennai,india
2,stu,salem,india
3,mia,bangalore,india
4,yepie,newyork,USA
table2
1,wqe,chennai,india
2,stu,salem,india
3,mia,bangalore,india
5,chapie,Los angels,USA
Inner Join
SELECT * FROM table1 INNER JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india 1 wqe chennai india
2 stu salem india 2 stu salem india
3 mia bangalore india 3 mia bangalore india
Left Join
SELECT * FROM table1 LEFT JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india 1 wqe chennai india
2 stu salem india 2 stu salem india
3 mia bangalore india 3 mia bangalore india
4 yepie newyork USA NULL NULL NULL NULL
Left Semi Join
SELECT * FROM table1 LEFT SEMI JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india
2 stu salem india
3 mia bangalore india
note: Only records in left table are displayed whereas for Left Join both the table records displayed
How about subtracting one and changing Sunday
IF(DAYOFWEEK() = 1, 7, DAYOFWEEK() - 1)
Of course you would have to do this for every query.
If you want to send ICMP packets in php you can take a look at this Native-PHP ICMP ping implementation, but I didn't test it.
EDIT:
Maybe the site was hacked because it seems that the files got deleted, there is copy in archive.org but you can't download the tar ball file, there are no contact email only contact form, but this will not work at archive.org, we can only wait until the owner will notice that sit is down.
You need to use an older version of the data connectivity driver (2007 Office System Driver: Data Connectivity Components) and select Excel version 2007-2010 in the connection manager configuration window. I assume the newest data connectivity driver for Office 2016 is corrupt
Interestingly I checked this on an app of mine and I got the same error.
I spent a while checking through headers to see if there was anything undef'ing the _USE_MATH_DEFINES
and found nothing.
So I moved the
#define _USE_MATH_DEFINES
#include <cmath>
to be the first thing in my file (I don't use PCHs so if you are you will have to have it after the #include "stdafx.h"
) and suddenly it compile perfectly.
Try moving it higher up the page. Totally unsure as to why this would cause issues though.
Edit: Figured it out. The #include <math.h>
occurs within cmath's header guards. This means that something higher up the list of #includes is including cmath
without the #define
specified. math.h
is specifically designed so that you can include it again with that define now changed to add M_PI
etc. This is NOT the case with cmath
. So you need to make sure you #define _USE_MATH_DEFINES
before you include anything else. Hope that clears it up for you :)
Failing that just include math.h
you are using non-standard C/C++ as already pointed out :)
Edit 2: Or as David points out in the comments just make yourself a constant that defines the value and you have something more portable anyway :)
To copy a directory's content to another directory you can use ansibles copy
module:
- name: Copy content of directory 'files'
copy:
src: files/ # note the '/' <-- !!!
dest: /tmp/files/
From the docs about the src
parameter:
If (src!) path is a directory, it is copied recursively...
... if path ends with "/", only inside contents of that directory are copied to destination.
... if it does not end with "/", the directory itself with all contents is copied.
Of course this will generate each pair twice as each for
loop will go through every item of the list.
You could use some itertools magic here to generate all possible combinations:
import itertools
for a, b in itertools.combinations(mylist, 2):
compare(a, b)
itertools.combinations
will pair each element with each other element in the iterable, but only once.
You could still write this using index-based item access, equivalent to what you are used to, using nested for
loops:
for i in range(len(mylist)):
for j in range(i + 1, len(mylist)):
compare(mylist[i], mylist[j])
Of course this may not look as nice and pythonic but sometimes this is still the easiest and most comprehensible solution, so you should not shy away from solving problems like that.
you can also use append function
b = [ ]
for x in range(0, 5):
b.append(["O"] * 5)
def print_b(b):
for row in b:
print " ".join(row)
Use this Command
if(JButton.getModel().isArmed()){
//your code here.
//your code will be only executed if JButton is clicked.
}
Answer is short. But it worked for me. Use the variable name of your button instead of "JButton".
Another vi command that'll do: :%s/.$//
This removes the last character of each line in the file. The drawback to this search and replace command is that it doesn't care what the last character is, so be careful not to call it twice.
You can use readlink
on /proc/self/fd/NNN
where NNN is the file descriptor. This will give you the name of the file as it was when it was opened — however, if the file was moved or deleted since then, it may no longer be accurate (although Linux can track renames in some cases). To verify, stat
the filename given and fstat
the fd you have, and make sure st_dev
and st_ino
are the same.
Of course, not all file descriptors refer to files, and for those you'll see some odd text strings, such as pipe:[1538488]
. Since all of the real filenames will be absolute paths, you can determine which these are easily enough. Further, as others have noted, files can have multiple hardlinks pointing to them - this will only report the one it was opened with. If you want to find all names for a given file, you'll just have to traverse the entire filesystem.
Well, I am quite surprised that the alternatives to this syntax have not been mentioned. Another common (but older) mechanism is to call a function that isn't defined and rely on the optimizer to compile-out the function call if your assertion is correct.
#define MY_COMPILETIME_ASSERT(test) \
do { \
extern void you_did_something_bad(void); \
if (!(test)) \
you_did_something_bad(void); \
} while (0)
While this mechanism works (as long as optimizations are enabled) it has the downside of not reporting an error until you link, at which time it fails to find the definition for the function you_did_something_bad(). That's why kernel developers starting using tricks like the negative sized bit-field widths and the negative-sized arrays (the later of which stopped breaking builds in GCC 4.4).
In sympathy for the need for compile-time assertions, GCC 4.3 introduced the error
function attribute that allows you to extend upon this older concept, but generate a compile-time error with a message of your choosing -- no more cryptic "negative sized array" error messages!
#define MAKE_SURE_THIS_IS_FIVE(number) \
do { \
extern void this_isnt_five(void) __attribute__((error( \
"I asked for five and you gave me " #number))); \
if ((number) != 5) \
this_isnt_five(); \
} while (0)
In fact, as of Linux 3.9, we now have a macro called compiletime_assert
which uses this feature and most of the macros in bug.h
have been updated accordingly. Still, this macro can't be used as an initializer. However, using by statement expressions (another GCC C-extension), you can!
#define ANY_NUMBER_BUT_FIVE(number) \
({ \
typeof(number) n = (number); \
extern void this_number_is_five(void) __attribute__(( \
error("I told you not to give me a five!"))); \
if (n == 5) \
this_number_is_five(); \
n; \
})
This macro will evaluate its parameter exactly once (in case it has side-effects) and create a compile-time error that says "I told you not to give me a five!" if the expression evaluates to five or is not a compile-time constant.
So why aren't we using this instead of negative-sized bit-fields? Alas, there are currently many restrictions of the use of statement expressions, including their use as constant initializers (for enum constants, bit-field width, etc.) even if the statement expression is completely constant its self (i.e., can be fully evaluated at compile-time and otherwise passes the __builtin_constant_p()
test). Further, they cannot be used outside of a function body.
Hopefully, GCC will amend these shortcomings soon and allow constant statement expressions to be used as constant initializers. The challenge here is the language specification defining what is a legal constant expression. C++11 added the constexpr keyword for just this type or thing, but no counterpart exists in C11. While C11 did get static assertions, which will solve part of this problem, it wont solve all of these shortcomings. So I hope that gcc can make a constexpr functionality available as an extension via -std=gnuc99 & -std=gnuc11 or some such and allow its use on statement expressions et. al.
They are successive, improved versions of the same product. Anyone noticed how the names of the last three and the next release are in alphabetical order (Galileo, Helios, Indigo, Juno)? This is probably how they will go in the future, in the same way that Ubuntu release codenames increase alphabetically (note Indigo is not a moon of Jupiter!).
if you want to combine the 4 bytes into a single int you need to do
int i= (rno[0]<<24)&0xff000000|
(rno[1]<<16)&0x00ff0000|
(rno[2]<< 8)&0x0000ff00|
(rno[3]<< 0)&0x000000ff;
I use 3 special operators |
is the bitwise logical OR &
is the logical AND and <<
is the left shift
in essence I combine the 4 8-bit bytes into a single 32 bit int by shifting the bytes in place and ORing them together
I also ensure any sign promotion won't affect the result with & 0xff
You want to write a function (a recursive function is easiest, but can easily run out of stack space on deep directories) that will enumerate the children of a directory. If you find a child that is a directory, you recurse on that. Otherwise, you delete the files inside. When you are done, the directory is empty and you can remove it via the syscall.
To enumerate directories on Unix, you can use opendir()
, readdir()
, and closedir()
. To remove you use rmdir()
on an empty directory (i.e. at the end of your function, after deleting the children) and unlink()
on a file. Note that on many systems the d_type
member in struct dirent
is not supported; on these platforms, you will have to use stat()
and S_ISDIR(stat.st_mode)
to determine if a given path is a directory.
On Windows, you will use FindFirstFile()
/FindNextFile()
to enumerate, RemoveDirectory()
on empty directories, and DeleteFile()
to remove files.
Here's an example that might work on Unix (completely untested):
int remove_directory(const char *path) {
DIR *d = opendir(path);
size_t path_len = strlen(path);
int r = -1;
if (d) {
struct dirent *p;
r = 0;
while (!r && (p=readdir(d))) {
int r2 = -1;
char *buf;
size_t len;
/* Skip the names "." and ".." as we don't want to recurse on them. */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
continue;
len = path_len + strlen(p->d_name) + 2;
buf = malloc(len);
if (buf) {
struct stat statbuf;
snprintf(buf, len, "%s/%s", path, p->d_name);
if (!stat(buf, &statbuf)) {
if (S_ISDIR(statbuf.st_mode))
r2 = remove_directory(buf);
else
r2 = unlink(buf);
}
free(buf);
}
r = r2;
}
closedir(d);
}
if (!r)
r = rmdir(path);
return r;
}
Using Regular Expressions...
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Return (New System.Text.RegularExpressions.Regex(ch)).Matches(value).Count
End Function
You have to add the order direction right after the column name:
$qb->orderBy('column1 ASC, column2 DESC');
As you have noted, multiple calls to orderBy
do not stack, but you can make multiple calls to addOrderBy
:
$qb->addOrderBy('column1', 'ASC')
->addOrderBy('column2', 'DESC');
There are severals ways to communicate between activities, fragments, services etc. The obvious one is to communicate using interfaces. However, it is not a productive way to communicate. You have to implement the listeners etc.
My suggestion is to use an event bus. Event bus is a publish/subscribe pattern implementation.
You can subscribe to events in your activity and then you can post that events in your fragments etc.
Here on my blog post you can find more detail about this pattern and also an example project to show the usage.
Call getActivity() method inside the onActivityCreated()
I spent some time trying to find a nice function to wrap a solution. Anyway, ended up with this which I feel is a better solutions when loading multiple content on a single page or across a site.
Function:
function ifViewLoadContent(elem, LoadContent)
{
var top_of_element = $(elem).offset().top;
var bottom_of_element = $(elem).offset().top + $(elem).outerHeight();
var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
var top_of_screen = $(window).scrollTop();
if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
if(!$(elem).hasClass("ImLoaded")) {
$(elem).load(LoadContent).addClass("ImLoaded");
}
}
else {
return false;
}
}
You can then call the function using window on scroll (for example, you could also bind it to a click etc. as I also do, hence the function):
To use:
$(window).scroll(function (event) {
ifViewLoadContent("#AjaxDivOne", "someFile/somecontent.html");
ifViewLoadContent("#AjaxDivTwo", "someFile/somemorecontent.html");
});
This approach should also work for scrolling divs etc. I hope it helps, in the question above you could use this approach to load your content in sections, maybe append and thereby dribble feed all that image data rather than bulk feed.
I used this approach to reduce the overhead on https://www.taxformcalculator.com. It died the trick, if you look at the site and inspect element etc. you can see impact on page load in Chrome (as an example).
Handle the Worksheet_Change
event or the Workbook_SheetChange
event.
The event handlers take an argument "Target As Range", so you can check if the range that's changing includes the cell you're interested in.
You may have imported,
project/controllers/base
inside the
project/controllers/routes
You have already imported before. That's not supported.
I couldn't believe that it could be as easy as @john-la-rooy's answer made it seem. So, I recreated the cp
command using line by line reading and writing. It's CRAZY FAST.
#!/usr/bin/env python3.6
import sys
with open(sys.argv[2], 'w') as outfile:
with open(sys.argv[1]) as infile:
for line in infile:
outfile.write(line)
You can download the Apache Standard Taglib and include the jar in your project.
According to the documentation since Symfony 2.1 simply use this shortcut :
$user = $this->getUser();
The above is still working on Symfony 3.2 and is a shortcut for this :
$user = $this->get('security.token_storage')->getToken()->getUser();
The
security.token_storage
service was introduced in Symfony 2.6. Prior to Symfony 2.6, you had to use thegetToken()
method of thesecurity.context
service.
Example : And if you want directly the username :
$username = $this->getUser()->getUsername();
The user will be an object and the class of that object will depend on your user provider.
Sure, what do you want to use for the gid? a static value, PHP var, ...
A static value of 1234 could be like:
INSERT INTO courses (name, location, gid)
SELECT name, location, 1234
FROM courses
WHERE cid = $cid
You just add one additional row before you execute the loop. This row contains your CSV file header name.
schema = ['a','b','c','b']
row = 4
generators = ['A','B','C','D']
with open('test.csv','wb') as csvfile:
writer = csv.writer(csvfile, delimiter=delimiter)
# Gives the header name row into csv
writer.writerow([g for g in schema])
#Data add in csv file
for x in xrange(rows):
writer.writerow([g() for g in generators])
You cannot directly copy a table into a destination server database from a different database if source db is not in your linked servers. But one way is possible that, generate scripts (schema with data) of the desired table into one table temporarily in the source server DB, then execute the script in the destination server DB to create a table with your data. Finally use INSERT INTO [DESTINATION_TABLE] select * from [TEMPORARY_SOURCE_TABLE]. After getting the data into your destination table drop the temporary one.
I found this solution when I faced the same situation. Hope this helps you too.
As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron
. Hence, do install it with:
yum install vixie-cron
And then start it with:
service crond start
To make it persistent, so that it starts on boot, use:
chkconfig crond on
On CentOS 7 you need to use cronie
:
yum install cronie
On CentOS 6 you can install vixie-cron
, but the real package is cronie
:
yum install vixie-cron
and
yum install cronie
In both cases you get the same output:
.../...
==================================================================
Package Arch Version Repository Size
==================================================================
Installing:
cronie x86_64 1.4.4-12.el6 base 73 k
Installing for dependencies:
cronie-anacron x86_64 1.4.4-12.el6 base 30 k
crontabs noarch 1.10-33.el6 base 10 k
exim x86_64 4.72-6.el6 epel 1.2 M
Transaction Summary
==================================================================
Install 4 Package(s)
The above commands are unsafe because you might break your module when switching versions. Instead I recommend the following
npm shrinkwrap
command.npm install -g next-update // from your package next-update
The problem could be due to too many users accessing the db at the same time. Either increase number of users that can concurrently access the db or kick out existing users (or apps). Use "Show processlist;" in the host DB to check connected users;
I came across another reason, catalina.policy file, could prohibit accessing specific IP/PORT
The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.
Step 1:
Step 2:
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
On client:
axios.get('/api', {
params: {
foo: 'bar'
}
});
On server:
function get(req, res, next) {
let param = req.query.foo
.....
}
This is pretty old, but I ran across this question via Google, so perhaps this solution might be useful to others.
function GetObjectName(myObject){
var objectName=JSON.stringify(myObject).match(/"(.*?)"/)[1];
return objectName;
}
It just uses the browser's JSON parser and regex without cluttering up the DOM or your object too much.
What do you mean costs too much? Too much what?
SELECT MAX(Balance) AS MaxBalance, CustomerID FROM CUSTOMERS GROUP BY CustomerID
If your table is properly indexed (Balance) and there has got to be an index on the PK than I am not sure what you mean about costs too much or seems unreliable? There is nothing unreliable about an aggregate that you are using and telling it to do. In this case, MAX()
does exactly what you tell it to do - there's nothing magical about it.
Take a look at MAX()
and if you want to filter it use the HAVING
clause.
Once an image has been loaded in any way into the browser, it will be in the browser cache and will load much faster the next time it is used whether that use is in the current page or in any other page as long as the image is used before it expires from the browser cache.
So, to precache images, all you have to do is load them into the browser. If you want to precache a bunch of images, it's probably best to do it with javascript as it generally won't hold up the page load when done from javascript. You can do that like this:
function preloadImages(array) {
if (!preloadImages.list) {
preloadImages.list = [];
}
var list = preloadImages.list;
for (var i = 0; i < array.length; i++) {
var img = new Image();
img.onload = function() {
var index = list.indexOf(this);
if (index !== -1) {
// remove image from the array once it's loaded
// for memory consumption reasons
list.splice(index, 1);
}
}
list.push(img);
img.src = array[i];
}
}
preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"]);
This function can be called as many times as you want and each time, it will just add more images to the precache.
Once images have been preloaded like this via javascript, the browser will have them in its cache and you can just refer to the normal URLs in other places (in your web pages) and the browser will fetch that URL from its cache rather than over the network.
Eventually over time, the browser cache may fill up and toss the oldest things that haven't been used in awhile. So eventually, the images will get flushed out of the cache, but they should stay there for awhile (depending upon how large the cache is and how much other browsing is done). Everytime the images are actually preloaded again or used in a web page, it refreshes their position in the browser cache automatically so they are less likely to get flushed out of the cache.
The browser cache is cross-page so it works for any page loaded into the browser. So you can precache in one place in your site and the browser cache will then work for all the other pages on your site.
When precaching as above, the images are loaded asynchronously so they will not block the loading or display of your page. But, if your page has lots of images of its own, these precache images can compete for bandwidth or connections with the images that are displayed in your page. Normally, this isn't a noticeable issue, but on a slow connection, this precaching could slow down the loading of the main page. If it was OK for preload images to be loaded last, then you could use a version of the function that would wait to start the preloading until after all other page resources were already loaded.
function preloadImages(array, waitForOtherResources, timeout) {
var loaded = false, list = preloadImages.list, imgs = array.slice(0), t = timeout || 15*1000, timer;
if (!preloadImages.list) {
preloadImages.list = [];
}
if (!waitForOtherResources || document.readyState === 'complete') {
loadNow();
} else {
window.addEventListener("load", function() {
clearTimeout(timer);
loadNow();
});
// in case window.addEventListener doesn't get called (sometimes some resource gets stuck)
// then preload the images anyway after some timeout time
timer = setTimeout(loadNow, t);
}
function loadNow() {
if (!loaded) {
loaded = true;
for (var i = 0; i < imgs.length; i++) {
var img = new Image();
img.onload = img.onerror = img.onabort = function() {
var index = list.indexOf(this);
if (index !== -1) {
// remove image from the array once it's loaded
// for memory consumption reasons
list.splice(index, 1);
}
}
list.push(img);
img.src = imgs[i];
}
}
}
}
preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"], true);
preloadImages(["url99.jpg", "url98.jpg"], true);
I was trying to find a clear answer for Years, Months and Days, and I didn't find anything clear, If you are still looking check this method:
public static string GetDifference(DateTime d1, DateTime d2)
{
int[] monthDay = new int[12] { 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
DateTime fromDate;
DateTime toDate;
int year;
int month;
int day;
int increment = 0;
if (d1 > d2)
{
fromDate = d2;
toDate = d1;
}
else
{
fromDate = d1;
toDate = d2;
}
// Calculating Days
if (fromDate.Day > toDate.Day)
{
increment = monthDay[fromDate.Month - 1];
}
if (increment == -1)
{
if (DateTime.IsLeapYear(fromDate.Year))
{
increment = 29;
}
else
{
increment = 28;
}
}
if (increment != 0)
{
day = (toDate.Day + increment) - fromDate.Day;
increment = 1;
}
else
{
day = toDate.Day - fromDate.Day;
}
// Month Calculation
if ((fromDate.Month + increment) > toDate.Month)
{
month = (toDate.Month + 12) - (fromDate.Month + increment);
increment = 1;
}
else
{
month = (toDate.Month) - (fromDate.Month + increment);
increment = 0;
}
// Year Calculation
year = toDate.Year - (fromDate.Year + increment);
return year + " years " + month + " months " + day + " days";
}
I have tried different kinds of maps and the Conversion Box worked. I have used your map and have pasted an example below with some inner maps. Hope it is helpful to you ....
import java.util.HashMap;
import java.util.Map;
import cjm.component.cb.map.ToMap;
import cjm.component.cb.xml.ToXML;
public class Testing
{
public static void main(String[] args)
{
try
{
Map<String, Object> map = new HashMap<String, Object>(); // ORIGINAL MAP
map.put("name", "chris");
map.put("island", "faranga");
Map<String, String> mapInner = new HashMap<String, String>(); // SAMPLE INNER MAP
mapInner.put("a", "A");
mapInner.put("b", "B");
mapInner.put("c", "C");
map.put("innerMap", mapInner);
Map<String, Object> mapRoot = new HashMap<String, Object>(); // ROOT MAP
mapRoot.put("ROOT", map);
System.out.println("Map: " + mapRoot);
System.out.println();
ToXML toXML = new ToXML();
String convertedXML = String.valueOf(toXML.convertToXML(mapRoot, true)); // CONVERTING ROOT MAP TO XML
System.out.println("Converted XML: " + convertedXML);
System.out.println();
ToMap toMap = new ToMap();
Map<String, Object> convertedMap = toMap.convertToMap(convertedXML); // CONVERTING CONVERTED XML BACK TO MAP
System.out.println("Converted Map: " + convertedMap);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output:
Map: {ROOT={name=chris, innerMap={b=B, c=C, a=A}, island=faranga}}
-------- Map Detected --------
-------- XML created Successfully --------
Converted XML: <ROOT><name>chris</name><innerMap><b>B</b><c>C</c><a>A</a></innerMap><island>faranga</island></ROOT>
-------- XML Detected --------
-------- Map created Successfully --------
Converted Map: {ROOT={name=chris, innerMap={b=B, c=C, a=A}, island=faranga}}
<gradient
android:centerColor="#c1c1c1"
android:endColor="#4f4f4f"
android:gradientRadius="400"
android:startColor="#c1c1c1"
android:type="radial" >
</gradient>
// sort algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
using namespace std;
int main () {
char myints[] = {'F','C','E','G','A','H','B','D'};
vector<char> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33
// using default comparison (operator <):
sort (myvector.begin(), myvector.end()); //(12 32 45 71)26 80 53 33
// print out content:
cout << "myvector contains:";
for (int i=0; i!=8; i++)
cout << ' ' <<myvector[i];
cout << '\n';
system("PAUSE");
return 0;
}
You would generally test these sorts of things in an integration test, which actually connects to a service. To do a unit test, you should test the objects used by your servlet's doGet/doPost methods.
In general you don't want to have much code in your servlet methods, you would want to create a bean class to handle operations and pass your own objects to it and not servlet API objects.
Here's an efficient option that doesn't use the clipboard.
Sub transposeAndPasteRow(rowToCopy As Range, pasteTarget As Range)
pasteTarget.Resize(rowToCopy.Columns.Count) = Application.WorksheetFunction.Transpose(rowToCopy.Value)
End Sub
Use it like this.
Sub test()
Call transposeAndPasteRow(Worksheets("Sheet1").Range("A1:A5"), Worksheets("Sheet2").Range("A1"))
End Sub
Only adapting the Ales's answer and the courtsimas's comment for linux bash:
To keep it in one line use:
git commit -am "comment"
This line will add and commit all changed to repository.
Just make sure there aren't new files that git hasn't picked up yet. otherwise you'll need to use:
git add . ; git commit -am "message"
EDIT: A simple possibility to eliminate before getting into more complicated solutions: have you tried setting the character set to utf8 in the text editor in which you're reading the file? This could just be a case of somebody sending you a utf8 file that you're reading in an editor set to say cp1252.
Just taking the two examples, this is a case of utf8 being read through the lens of a single-byte encoding, likely one of iso-8859-1, iso-8859-15, or cp1252. If you can post examples of other problem characters, it should be possible to narrow that down more.
As visual inspection of the characters can be misleading, you'll also need to look at the underlying bytes: the § you see on screen might be either 0xa7 or 0xc2a7, and that will determine the kind of character set conversion you have to do.
Can you assume that all of your data has been distorted in exactly the same way - that it's come from the same source and gone through the same sequence of transformations, so that for example there isn't a single é in your text, it's always ç? If so, the problem can be solved with a sequence of character set conversions. If you can be more specific about the environment you're in and the database you're using, somebody here can probably tell you how to perform the appropriate conversion.
Otherwise, if the problem characters are only occurring in some places in your data, you'll have to take it instance by instance, based on assumptions along the lines of "no author intended to put ç in their text, so whenever you see it, replace by ç". The latter option is more risky, firstly because those assumptions about the intentions of the authors might be wrong, secondly because you'll have to spot every problem character yourself, which might be impossible if there's too much text to visually inspect or if it's written in a language or writing system that's foreign to you.
The &&
function is not vectorized. You need the &
function:
EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]
If the function floatval does not work you can try to make this :
$string = "2968789218";
$float = $string * 1.0;
echo $float;
But for me all the previous answer worked ( try it in http://writecodeonline.com/php/ ) Maybe the problem is on your server ?
Use TRY_CAST function in exact same way of CAST function. TRY_CAST takes a string and tries to cast it to a data type specified after the AS keyword. If the conversion fails, TRY_CAST returns a NULL instead of failing.
If you want to load csv as a dataframe then you can do the following:
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
df = sqlContext.read.format('com.databricks.spark.csv') \
.options(header='true', inferschema='true') \
.load('sampleFile.csv') # this is your csv file
It worked fine for me.
It comes down to whether the feature is used by one person or if others are working off of it.
You can force the push after the rebase if it's just you:
git push origin feature -f
However, if others are working on it, you should merge and not rebase off of master.
git merge master
git push origin feature
This will ensure that you have a common history with the people you are collaborating with.
On a different level, you should not be doing back-merges. What you are doing is polluting your feature branch's history with other commits that don't belong to the feature, making subsequent work with that branch more difficult - rebasing or not.
This is my article on the subject called branch per feature.
Hope this helps.
I'd start with:
secedit /export /areas USER_RIGHTS /cfg OUTFILE.CFG
Then examine the line for the relevant privilege. However, the problem now is that the accounts are listed as SIDs, not usernames.
Try to surround the path with quotes, and remove the spaces
export PYTHONPATH="/home/user/my_project":$PYTHONPATH
And don't forget to preserve previous content suffixing by :$PYTHONPATH (which is the value of the variable)
Execute the following command to check everything is configured correctly:
echo $PYTHONPATH
var request = require('request');
request.post('http://localhost/test2.php',
{form:{ mes: "heydude" }},
function(error, response, body){
console.log(body);
});
Shouldn't you add to the login form?;
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
As stated in the here in the Spring security documentation
// In ios 7 :-
[self.navigationController.navigationBar setBarTintColor:[UIColor yellowColor]];
// In ios 6 :-
[self.navigationController.navigationBar setTintColor:[UIColor yellowColor]];
var d = $('.text_div');
d.text(d.text().trim().replace(/contains/i, "hello everyone"));
Try swich fetchType from LAZY to EAGER
...
@OneToMany(fetch=FetchType.EAGER)
private Set<NodeValue> nodeValues;
...
But in this case your app will fetch data from DB anyway. If this query very hard - this may impact on performance. More here: https://docs.oracle.com/javaee/6/api/javax/persistence/FetchType.html
==> 73
Changing only what's after hash - old browsers
document.location.hash = 'lookAtMeNow';
Changing full URL. Chrome, Firefox, IE10+
history.pushState('data to be passed', 'Title of the page', '/test');
The above will add a new entry to the history so you can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use
history.replaceState('data to be passed', 'Title of the page', '/test');
Try running these in the console now!
Simple but effective and assumes you know the checkbox will be found:
$("#some_id")[0].checked;
Gives true
/false
I did the following...
app/assets/stylesheets
folder.<%= stylesheet_link_tag "filename" %>
in your default layouts file (most likely application.html.erb
)I recommend this over using your public folder. You can also reference the stylesheet inline, such as in your index page.
Well, by IP is faster.
Basically, when you call by server name, it is converted to original IP.
But it would be difficult to memorize an IP, for this reason the domain name was created.
Personally I use http://localhost
instead of http://127.0.0.1
or http://username
.
For secure HTTPS
<meta property="og:image:secure_url" content="https://image.path.png" />
WHY INTERFACE??????
It starts with a dog. In particular, a pug.
The pug has various behaviors:
public class Pug {
private String name;
public Pug(String n) { name = n; }
public String getName() { return name; }
public String bark() { return "Arf!"; }
public boolean hasCurlyTail() { return true; } }
And you have a Labrador, who also has a set of behaviors.
public class Lab {
private String name;
public Lab(String n) { name = n; }
public String getName() { return name; }
public String bark() { return "Woof!"; }
public boolean hasCurlyTail() { return false; } }
We can make some pugs and labs:
Pug pug = new Pug("Spot");
Lab lab = new Lab("Fido");
And we can invoke their behaviors:
pug.bark() -> "Arf!"
lab.bark() -> "Woof!"
pug.hasCurlyTail() -> true
lab.hasCurlyTail() -> false
pug.getName() -> "Spot"
Let's say I run a dog kennel and I need to keep track of all the dogs I'm housing. I need to store my pugs and labradors in separate arrays:
public class Kennel {
Pug[] pugs = new Pug[10];
Lab[] labs = new Lab[10];
public void addPug(Pug p) { ... }
public void addLab(Lab l) { ... }
public void printDogs() { // Display names of all the dogs } }
But this is clearly not optimal. If I want to house some poodles, too, I have to change my Kennel definition to add an array of Poodles. In fact, I need a separate array for each kind of dog.
Insight: both pugs and labradors (and poodles) are types of dogs and they have the same set of behaviors. That is, we can say (for the purposes of this example) that all dogs can bark, have a name, and may or may not have a curly tail. We can use an interface to define what all dogs can do, but leave it up to the specific types of dogs to implement those particular behaviors. The interface says "here are the things that all dogs can do" but doesn't say how each behavior is done.
public interface Dog
{
public String bark();
public String getName();
public boolean hasCurlyTail(); }
Then I slightly alter the Pug and Lab classes to implement the Dog behaviors. We can say that a Pug is a Dog and a Lab is a dog.
public class Pug implements Dog {
// the rest is the same as before }
public class Lab implements Dog {
// the rest is the same as before
}
I can still instantiate Pugs and Labs as I previously did, but now I also get a new way to do it:
Dog d1 = new Pug("Spot");
Dog d2 = new Lab("Fido");
This says that d1 is not only a Dog, it's specifically a Pug. And d2 is also a Dog, specifically a Lab. We can invoke the behaviors and they work as before:
d1.bark() -> "Arf!"
d2.bark() -> "Woof!"
d1.hasCurlyTail() -> true
d2.hasCurlyTail() -> false
d1.getName() -> "Spot"
Here's where all the extra work pays off. The Kennel class become much simpler. I need only one array and one addDog method. Both will work with any object that is a dog; that is, objects that implement the Dog interface.
public class Kennel {
Dog[] dogs = new Dog[20];
public void addDog(Dog d) { ... }
public void printDogs() {
// Display names of all the dogs } }
Here's how to use it:
Kennel k = new Kennel();
Dog d1 = new Pug("Spot");
Dog d2 = new Lab("Fido");
k.addDog(d1);
k.addDog(d2);
k.printDogs();
The last statement would display: Spot Fido
An interface give you the ability to specify a set of behaviors that all classes that implement the interface will share in common. Consequently, we can define variables and collections (such as arrays) that don't have to know in advance what kind of specific object they will hold, only that they'll hold objects that implement the interface.
I doubt that this is what you want but your question is a little bit vague
Dim totalCount As Int32 = DataTable1.Columns.Count * DataTable1.Rows.Count
If all your columns are numeric-columns you might want this:
You could use DataTable.Compute to Sum
all values in the column.
Dim totalCount As Double
For Each col As DataColumn In DataTable1.Columns
totalCount += Double.Parse(DataTable1.Compute(String.Format("SUM({0})", col.ColumnName), Nothing).ToString)
Next
After you've edited your question and added more informations, this should work:
Dim totalRow = DataTable1.NewRow
For Each col As DataColumn In DataTable1.Columns
totalRow(col.ColumnName) = Double.Parse(DataTable1.Compute("SUM(" & col.ColumnName & ")", Nothing).ToString)
Next
DataTable1.Rows.Add(totalRow)
do you consider using change event ?
$("#myTextBox").change(function() { alert("content changed"); });
Working with Intellj 2016, Angular2, and Typescript... the only thing that worked for me was to get the Typescript Definitions for NodeJS
Get node.d.ts from DefinitelyTyped on GitHub
Or just run:
npm install @types/node --save-dev
Then in tsconfig.json, include
"types": [
"node"
]
Instead:
public class PhotosFragment extends Fragment
You can use:
public class PhotosFragment extends ListFragment
It change the methods
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<ListviewContactItem> listContact = GetlistContact();
setAdapter(new ListviewContactAdapter(getActivity(), listContact));
}
onActivityCreated is void and you didn't need to return a view like in onCreateView
You can see an example here
WebMvcConfigurerAdapter
will be deprecated with Spring 5. From its Javadoc:
@deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made possible by a Java 8 baseline) and can be implemented directly without the need for this adapter
As stated above, what you should do is implementing WebMvcConfigurer
and overriding addInterceptors
method.
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyCustomInterceptor());
}
}
Try using System.getProperty("line.separator")
to get a new line.
I think buffers are e.g. useful when interfacing python to native libraries. (Guido van Rossum explains buffer
in this mailinglist post).
For example, numpy seems to use buffer for efficient data storage:
import numpy
a = numpy.ndarray(1000000)
the a.data
is a:
<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>
We don't need to access the canvas context.
Implementing hednek in pure JS you would get canvas.setAttribute('style', 'background-color:#00F8')
. But my preferred method requires converting the kabab-case to camelCase.
canvas.style.backgroundColor = '#00F8'
You can get much more detailed information than the bash built-in time
(which Robert Gamble mentions) using time(1). Normally this is /usr/bin/time
.
Editor's note:
To ensure that you're invoking the external utility time
rather than your shell's time
keyword, invoke it as /usr/bin/time
.
time
is a POSIX-mandated utility, but the only option it is required to support is -p
.
Specific platforms implement specific, nonstandard extensions: -v
works with GNU's time
utility, as demonstrated below (the question is tagged linux); the BSD/macOS implementation uses -l
to produce similar output - see man 1 time
.
Example of verbose output:
$ /usr/bin/time -v sleep 1
Command being timed: "sleep 1"
User time (seconds): 0.00
System time (seconds): 0.00
Percent of CPU this job got: 1%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.05
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 210
Voluntary context switches: 2
Involuntary context switches: 1
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value)
no add(value)
.
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
For Query parameters like domain.com/test?format=json&type=mini
format, then you can easily receive it via - req.query.
app.get('/test', function(req, res){
var format = req.query.format,
type = req.query.type;
});
i believe what you're looking for is the str.encode("string-escape") function. For example, if you have a variable that you want to 'raw string':
a = '\x89'
a.encode('unicode_escape')
'\\x89'
Note: Use string-escape
for python 2.x and older versions
I was searching for a similar solution and found the solution via: casting raw strings python
When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,
ErrorDocument 404 /yourfoldernames/errors/404.html
The server directive has to be in the http directive. It should not be outside of it.
Incase if you need detailed information, refer this.
Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.
Update for FontAwesome 5 Thanks to Aurelien
You need to change the font-family
to Font Awesome 5 Brands
OR Font Awesome 5 Free
, based on the type of icon you are trying to render. Also, do not forget to declare font-weight: 900;
a:before {
font-family: "Font Awesome 5 Free";
content: "\f095";
display: inline-block;
padding-right: 3px;
vertical-align: middle;
font-weight: 900;
}
You can read the rest of the answer below to understand how it works and to know some workarounds for spacing between icon and the text.
FontAwesome 4 and below
That's the wrong way to use it. Open the font awesome style sheet, go to the class
of the font you want to use say fa-phone
, copy the content property under that class with the entity, and use it like:
a:before {
font-family: FontAwesome;
content: "\f095";
}
Just make sure that if you are looking to target a specific a
tag, then consider using a class
instead to make it more specific like:
a.class_name:before {
font-family: FontAwesome;
content: "\f095";
}
Using the way above will stick the icon with the remaining text of yours, so if you want to have a bit of space between the two of them, make it display: inline-block;
and use some padding-right
:
a:before {
font-family: FontAwesome;
content: "\f095";
display: inline-block;
padding-right: 3px;
vertical-align: middle;
}
Extending this answer further, since many might be having a requirement to change an icon on hover, so for that, we can write a separate selector and rules for :hover
action:
a:hover:before {
content: "\f099"; /* Code of the icon you want to change on hover */
}
Now in the above example, icon nudges because of the different size and you surely don't want that, so you can set a fixed width
on the base declaration like
a:before {
/* Other properties here, look in the above code snippets */
width: 12px; /* add some desired width here to prevent nudge */
}
Simple to trigger finish typing in EditText
worked for me , if you using java convert it
In Kotlin
youredittext.doAfterTextChanged { searchTerm ->
val currentTextLength = searchTerm?.length
Handler().postDelayed({
if (currentTextLength == searchTerm?.length) {
// your code
Log.d("aftertextchange", "ON FINISH TRIGGER")
}
}, 3000)
}
You can use the ternary operator notation:
<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">
1) Add selected class to target element
2) Find all children of parent element excluding target element
3) Remove class from target element
<div id = "outer">
<div class="item" id="inner1">Div 1 </div>
<div class="item" id="inner2">Div 2 </div>
<div class="item" id="inner3">Div 3 </div>
<div class="item" id="inner4">Div 4 </div>
</div>
function getSiblings(target) {
target.classList.add('selected');
let siblings = document.querySelecttorAll('#outer .item:not(.currentlySelected)')
target.classList.remove('selected');
return siblings
}
Apparently it does not and I didn't quite expect it would. HOWEVER Ivan brings up a good possibility that has escaped Android people.
What is the purpose of an emulator? to EMULATE, right? I don't see why for testing purposes -provided the tester understands the limitations- the emulator might not add a Wifi emulator.
It could for example emulate WiFi access by using the underlying internet connection of the host. Obviously testing WPA/WEP differencess would not make sense but at least it could toggle access via WiFi.
Or some sort of emulator plugin where there would be a base WiFi emulator that would emulate WiFi access via the underlying connection but then via configuration it could emulate WPA/WEP by providing a list of fake WiFi networks and their corresponding fake passwords that would be matched against a configurable list of credentials.
After all the idea is to do initial testing on the emulator and then move on to the actual device.
This is a bit high-level answer for applications which want to seamlessly fit into the Windows environment. Technical details of playing particular sound were provided in other answers. Besides that, always note these two points:
Use five standard system sounds in typical scenarios, i.e.
Asterisk - play when you want to highlight current event
Question - play with questions (system message box window plays this one)
Exclamation - play with excalamation icon (system message box window plays this one)
Beep (default system sound)
Critical stop ("Hand") - play with error (system message box window plays this one)
Methods of class System.Media.SystemSounds
will play them for you.
Implement any other sounds as customizable by your users in Sound control panel
This sounds like your browser is caching your css. If you are using Firefox, try loading your page using Shift-Reload.
This is story from my workplace:
- We try to upload multiply images and document files use Struts 1 and Tomcat 7.x.
- We try to write uploaded files to file system, filename and full path to database records.
- We try to separate file folders outside web app directory. (*)
The below solution is pretty simple, effective for requirement (*):
In file META-INF/context.xml
file with the following content:
(Example, my application run at http://localhost:8080/ABC
, my application / project named ABC
).
(this is also full content of file context.xml
)
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/ABC" aliases="/images=D:\images,/docs=D:\docs"/>
(works with Tomcat version 7 or later)
Result: We have been created 2 alias. For example, we save images at: D:\images\foo.jpg
and view from link or using image tag:
<img src="http://localhost:8080/ABC/images/foo.jsp" alt="Foo" height="142" width="142">
or
<img src="/images/foo.jsp" alt="Foo" height="142" width="142">
(I use Netbeans 7.x, Netbeans seem auto create file WEB-INF\context.xml
)
Use Not IsNull(Fields!W_O_Count.Value)
Another option, if you're using temporary tables instead of staging tables, could be to create the temporary table as your import expects, then add the identity column after the import.
So your sql does something like this:
Still not very clean, but it's another option... might have to get locks to be safe, too.
[]
is replaced by %5B%5D
at URL encoding time.
Similar to the answer before there there is
location.host
The location global has more fun facts about the current url as well. ( protocol, host, port, pathname, search, hash )
Two options for runtime type checking with generics:
Option 1 - Corrupt your constructor
Let's assume you are overriding indexOf(...), and you want to check the type just for performance, to save yourself iterating the entire collection.
Make a filthy constructor like this:
public MyCollection<T>(Class<T> t) {
this.t = t;
}
Then you can use isAssignableFrom to check the type.
public int indexOf(Object o) {
if (
o != null &&
!t.isAssignableFrom(o.getClass())
) return -1;
//...
Each time you instantiate your object you would have to repeat yourself:
new MyCollection<Apples>(Apples.class);
You might decide it isn't worth it. In the implementation of ArrayList.indexOf(...), they do not check that the type matches.
Option 2 - Let it fail
If you need to use an abstract method that requires your unknown type, then all you really want is for the compiler to stop crying about instanceof. If you have a method like this:
protected abstract void abstractMethod(T element);
You can use it like this:
public int indexOf(Object o) {
try {
abstractMethod((T) o);
} catch (ClassCastException e) {
//...
You are casting the object to T (your generic type), just to fool the compiler. Your cast does nothing at runtime, but you will still get a ClassCastException when you try to pass the wrong type of object into your abstract method.
NOTE 1: If you are doing additional unchecked casts in your abstract method, your ClassCastExceptions will get caught here. That could be good or bad, so think it through.
NOTE 2: You get a free null check when you use instanceof. Since you can't use it, you may need to check for null with your bare hands.
If you want Rails 3 or Ruby 1.9 compatibility try the date_validator gem.
I took Jeet's answer and adapted it to Windows (thanks to this answer):
FOR /F %x IN ('"git rev-list --all"') DO @git grep <regex> %x > out.txt
Note that for me, for some reason, the actual commit that deleted this regex did not appear in the output of the command, but rather one commit prior to it.
Had this issue occur when everything seemed to be setup correctly, build setting were pointing to correct provisioning profile, code signing was properly setup, etc.
Issue occurred because I had just created a new scheme and hadn't regenerated my CocoaPods for the new configurations. As you can see from the image, the new ad-hoc configuration is pointing to the Pods.production
configuration, instead of a Pods.ad-hoc
configuration (and test respectively)
To fix:
None
-- cocoapods wouldn't generate the configs unless I did thispod install
That's it!
If you want an index to be used and the query not to do a table scan:
WHERE timestamp >= CURDATE()
AND timestamp < CURDATE() + INTERVAL 1 DAY
To show the difference that this makes on the actual execution plans, we'll test with an SQL-Fiddle (an extremely helpful site):
CREATE TABLE test --- simple table
( id INT NOT NULL AUTO_INCREMENT
,`timestamp` datetime --- index timestamp
, data VARCHAR(100) NOT NULL
DEFAULT 'Sample data'
, PRIMARY KEY (id)
, INDEX t_IX (`timestamp`, id)
) ;
INSERT INTO test
(`timestamp`)
VALUES
('2013-02-08 00:01:12'),
--- --- insert about 7k rows
('2013-02-08 20:01:12') ;
Lets try the 2 versions now.
Version 1 with DATE(timestamp) = ?
EXPLAIN
SELECT * FROM test
WHERE DATE(timestamp) = CURDATE() --- using DATE(timestamp)
ORDER BY timestamp ;
Explain:
ID SELECT_TYPE TABLE TYPE POSSIBLE_KEYS KEY KEY_LEN REF
1 SIMPLE test ALL
ROWS FILTERED EXTRA
6671 100 Using where; Using filesort
It filters all (6671) rows and then does a filesort (that's not a problem as the returned rows are few)
Version 2 with timestamp <= ? AND timestamp < ?
EXPLAIN
SELECT * FROM test
WHERE timestamp >= CURDATE()
AND timestamp < CURDATE() + INTERVAL 1 DAY
ORDER BY timestamp ;
Explain:
ID SELECT_TYPE TABLE TYPE POSSIBLE_KEYS KEY KEY_LEN REF
1 SIMPLE test range t_IX t_IX 9
ROWS FILTERED EXTRA
2 100 Using where
It uses a range scan on the index, and then reads only the corresponding rows from the table.
if (!$.trim($("element").val())) {
}
the data object is a buffer of bytes. Simply call .toString()
to get human-readable code:
console.log( data.toString() );
reference: Node.js buffers
Also make sure the page is valid. You can check this in the browsers developer tools (F12)
In the Console tab select the correct Target/Frame and check for the [Page_IsValid] property
If the page is not valid the form will not submit and therefore not fire the event.
This is what I used to copy some resource files: the copy-files is an empty target to ignore errors
add_custom_target(copy-files ALL
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_BINARY_DIR}/SOURCEDIRECTORY
${CMAKE_BINARY_DIR}/DESTINATIONDIRECTORY
)
Very simple and clean function to break the back arrow without interfering with the page afterward.
Benefits:
onbeforeunload
setInterval
, so it doesn't break slow browsers and always works.unbeforeunload
which interrupts user with modal dialog.Note: some of the other solutions use onbeforeunload
. Please do not use onbeforeunload
for this purpose, which pops up a dialog whenever users try to close the window, hit backarrow, etc. Modals like onbeforeunload
are usually only appropriate in rare circumstances, such as when they've actually made changes on screen and haven't saved them, not for this purpose.
How It Works
That's it. No further messing around, no background event monitoring, nothing else.
Use It In One Second
To deploy, just add this anywhere on your page or in your JavaScript code:
<script>
/* Break back button */
window.onload = function(){
var i = 0;
var previous_hash = window.location.hash;
var x = setInterval(function(){
i++;
window.location.hash = "/noop/" + i;
if (i==10){
clearInterval(x);
window.location.hash = previous_hash;
}
}, 10);
}
</script>
I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands
OP, you can convert a string to type Boolean
by using any of the methods stated below:
string sample = "True";
bool myBool = bool.Parse(sample);
///or
bool myBool = Convert.ToBoolean(sample);
bool.Parse
expects one parameter which in this case is sample
, .ToBoolean
also expects one parameter.
You can use TryParse
which is the same as Parse
but it doesn't throw any exception :)
string sample = "false";
Boolean myBool;
if (Boolean.TryParse(sample , out myBool))
{
}
Please note that you cannot convert any type of string to type Boolean
because the value of a Boolean
can only be True
or False
Hope you understand :)
the complete know how, i have included a example of the triggers and sequence
create table temasforo(
idtemasforo NUMBER(5) PRIMARY KEY,
autor VARCHAR2(50) NOT NULL,
fecha DATE DEFAULT (sysdate),
asunto LONG );
create sequence temasforo_seq
start with 1
increment by 1
nomaxvalue;
create or replace
trigger temasforo_trigger
before insert on temasforo
referencing OLD as old NEW as new
for each row
begin
:new.idtemasforo:=temasforo_seq.nextval;
end;
reference: http://thenullpointerexceptionx.blogspot.mx/2013/06/llaves-primarias-auto-incrementales-en.html
Programmers from structural programming language background know it as a function while in OOPS it's called a method.
But there's not any difference between the two.
In the old days, methods did not return values and functions did. Now they both are used interchangeably.
I used accepted answer reference and would like to put an example, since Angular 2 documentation is very very hard to read, I hope this is easier:
Import NgZone
:
import { Component, NgZone } from '@angular/core';
Add it to your class constructor
constructor(public zone: NgZone, ...args){}
Run code with zone.run
:
this.zone.run(() => this.donations = donations)
It's a convention in Ruby that methods that return boolean values end in a question mark. There's no more significance to it than that.
In my case, I couldn't see any of the controls in the project. Only when right clicking on toolBox and selecting "Show All" I saw them, but yet they were disabled...
Changing Project type from Windows application to ClassLibrary made the fix.
Upon downloading Bootstrap 3.x, you'll get bootstrap.css and bootstrap-theme.css (not to mention the minified versions of these files that are also present).
bootstrap.css
is completely styled and ready to use, if such is your desire. It is perhaps a bit plain but it is ready and it is there.
You do not need to use bootstrap-theme.css if you don't want to and things will be just fine.
bootstrap-theme.css
is just what the name of the file is trying to suggest: it is a theme for bootstrap that is creatively considered 'THE bootstrap theme'. The name of the file confuses things just a bit since the base bootstrap.css
already has styling applied and I, for one, would consider those styles to be the default. But that conclusion is apparently incorrect in light of things said in the Bootstrap documentation's examples section in regard to this bootstrap-theme.css
file:
"Load the optional Bootstrap theme for a visually enhanced experience."
The above quote is found here http://getbootstrap.com/getting-started/#examples on a thumbnail that links to this example page http://getbootstrap.com/examples/theme/. The idea is that bootstrap-theme.css
is THE bootstrap theme AND it's optional.
About the themes at BootSwatch.com: These themes are not implemented like bootstrap-theme.css
. The BootSwatch themes are modified versions of the original bootstrap.css
. So, you should definitely NOT use a theme from BootSwatch AND the bootstrap-theme.css
file at the same time.
About Your Own Custom Theme: You might choose to modify bootstrap-theme.css
when creating your own theme. Doing so may make it easier to make styling changes without accidentally breaking any of that built-in Bootstrap goodness.
On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql
There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.
If you have a local version of the repository, you might want to try this crude shell script I wrote to open the GitHub pages for all commits matching your search term in new tabs in your default browser:
#!/bin/sh
for sha1 in $(git rev-list HEAD -i --grep="$1"); do
python -mwebbrowser https://github.com/RepoOwnerUserName/RepoName/commit/$sha1 >/dev/null 2>/dev/null
done
Just replace https://github.com/RepoOwnerUserName/RepoName/
with the actual GitHub URL of your repository, save the script somewhere (e.g. as githubsearch.sh
, make it executable (chmod +x githubsearch.sh
) and then add the following alias to your ~/.bashrc
file:
alias githubsearch='/path/to/githubsearch.sh'
Then, from anywhere in your Git repository, just do this at the terminal:
githubsearch "what you want to search for"
and any commits that match your (case insensitive) search term will have their corresponding GitHub pages opened in your browser. (Be warned that if your search term appears in hundreds of commits, this may well crash your browser and eat your PC's CPU for a while.)
If removing \0 from the end of string is impossible, you can add your own character for each string you encode, and remove it on decode.
You should have access to the POST dictionary on the request object.
For splitting an InputStream
in two, while avoiding to load all data in memory, and then process them independently:
OutputStream
, precisely: PipedOutputStream
PipedInputStream
are the returned InputStream
.OutputStream
. So, everything read it from the sourcing InputStream
, would be written in both OutputStream
. There is not need to implement that, because it is done already in TeeInputStream
(commons.io).Within a separated thread read the whole sourcing inputStream, and implicitly the input data is transferred to the target inputStreams.
public static final List<InputStream> splitInputStream(InputStream input)
throws IOException
{
Objects.requireNonNull(input);
PipedOutputStream pipedOut01 = new PipedOutputStream();
PipedOutputStream pipedOut02 = new PipedOutputStream();
List<InputStream> inputStreamList = new ArrayList<>();
inputStreamList.add(new PipedInputStream(pipedOut01));
inputStreamList.add(new PipedInputStream(pipedOut02));
TeeOutputStream tout = new TeeOutputStream(pipedOut01, pipedOut02);
TeeInputStream tin = new TeeInputStream(input, tout, true);
Executors.newSingleThreadExecutor().submit(tin::readAllBytes);
return Collections.unmodifiableList(inputStreamList);
}
Be aware to close the inputStreams after being consumed, and close the thread that runs: TeeInputStream.readAllBytes()
In case, you need to split it into multiple InputStream
, instead of just two. Replace in the previous fragment of code the class TeeOutputStream
for your own implementation, which would encapsulate a List<OutputStream>
and override the OutputStream
interface:
public final class TeeListOutputStream extends OutputStream {
private final List<? extends OutputStream> branchList;
public TeeListOutputStream(final List<? extends OutputStream> branchList) {
Objects.requireNonNull(branchList);
this.branchList = branchList;
}
@Override
public synchronized void write(final int b) throws IOException {
for (OutputStream branch : branchList) {
branch.write(b);
}
}
@Override
public void flush() throws IOException {
for (OutputStream branch : branchList) {
branch.flush();
}
}
@Override
public void close() throws IOException {
for (OutputStream branch : branchList) {
branch.close();
}
}
}
Move excel variables which are global declare in your form to local like in my form I have:
Dim xls As New MyExcel.Interop.Application
Dim xlb As MyExcel.Interop.Workbook
above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.
The following program calculates nCr
in an efficient manner (compared to calculating factorials etc.)
import operator as op
from functools import reduce
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom # or / in Python 2
As of Python 3.8, binomial coefficients are available in the standard library as math.comb
:
>>> from math import comb
>>> comb(10,3)
120
You'll need to serialize to something: that is, pick binary, or xml (for default serializers) or write custom serialization code to serialize to some other text form.
Once you've picked that, your serialization will (normally) call a Stream that is writing to some kind of file.
So, with your code, if I were using XML Serialization:
var path = @"C:\Test\myserializationtest.xml";
using(FileStream fs = new FileStream(path, FileMode.Create))
{
XmlSerializer xSer = new XmlSerializer(typeof(SomeClass));
xSer.Serialize(fs, serializableObject);
}
Then, to deserialize:
using(FileStream fs = new FileStream(path, FileMode.Open)) //double check that...
{
XmlSerializer _xSer = new XmlSerializer(typeof(SomeClass));
var myObject = _xSer.Deserialize(fs);
}
NOTE: This code hasn't been compiled, let alone run- there may be some errors. Also, this assumes completely out-of-the-box serialization/deserialization. If you need custom behavior, you'll need to do additional work.
The slickest method woud be to use LINQ:
var fileCount = (from file in Directory.EnumerateFiles(@"H:\iPod_Control\Music", "*.mp3", SearchOption.AllDirectories)
select file).Count();
Another way to get to the deleted commit is with the git fsck
command.
git fsck --lost-found
This will output something like at the last line:
dangling commit xyz
We can check that it is the same commit using reflog
as suggested in other answers. Now we can do a git merge
git merge xyz
Note:
We cannot get the commit back with fsck
if we have already run a git gc
command which will remove the reference to the dangling commit.
YAML supports inline comments, but does not support block comments.
From Wikipedia:
Comments begin with the number sign (
#
), can start anywhere on a line, and continue until the end of the line
A comparison with JSON, also from Wikipedia:
The syntax differences are subtle and seldom arise in practice: JSON allows extended charactersets like UTF-32, YAML requires a space after separators like comma, equals, and colon while JSON does not, and some non-standard implementations of JSON extend the grammar to include Javascript's
/* ... */
comments. Handling such edge cases may require light pre-processing of the JSON before parsing as in-line YAML.
# If you want to write
# a block-commented Haiku
# you'll need three pound signs
I had let this go for a good while but revisited it later. Since this question is viewed regularly. This is eventually what I ended up using that worked for me.
define("DOC_ROOT","/path/to/html");
//username and password of account
$username = trim($values["email"]);
$password = trim($values["password"]);
//set the directory for the cookie using defined document root var
$path = DOC_ROOT."/ctemp";
//build a unique path with every request to store. the info per user with custom func. I used this function to build unique paths based on member ID, that was for my use case. It can be a regular dir.
//$path = build_unique_path($path); // this was for my use case
//login form action url
$url="https://www.example.com/login/action";
$postinfo = "email=".$username."&password=".$password;
$cookie_file_path = $path."/cookie.txt";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
//set the cookie the site has for certain features, this is optional
curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0");
curl_setopt($ch, CURLOPT_USERAGENT,
"Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
curl_exec($ch);
//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/page/");
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);
Update: This code was never meant to be a copy and paste. It was to show how I used it for my specific use case. You should adapt it to your code as needed. Such as directories, vars etc
It involves eyeballing it (well I suppose you could get out a calculator and calculate) but just insert said control on the form and then remove any anchoring (anchor = None).
This issue occurs because of web application security model policy that is Same Origin Policy Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. That means requester must match the exact host, protocol, and port of requesting site.
We have multiple options to over come this CORS header issue.
Using Proxy - In this solution we will run a proxy such that when request goes through the proxy it will appear like it is some same origin. If you are using the nodeJS you can use cors-anywhere to do the proxy stuff. https://www.npmjs.com/package/cors-anywhere.
Example:-
var host = process.env.HOST || '0.0.0.0';
var port = process.env.PORT || 8080;
var cors_proxy = require('cors-anywhere');
cors_proxy.createServer({
originWhitelist: [], // Allow all origins
requireHeader: ['origin', 'x-requested-with'],
removeHeaders: ['cookie', 'cookie2']
}).listen(port, host, function() {
console.log('Running CORS Anywhere on ' + host + ':' + port);
});
JSONP - JSONP is a method for sending JSON data without worrying about cross-domain issues.It does not use the XMLHttpRequest object.It uses the <script>
tag instead. https://www.w3schools.com/js/js_json_jsonp.asp
Server Side - On server side we need to enable cross-origin requests. First we will get the Preflighted requests (OPTIONS) and we need to allow the request that is status code 200 (ok).
Preflighted requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if it uses methods other than GET or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted. It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)
If you are using the spring just adding the bellow code will resolves the issue. Here I have disabled the csrf token that doesn't matter enable/disable according to your requirement.
@SpringBootApplication
public class SupplierServicesApplication {
public static void main(String[] args) {
SpringApplication.run(SupplierServicesApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
}
If you are using the spring security use below code along with above code.
@Configuration
@EnableWebSecurity
public class SupplierSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll().antMatchers("/**").authenticated().and()
.httpBasic();
}
}
Android ready county list and flag images
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- country list -->
<string-array name="data000">
<item name="code">+93</item>
<item name="country">Afghanistan</item>
<item name="iso">AF</item>
<item name="flag">@drawable/afghanistan</item>
</string-array>
<string-array name="data001">
<item name="code">+355</item>
<item name="country">Albania</item>
<item name="iso">AL</item>
<item name="flag">@drawable/albania</item>
</string-array>
...
<array name="countries">
<item>@array/data000</item>
<item>@array/data001</item>
...
</array>
</resources>
A slight tangent -- if you want to parse and evaluate an entire expression string which contains (nested!) functions, consider NCalc (http://ncalc.codeplex.com/ and nuget)
Ex. slightly modified from the project documentation:
// the expression to evaluate, e.g. from user input (like a calculator program, hint hint college students)
var exprStr = "10 + MyFunction(3, 6)";
Expression e = new Expression(exprString);
// tell it how to handle your custom function
e.EvaluateFunction += delegate(string name, FunctionArgs args) {
if (name == "MyFunction")
args.Result = (int)args.Parameters[0].Evaluate() + (int)args.Parameters[1].Evaluate();
};
// confirm it worked
Debug.Assert(19 == e.Evaluate());
And within the EvaluateFunction
delegate you would call your existing function.
Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step.
import collections
def flatten(d, parent_key='', sep='_'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(flatten(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
>>> flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]})
{'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}
My suggestion is: do not use activities at all, instead use fragments, and replace them in the container (Linear Layout for example) where you show your first fragment.
The code is available in Android Developer Tutorials, you just have to customize.
http://developer.android.com/training/implementing-navigation/nav-drawer.html
It is advisable that you should use more and more fragments in your application, and there should be only four basic activities local to your application, that you mention in your AndroidManifest.xml apart from the external ones (FacebookActivity for example):
SplashActivity: uses no fragment, and uses FullScreen theme.
LoginSignUpActivity: Do not require NavigationDrawer at all, and no back button as well, so simply use the normal toolbar, but at the least, 3 or 4 fragments will be required. Uses no-action-bar theme
HomeActivity or DashBoard Activity: Uses no-action-bar theme. Here you require Navigation drawer, also all the screens that follow will be fragments or nested fragments, till the leaf view, with the shared drawer. All the settings, user profile and etc. will be here as fragments, in this activity. The fragments here will not be added to the back stack and will be opened from the drawer menu items. In the case of fragments that require back button instead of the drawer, there is a fourth kind of activity below.
Activity without drawer. This activity has a back button on top and the fragments inside will be sharing the same action-bar. These fragments will be added to the back-stack, as there will be a navigation history.
[ For further guidance see: https://stackoverflow.com/a/51100507/787399 ]
Happy Coding !!
I recently had the same issue on OS X Sierra with bash shell, and thanks to answers above I only had to edit the file
~/.bash_profile
and append those lines
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
int
is a primitive type that represent an integer. whereas Integer
is an Object that wraps int
. The Integer
object gives you more functionality, such as converting to hex, string, etc.
You can also use OOP concepts with Integer
. For example, you can use Integer for generics (i.e. Collection
).<Integer>
You can parse the string using Html Agility pack and get the InnerText.
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(@"<b> Hulk Hogan's Celebrity Championship Wrestling <font color=\"#228b22\">[Proj # 206010]</font></b> (Reality Series, )");
string result = htmlDoc.DocumentNode.InnerText;
The main difference is that appendChild
is a DOM method and append
is a jQuery method. The second one uses the first as you can see on jQuery source code
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.appendChild( elem );
}
});
},
If you're using jQuery library on your project, you'll be safe always using append
when adding elements to the page.
Having seen simply too many edge cases, I went for a simpler check:
^(([0-9\ \+\_\-\,\.\^\*\?\$\^\#\(\)])|(ext|x)){1,20}$
The first thing one may point out is allowing repetition of "ext", but the purpose of this regex is to prevent users from accidentally entering email ids etc. instead of phone numbers, which it does.
please note, if you use $filter like this:
$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'});
and you happened to have another grade for, Oh I don't know, CC or AC or C+ or CCC it pulls them in to. you need to append a requirement for an exact match:
$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'}, true);
This really killed me when I was pulling in some commission details like this:
var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}))[0];
only get called in for a bug because it was pulling in the commission ID 56 rather than 6.
Adding the true forces an exact match.
var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}, true))[0];
Yet still, I prefer this (I use typescript, hence the "Let" and =>):
let obj = this.$filter('filter')(this.CommissionTypes, (item) =>{
return item.commission_type_id === 6;
})[0];
I do that because, at some point down the road, I might want to get some more info from that filtered data, etc... having the function right in there kind of leaves the hood open.
I encountered this bug when attempting to define a new OptionSetType
struct in Swift 2. When I corrected the type on the init()
parameter from Self.RawValue
to Int
the crash stopped occurring:
// bad:
// public init(rawValue: Self.RawValue) {
// self.rawValue = rawValue
// }
// good:
public init(rawValue: Int) {
self.rawValue = rawValue
}
No Worries! I have found the solution! I just installed https://msdn.microsoft.com/en-us/windows/desktop/bg162891.aspx and it all worked fine :)
SQL Server drops and recreates the tables only if you:
Using ALTER is safer, as in case the metadata is lost while you re-create the table, your data will be lost.
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
the trick is to delayed the button to be disabled, and submit the form you can use
window.setTimeout('this.disabled=true',0);
yes even with 0 MS is working
I have found a great solution for fixed backgrounds on mobile devices requiring no JavaScript at all.
body:before {
content: "";
display: block;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: -10;
background: url(photos/2452.jpg) no-repeat center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Please be aware of the negative z-index
value of -10
. html
root element default z-index
is 0
. This value must be the smallest z-index
to have it as background.
You can use DataKeys for retrieving the value of such fields, because (as you said) when you set a normal BoundField
as visible false you cannot get their value.
In the .aspx
file set the GridView
property
DataKeyNames = "Outlook_ID"
Now, in an event handler you can access the value of this key like so:
grid.DataKeys[rowIndex]["Outlook_ID"]
This will give you the id at the specified rowindex of the grid.
Source article: Passing a list as an argument to a vararg method
Use the toArray(T[] arr)
method.
.getMap(locations.toArray(new WorldLocation[locations.size()]))
(toArray(new WorldLocation[0])
also works, but you would allocate a zero-length array for no reason.)
Here's a complete example:
public static void method(String... strs) {
for (String s : strs)
System.out.println(s);
}
...
List<String> strs = new ArrayList<String>();
strs.add("hello");
strs.add("world");
method(strs.toArray(new String[strs.size()]));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
The accepted answer is correct, but I prefer:
@{int count = 0;}
@foreach (var item in Model.Resources)
{
@Html.Raw(count <= 3 ? "<div class=\"resource-row\">" : "")
// some code
@Html.Raw(count <= 3 ? "</div>" : "")
@(count++)
}
I hope this inspires someone, even though I'm late to the party.
Also from Java doc:
java.lang
Class Process
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
Fail to clear the buffer of input stream (which pipes to the output stream of subprocess) from Process may lead to a subprocess blocking.
Try this:
Process process = Runtime.getRuntime().exec("tasklist");
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((reader.readLine()) != null) {}
process.waitFor();
To change button Radius, Color and Width I set like this:
self.myBtn.layer.cornerRadius = 10;
self.myBtn.layer.borderWidth = 1;
self.myBtn.layer.borderColor =[UIColor colorWithRed:189.0/255.0f green:189.0/255.0f blue:189.0/255.0f alpha:1.0].CGColor;
There's also COM.
There are technicalities, but I'd say the advantage is that you'll be able to call methods that you can define.
MSDN offers C# COM interop tutorials. Please search because these links do change.
To get started rightaway go here...
This is the solution ,
Add the html
also to 100%
html,body {
height: 100%;
width: 100%;
}
After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC"
) you should loop over the table using the DefaultView not the DataTable instance itself
foreach(DataRowView r in table.DefaultView)
{
//... here you get the rows in sorted order
Console.WriteLine(r["Town"].ToString());
}
Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable
DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
Console.WriteLine(r["Town"].ToString());
}
for me Exception should be thrown when a required technical or business rule fails. for instance if a car entity is associated with array of 4 tires ... if one tire or more are null ... an exception should be Fired "NotEnoughTiresException" , cuz it can be caught at different level of the system and have a significant meaning through logging. besides if we just try to flow control the null and prevent the instanciation of the car . we might never never find the source of the problem , cuz the tire isn't supposed to be null in the first place .
It is possible of course, use -l:
instead of -l
. For example -l:libXYZ.a
to link with libXYZ.a
. Notice the lib
written out, as opposed to -lXYZ
which would auto expand to libXYZ
.
None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me:
Edit file phpMyAdmin.conf
sudo nano /etc/httpd/conf.d/phpMyAdmin.conf
And replace this at the top:
<Directory /usr/share/phpMyAdmin/>
AddDefaultCharset UTF-8
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
#Require ip 127.0.0.1
#Require ip ::1
Require all granted
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
Deny from All
Allow from 127.0.0.1
Allow from ::1
</IfModule>
</Directory>