You need to follow the following steps:
Find line that read follows
Require ip 127.0.0.1
Replace with your workstation IP address:
Require ip 10.1.3.53
Again find the following line:
Allow from 127.0.0.1
Replace as follows:
Allow from 10.1.3.53
Also find deny from all
and comment it in the entire file.
Save and close the file.Restart Apache httpd server
:
# service httpd restart
Edit: Since this is the selected answer and gets best visibility ... please also make sure that PHP is installed, otherwise you get same Forbidden
error.
Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt
). You can check where you are spooling by issuing spool
command.
In IFrames I usually solve this problem by putting a small script to the very end of the block:
<body>
The content of your IFrame
<script type="text/javascript">
//<![CDATA[
fireOnReadyEvent();
parent.IFrameLoaded();
//]]>
</script>
</body>
This work most of the time for me. Sometimes the simplest and most naive solution is the most appropriate.
It's been noted that in Python 3.0+ you can use
super().__init__()
to make your call, which is concise and does not require you to reference the parent OR class names explicitly, which can be handy. I just want to add that for Python 2.7 or under, some people implement a name-insensitive behaviour by writing self.__class__
instead of the class name, i.e.
super(self.__class__, self).__init__() # DON'T DO THIS!
HOWEVER, this breaks calls to super
for any classes that inherit from your class, where self.__class__
could return a child class. For example:
class Polygon(object):
def __init__(self, id):
self.id = id
class Rectangle(Polygon):
def __init__(self, id, width, height):
super(self.__class__, self).__init__(id)
self.shape = (width, height)
class Square(Rectangle):
pass
Here I have a class Square
, which is a sub-class of Rectangle
. Say I don't want to write a separate constructor for Square
because the constructor for Rectangle
is good enough, but for whatever reason I want to implement a Square so I can reimplement some other method.
When I create a Square
using mSquare = Square('a', 10,10)
, Python calls the constructor for Rectangle
because I haven't given Square
its own constructor. However, in the constructor for Rectangle
, the call super(self.__class__,self)
is going to return the superclass of mSquare
, so it calls the constructor for Rectangle
again. This is how the infinite loop happens, as was mentioned by @S_C. In this case, when I run super(...).__init__()
I am calling the constructor for Rectangle
but since I give it no arguments, I will get an error.
You are binding you click on the wrong element, you should bind it to the a
.
You are prevent default event to occur on the li
, but li
have no default behavior, a
does.
Try this:
$(document).ready(function () {
$('.nav li a').click(function(e) {
$('.nav li.active').removeClass('active');
var $parent = $(this).parent();
$parent.addClass('active');
e.preventDefault();
});
});
Instance variable is the variable declared inside a class, but outside a method: something like:
class IronMan {
/** These are all instance variables **/
public String realName;
public String[] superPowers;
public int age;
/** Getters and setters here **/
}
Now this IronMan Class can be instantiated in another class to use these variables. Something like:
class Avengers {
public static void main(String[] a) {
IronMan ironman = new IronMan();
ironman.realName = "Tony Stark";
// or
ironman.setAge(30);
}
}
This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.
Look at the getFragmentManager().popBackStack()
methods (there are several to choose from)
http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()
I had a similar issue: to count all distinct values, counting null values as 1, too. A simple count doesn't work in this case, as it does not take null values into account.
Here's a snippet that works on SQL and does not involve selection of new values. Basically, once performed the distinct, also return the row number in a new column (n) using the row_number() function, then perform a count on that column:
SELECT COUNT(n)
FROM (
SELECT *, row_number() OVER (ORDER BY [MyColumn] ASC) n
FROM (
SELECT DISTINCT [MyColumn]
FROM [MyTable]
) items
) distinctItems
I think its worth referencing this similar answer: https://stackoverflow.com/a/5288804/64313
Here is a another quick solution. There are other variations possible on this using the <available>
tag:
# exit with failure if no files are found
<property name="file" value="${some.path}/some.txt" />
<fail message="FILE NOT FOUND: ${file}">
<condition><not>
<available file="${file}" />
</not></condition>
</fail>
Create an integer random between e.g. 1-11
and multiply it by 5
. Simple math.
import random
for x in range(20):
print random.randint(1,11)*5,
print
produces e.g.
5 40 50 55 5 15 40 45 15 20 25 40 15 50 25 40 20 15 50 10
Well seeing this thread as a beginner got my head spinning. Hence came up with a simple shortcut.
Though str.strip() works to remove leading & trailing spaces it does nothing for spaces between characters.
words=input("Enter the word to test")
# If I have a user enter discontinous threads it becomes a problem
# input = " he llo, ho w are y ou "
n=words.strip()
print(n)
# output "he llo, ho w are y ou" - only leading & trailing spaces are removed
Instead use str.replace() to make more sense plus less error & more to the point. The following code can generalize the use of str.replace()
def whitespace(words):
r=words.replace(' ','') # removes all whitespace
n=r.replace(',','|') # other uses of replace
return n
def run():
words=input("Enter the word to test") # take user input
m=whitespace(words) #encase the def in run() to imporve usability on various functions
o=m.count('f') # for testing
return m,o
print(run())
output- ('hello|howareyou', 0)
Can be helpful while inheriting the same in diff. functions.
session_start();
include('connection.php');
/* function msg($subjectname,$coursename,$sem)
{
return '{"subjectname":'.$subjectname.'"coursename":'.$coursename.'"sem":'.$sem.'}';
}*/
$title_id=$_POST['title_id'];
$result=mysql_query("SELECT * FROM `video` WHERE id='$title_id'") or die(mysql_error());
$qr=mysql_fetch_array($result);
$subject=$qr['subject'];
$course=$qr['course'];
$resultes=mysql_query("SELECT * FROM course JOIN subject ON course.id='$course' AND subject.id='$subject'");
$qqr=mysql_fetch_array($resultes);
$subjectname=$qqr['subjectname'];
$coursename=$qqr['coursename'];
$sem=$qqr['sem'];
$json = array("subjectname" => $subjectname, "coursename" => $coursename, "sem" => $sem,);
header("Content-Type: application/json", true);
echo json_encode( $json_arr );
$.ajax({type:"POST",
dataType: "json",
url:'select-title.php',
data:$('#studey-form').serialize(),
contentType: "application/json; charset=utf-8",
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success:function(response)
{
var response=$.parseJSON(response)
alert(response.subjectname);
$('#course').html("<option>"+response.coursename+"</option>");
$('#subject').html("<option>"+response.subjectname+"</option>");
},
error: function( error,x,y)
{
alert( x,y );
}
});
You can achieve it by using following code,
@Query(value = "SELECT * FROM users u WHERE ORDER BY ?#{#pageable}", nativeQuery = true)
List<User> getUsers(String name, Pageable pageable);
Simply use ORDER BY ?#{#pageable} and pass page request to your method.
Enjoy!
Not being a Python person, but the easiest without any libraries is just:
total = 3800
seconds = total % 60
total = total - seconds
hours = total / 3600
total = total - (hours * 3600)
mins = total / 60
It will group by the column position you put after the group by clause.
for example if you run 'SELECT SALESMAN_NAME, SUM(SALES) FROM SALES GROUP BY 1
'
it will group by SALESMAN_NAME
.
One risk on doing that is if you run 'Select *
' and for some reason you recreate the table with columns on a different order, it will give you a different result than you would expect.
You can execute the following commands
lsof / |grep deleted
kill the process id's, which free up the disk space.
Try this, it work for me
DECLARE @spname sysname;
DECLARE SPCursor CURSOR FOR
SELECT SCHEMA_NAME(schema_id) + '.' + name
FROM sys.objects
WHERE type = 'P';
OPEN SPCursor;
FETCH NEXT FROM SPCursor INTO @spname;
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC('DROP PROCEDURE ' + @spname);
FETCH NEXT FROM SPCursor INTO @spname;
END
CLOSE SPCursor;
DEALLOCATE SPCursor;
The following correctly rounds the quotient to the nearest integer for both positive and negative operands WITHOUT floating point or conditional branches (see assembly output below). Assumes N-bit 2's complement integers.
#define ASR(x) ((x) < 0 ? -1 : 0) // Compiles into a (N-1)-bit arithmetic shift right
#define ROUNDING(x,y) ( (y)/2 - (ASR((x)^(y)) & (y)))
int RoundedQuotient(int x, int y)
{
return (x + ROUNDING(x,y)) / y ;
}
The value of ROUNDING will have the same sign as the dividend (x) and half the magnitude of the divisor (y). Adding ROUNDING to the dividend thus increases its magnitude before the integer division truncates the resulting quotient. Here's the output of the gcc compiler with -O3 optimization for a 32-bit ARM Cortex-M4 processor:
RoundedQuotient: // Input parameters: r0 = x, r1 = y
eor r2, r1, r0 // r2 = x^y
and r2, r1, r2, asr #31 // r2 = ASR(x^y) & y
add r3, r1, r1, lsr #31 // r3 = (y < 0) ? y + 1 : y
rsb r3, r2, r3, asr #1 // r3 = y/2 - (ASR(x^y) & y)
add r0, r0, r3 // r0 = x + (y/2 - (ASR(x^y) & y)
sdiv r0, r0, r1 // r0 = (x + ROUNDING(x,y)) / y
bx lr // Returns r0 = rounded quotient
I encountered a similar error. It was a noob mistake done in a hurry. Integer array without declaring size int a[] then trying to access it. C++ compiler should've caught such an error easily if it were in main. However since this particular int array was declared inside an object, it was being created at the same time as my object (many objects were being created) and the compiler was throwing a free(): invalid next size(normal) error. I thought of 2 explanations for this (please enlighten me if anyone knows more): 1.) This resulted in some random memory being assigned to it but since this wasn't accessible it was freeing up all the other heap memory just trying to find this int. 2.) The memory required by it was practically infinite for a program and to assign this it was freeing up all other memory.
A simple:
int* a;
class foo{
foo(){
for(i=0;i<n;i++)
a=new int[i];
}
Solved the problem. But it did take a lot of time trying to debug this because the compiler could not "really" find the error.
One option is to directly input the character you're interested in using hex or octal notation:
printf "\x41\n"
printf "\101\n"
Asked question title is general, but authors use case stated in the body of the question is specific. So any other answers may be used.
But in order to fully answer the title question it should be clarified that it seems like all of the approaches may fail in some cases and require some rework. I reviewed all of them (and some additional) in decreasing of reliability order (in my opinion):
==
(accepted answer).Despite the fact that this is accepted answer and has most upvotes count, I think this method should not be used at all. Because in fact this approach is discouraged in python as mentioned several times here.
But if one still want to use it - should be aware of some pandas-specific dtypes like pd.CategoricalDType
, pd.PeriodDtype
, or pd.IntervalDtype
. Here one have to use extra type( )
in order to recognize dtype correctly:
s = pd.Series([pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')])
s
s.dtype == pd.PeriodDtype # Not working
type(s.dtype) == pd.PeriodDtype # working
>>> 0 2002-03-01
>>> 1 2012-02-01
>>> dtype: period[D]
>>> False
>>> True
Another caveat here is that type should be pointed out precisely:
s = pd.Series([1,2])
s
s.dtype == np.int64 # Working
s.dtype == np.int32 # Not working
>>> 0 1
>>> 1 2
>>> dtype: int64
>>> True
>>> False
isinstance()
approach.This method has not been mentioned in answers so far.
So if direct comparing of types is not a good idea - lets try built-in python function for this purpose, namely - isinstance()
.
It fails just in the beginning, because assumes that we have some objects, but pd.Series
or pd.DataFrame
may be used as just empty containers with predefined dtype
but no objects in it:
s = pd.Series([], dtype=bool)
s
>>> Series([], dtype: bool)
But if one somehow overcome this issue, and wants to access each object, for example, in the first row and checks its dtype like something like that:
df = pd.DataFrame({'int': [12, 2], 'dt': [pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')]},
index = ['A', 'B'])
for col in df.columns:
df[col].dtype, 'is_int64 = %s' % isinstance(df.loc['A', col], np.int64)
>>> (dtype('int64'), 'is_int64 = True')
>>> (dtype('<M8[ns]'), 'is_int64 = False')
It will be misleading in the case of mixed type of data in single column:
df2 = pd.DataFrame({'data': [12, pd.Timestamp('2013-01-02')]},
index = ['A', 'B'])
for col in df2.columns:
df2[col].dtype, 'is_int64 = %s' % isinstance(df2.loc['A', col], np.int64)
>>> (dtype('O'), 'is_int64 = False')
And last but not least - this method cannot directly recognize Category
dtype. As stated in docs:
Returning a single item from categorical data will also return the value, not a categorical of length “1”.
df['int'] = df['int'].astype('category')
for col in df.columns:
df[col].dtype, 'is_int64 = %s' % isinstance(df.loc['A', col], np.int64)
>>> (CategoricalDtype(categories=[2, 12], ordered=False), 'is_int64 = True')
>>> (dtype('<M8[ns]'), 'is_int64 = False')
So this method is also almost inapplicable.
df.dtype.kind
approach.This method yet may work with empty pd.Series
or pd.DataFrames
but has another problems.
First - it is unable to differ some dtypes:
df = pd.DataFrame({'prd' :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
'str' :['s1', 's2'],
'cat' :[1, -1]})
df['cat'] = df['cat'].astype('category')
for col in df:
# kind will define all columns as 'Object'
print (df[col].dtype, df[col].dtype.kind)
>>> period[D] O
>>> object O
>>> category O
Second, what is actually still unclear for me, it even returns on some dtypes None.
df.select_dtypes
approach.This is almost what we want. This method designed inside pandas so it handles most corner cases mentioned earlier - empty DataFrames, differs numpy or pandas-specific dtypes well. It works well with single dtype like .select_dtypes('bool')
. It may be used even for selecting groups of columns based on dtype:
test = pd.DataFrame({'bool' :[False, True], 'int64':[-1,2], 'int32':[-1,2],'float': [-2.5, 3.4],
'compl':np.array([1-1j, 5]),
'dt' :[pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')],
'td' :[pd.Timestamp('2012-03-02')- pd.Timestamp('2016-10-20'),
pd.Timestamp('2010-07-12')- pd.Timestamp('2000-11-10')],
'prd' :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
'intrv':pd.arrays.IntervalArray([pd.Interval(0, 0.1), pd.Interval(1, 5)]),
'str' :['s1', 's2'],
'cat' :[1, -1],
'obj' :[[1,2,3], [5435,35,-52,14]]
})
test['int32'] = test['int32'].astype(np.int32)
test['cat'] = test['cat'].astype('category')
Like so, as stated in the docs:
test.select_dtypes('number')
>>> int64 int32 float compl td
>>> 0 -1 -1 -2.5 (1-1j) -1693 days
>>> 1 2 2 3.4 (5+0j) 3531 days
On may think that here we see first unexpected (at used to be for me: question) results - TimeDelta
is included into output DataFrame
. But as answered in contrary it should be so, but one have to be aware of it. Note that bool
dtype is skipped, that may be also undesired for someone, but it's due to bool
and number
are in different "subtrees" of numpy dtypes. In case with bool, we may use test.select_dtypes(['bool'])
here.
Next restriction of this method is that for current version of pandas (0.24.2), this code: test.select_dtypes('period')
will raise NotImplementedError
.
And another thing is that it's unable to differ strings from other objects:
test.select_dtypes('object')
>>> str obj
>>> 0 s1 [1, 2, 3]
>>> 1 s2 [5435, 35, -52, 14]
But this is, first - already mentioned in the docs. And second - is not the problem of this method, rather the way strings are stored in DataFrame
. But anyway this case have to have some post processing.
df.api.types.is_XXX_dtype
approach.This one is intended to be most robust and native way to achieve dtype recognition (path of the module where functions resides says by itself) as i suppose. And it works almost perfectly, but still have at least one caveat and still have to somehow distinguish string columns.
Besides, this may be subjective, but this approach also has more 'human-understandable' number
dtypes group processing comparing with .select_dtypes('number')
:
for col in test.columns:
if pd.api.types.is_numeric_dtype(test[col]):
print (test[col].dtype)
>>> bool
>>> int64
>>> int32
>>> float64
>>> complex128
No timedelta
and bool
is included. Perfect.
My pipeline exploits exactly this functionality at this moment of time, plus a bit of post hand processing.
Hope I was able to argument the main point - that all discussed approaches may be used, but only pd.DataFrame.select_dtypes()
and pd.api.types.is_XXX_dtype
should be really considered as the applicable ones.
In a terminal emulator like konsole or gnome-terminal, you should to set a 256 color setting for vim.
:set t_Co=256
After that you can to change your background.
Execute only 1 of the below
Once a command works, skip the rest/ below to it:
Normal:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe myTest.dll
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe myTest.dll /tlb:myTest.tlb
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe myTest.dll /tlb:myTest.tlb /codebase
Only if you face issues, use old version 'v2.0.50727':
%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe myTest.dll
%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe myTest.dll /tlb:myTest.tlb
%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe myTest.dll /tlb:myTest.tlb
Only if you built myTest.dll for 64bit Only, use 'Framework64' path:
%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe myTest.dll
%SystemRoot%\Microsoft.NET\Framework64\v2.0.50727\RegAsm.exe myTest.dll
Note: 64-bit built dlls will not work on 32-bit platform.
All options:
See https://docs.microsoft.com/en-us/dotnet/framework/tools/regasm-exe-assembly-registration-tool
WITH CHECK
is indeed the default behaviour however it is good practice to include within your coding.
The alternative behaviour is of course to use WITH NOCHECK
, so it is good to explicitly define your intentions. This is often used when you are playing with/modifying/switching inline partitions.
eval
is not an acceptable practice if your directory names can be generated by untrusted sources. See BashFAQ #48 for more on why eval
should not be used, and BashFAQ #50 for more on the root cause of this problem and its proper solutions, some of which are touched on below:
If you need to build up your commands over time, use arrays:
tar_cmd=( tar cv "$directory" )
split_cmd=( split -b 1024m - "$backup_file" )
encrypt_cmd=( openssl des3 -salt )
"${tar_cmd[@]}" | "${encrypt_cmd[@]}" | "${split_cmd[@]}"
Alternately, if this is just about defining your commands in one central place, use functions:
tar_cmd() { tar cv "$directory"; }
split_cmd() { split -b 1024m - "$backup_file"; }
encrypt_cmd() { openssl des3 -salt; }
tar_cmd | split_cmd | encrypt_cmd
Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:
array.length * array[0].length
The &
makes the command run in the background.
From man bash
:
If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.
You will have to set your custom WebviewClient overriding shouldOverrideUrlLoading method for your webview before loading the url.
mWebView.setWebViewClient(new WebViewClient()
{
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
return shouldOverrideUrlLoading(url);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request)
{
Uri uri = request.getUrl();
return shouldOverrideUrlLoading(uri.toString());
}
private boolean shouldOverrideUrlLoading(final String url)
{
Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url);
// Here put your code
return true; // Returning True means that application wants to leave the current WebView and handle the url itself, otherwise return false.
}
});
Checkout the example code for handling redirect urls and open PDF without download, in webview. https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500
CREATE TABLE UserGroup
(
[User_Id] INT NOT NULL,
[Group_Id] INT NOT NULL
CONSTRAINT PK_UserGroup PRIMARY KEY NONCLUSTERED ([User_Id], [Group_Id])
)
Adding to @Lombo 's answer
When will you need to override equals() ?
The default implementation of Object's equals() is
public boolean equals(Object obj) {
return (this == obj);
}
which means two objects will be considered equal only if they have the same memory address which will be true only if you are comparing an object with itself.
But you might want to consider two objects the same if they have the same value for one or more of their properties (Refer the example given in @Lombo 's answer).
So you will override equals()
in these situations and you would give your own conditions for equality.
I have successfully implemented equals() and it is working great.So why are they asking to override hashCode() as well?
Well.As long as you don't use "Hash" based Collections on your user-defined class,it is fine.
But some time in the future you might want to use HashMap
or HashSet
and if you don't override
and "correctly implement" hashCode(), these Hash based collection won't work as intended.
Override only equals (Addition to @Lombo 's answer)
myMap.put(first,someValue)
myMap.contains(second); --> But it should be the same since the key are the same.But returns false!!! How?
First of all,HashMap checks if the hashCode of second
is the same as first
.
Only if the values are the same,it will proceed to check the equality in the same bucket.
But here the hashCode is different for these 2 objects (because they have different memory address-from default implementation). Hence it will not even care to check for equality.
If you have a breakpoint inside your overridden equals() method,it wouldn't step in if they have different hashCodes.
contains()
checks hashCode()
and only if they are the same it would call your equals()
method.
Why can't we make the HashMap check for equality in all the buckets? So there is no necessity for me to override hashCode() !!
Then you are missing the point of Hash based Collections. Consider the following :
Your hashCode() implementation : intObject%9.
The following are the keys stored in the form of buckets.
Bucket 1 : 1,10,19,... (in thousands)
Bucket 2 : 2,20,29...
Bucket 3 : 3,21,30,...
...
Say,you want to know if the map contains the key 10. Would you want to search all the buckets? or Would you want to search only one bucket?
Based on the hashCode,you would identify that if 10 is present,it must be present in Bucket 1. So only Bucket 1 will be searched !!
No JavaScript needed if you use a button instead:
<form action="your_url" method="post">
<button type="submit" name="your_name" value="your_value" class="btn-link">Go</button>
</form>
You can style a button to look like a link, for example:
.btn-link {
border: none;
outline: none;
background: none;
cursor: pointer;
color: #0000EE;
padding: 0;
text-decoration: underline;
font-family: inherit;
font-size: inherit;
}
You are missing the @Id
entity property, and that's why Hibernate is throwing that exception.
Any JPA entity must have an identifier property, that is marked with the Id
annotation.
There are two types of identifiers:
An assigned identifier looks as follows:
@Id
private Long id;
Notice that we are using a wrapper (e.g.,
Long
,Integer
) instead of a primitive type (e.g.,long
,int
). Using a wrapper type is a better choice when using Hibernate because, by checking if theid
isnull
or not, Hibernate can better determine if an entity is transient (it does not have an associated table row) or detached (it has an associated table row, but it's not managed by the current Persistence Context).
The assigned identifier must be set manually by the application prior to calling persist:
Post post = new Post();
post.setId(1L);
entityManager.persist(post);
An auto-generated identifier requires the @GeneratedValue
annotation besides the @Id
:
@Id
@GeneratedValue
private int id;
There are 3 strategies Hibernate can use to auto-generate the entity identifier:
IDENTITY
SEQUENCE
TABLE
The IDENTITY
strategy is to be avoided if the underlying database supports sequences (e.g., Oracle, PostgreSQL, MariaDB since 10.3, SQL Server since 2012). The only major database that does not support sequences is MySQL.
The problem with
IDENTITY
is that automatic Hibernate batch inserts are disabled for this strategy.
The SEQUENCE
strategy is the best choice unless you are using MySQL. For the SEQUENCE
strategy, you also want to use the pooled
optimizer to reduce the number of database roundtrips when persisting multiple entities in the same Persistence Context.
The TABLE
generator is a terrible choice because it does not scale. For portability, you are better off using SEQUENCE
by default and switch to IDENTITY
for MySQL only.
All the slowest (>100x) usages of Python on the shootout are scientific operations that require high GFlop/s count. You should NOT use python for those anyways. The correct way to use python is to import a module that does those calculations, and then go have a relaxing afternoon with your family. That is the pythonic way :)
var divs = $("div[class*='alert-box']");
https://jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#sh-shell-script
if you include a returnStatus: true property, then the shell return is ignored.
use the {10,} operator:
$: cat > testre
============================
==
==============
$: grep -E '={10,}' testre
============================
==============
I'm not sure if this is quite what you're looking for but I've had a lot of success using an HTML to Postscript converter html2ps to create postscript copies of web pages, which I then convert to .gif or .pngs
This doesn't produce exact screenshot quality that you'd get from a web browser and doesn't handle complicated things like flash or css all that well, but the advantage is that you can run it on the web server.
(I use it to create thumbnails of user created content, for navigation)
There is no built-in PHP now()
function, but you can do it using date()
.
Example
function now() {
return date('Y-m-d H:i:s');
}
You can use date_default_timezone_set()
if you need to change timezone.
Otherwise you can make use of Carbon - A simple PHP API extension for DateTime.
I know it is a very old question, but better update it with new information.
You can install service by using sc command:
InstallService.bat:
@echo OFF
echo Stopping old service version...
net stop "[YOUR SERVICE NAME]"
echo Uninstalling old service version...
sc delete "[YOUR SERVICE NAME]"
echo Installing service...
rem DO NOT remove the space after "binpath="!
sc create "[YOUR SERVICE NAME]" binpath= "[PATH_TO_YOUR_SERVICE_EXE]" start= auto
echo Starting server complete
pause
With SC, you can do a lot more things as well: uninstalling the old service (if you already installed it before), checking if service with same name exists... even set your service to autostart.
One of many references: creating a service with sc.exe; how to pass in context parameters
I have done by both this way & InstallUtil
. Personally I feel that using SC is cleaner and better for your health.
Steps to manually configure DNS:
You can access Network and Sharing center by right clicking on the Network icon on the taskbar.
Now choose adapter settings from the side menu.
This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.
In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.
Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.
Select ‘use the following DNS address’ option. Now fill the following fields as given here.
Preferred DNS server: 208.67.222.222
Alternate DNS server : 208.67.220.220
This is an available Open DNS address. You may also use google DNS server addresses.
After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.
You have to add this DNS server address in the router configuration also (by referring the router manual for more information).
Refer : for above method & alternative
If none of this works, then open command prompt(Run as Administrator) and run these:
ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit
Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).
Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue
I just used :before with the input and passed $ as the content
input{
margin-left: 20px;
}
input:before {
content: "$";
position: absolute;
}
Take a substr of the CLOB and then convert it to a char:
UPDATE IMS_TEST
SET TEST_Category = 'just testing'
WHERE to_char(substr(TEST_SCRIPT, 1, 9)) = 'something'
AND ID = '10000239';
Here you go, Python documentation on old string formatting. tutorial -> 7.1.1. Old String Formatting -> "More information can be found in the [link] section".
Note that you should start using the new string formatting when possible.
Locations are evaluated in this order:
location = /path/file.ext {}
Exact matchlocation ^~ /path/ {}
Priority prefix match -> longest firstlocation ~ /Paths?/ {}
(case-sensitive regexp) and location ~* /paths?/ {}
(case-insensitive regexp) -> first matchlocation /path/ {}
Prefix match -> longest firstThe priority prefix match (number 2) is exactly as the common prefix match (number 4), but has priority over any regexp.
For both prefix matche types the longest match wins.
Case-sensitive and case-insensitive have the same priority. Evaluation stops at the first matching rule.
Documentation says that all prefix rules are evaluated before any regexp, but if one regexp matches then no standard prefix rule is used. That's a little bit confusing and does not change anything for the priority order reported above.
With quotes around the date:
mysql> CALL insertEvent('2012.01.01 12:12:12');
all(getattr(someTime,x)==getattr(today(),x) for x in ['year','month','day'])
One should compare using .date()
, but I leave this method as an example in case one wanted to, for example, compare things by month or by minute, etc.
I have a test application set up using JPA/Hibernate & Spring, and my configuration mirrors yours with the exception that I create a datasource and inject it into the EntityManagerFactory, and moved the datasource specific properties out of the persistenceUnit and into the datasource. With these two small changes, my EM gets injected properly.
Yes: Source
switch(shape)
{
case Circle c:
WriteLine($"circle with radius {c.Radius}");
break;
case Rectangle s when (s.Length == s.Height):
WriteLine($"{s.Length} x {s.Height} square");
break;
case Rectangle r:
WriteLine($"{r.Length} x {r.Height} rectangle");
break;
default:
WriteLine("<unknown shape>");
break;
case null:
throw new ArgumentNullException(nameof(shape));
}
No.
http://blogs.msdn.com/b/peterhal/archive/2005/07/05/435760.aspx
We get a lot of requests for addditions to the C# language and today I'm going to talk about one of the more common ones - switch on type. Switch on type looks like a pretty useful and straightforward feature: Add a switch-like construct which switches on the type of the expression, rather than the value. This might look something like this:
switch typeof(e) {
case int: ... break;
case string: ... break;
case double: ... break;
default: ... break;
}
This kind of statement would be extremely useful for adding virtual method like dispatch over a disjoint type hierarchy, or over a type hierarchy containing types that you don't own. Seeing an example like this, you could easily conclude that the feature would be straightforward and useful. It might even get you thinking "Why don't those #*&%$ lazy C# language designers just make my life easier and add this simple, timesaving language feature?"
Unfortunately, like many 'simple' language features, type switch is not as simple as it first appears. The troubles start when you look at a more significant, and no less important, example like this:
class C {}
interface I {}
class D : C, I {}
switch typeof(e) {
case C: … break;
case I: … break;
default: … break;
}
Link: https://blogs.msdn.microsoft.com/peterhal/2005/07/05/many-questions-switch-on-type/
You can find the difference by converting the date in seconds and take time interval since 1970 for this and then you can find the difference between two dates.
When you run
install.packages("whatever")
you got message that your binaries are downloaded into temporary location (e.g. The downloaded binary packages are in C:\Users\User_name\AppData\Local\Temp\RtmpC6Y8Yv\downloaded_packages ). Go there. Take binaries (zip file). Copy paste into location which you get from running the code:
.libPaths()
If libPaths shows 2 locations, then paste into second one. Load library:
library(whatever)
Fixed.
Use this cmd to display the packages in your device (for windows users)
adb shell pm list packages
then you can delete completely the package with the following cmd
adb uninstall com.example.myapp
Although the solutions presented before are valid and work, I humbly offer a code that's cleaner, more elegant, and with better performance, at least as I see it.
Firstly, one may ask: Why would anyone ever need a code snippet to globally and blindly look for a string? Hey, they already invented fulltext, don't you know?
My answer: my mainly work is at systems integration projects, and discovering where the data is written is important whenever I'm learning a new and undocummented database, which seldom happens.
Also, the code I present is a stripped down version of a more powerful and dangerous script that searches and REPLACES text throughout the database.
CREATE TABLE #result(
id INT IDENTITY, -- just for register seek order
tblName VARCHAR(255),
colName VARCHAR(255),
qtRows INT
)
go
DECLARE @toLookFor VARCHAR(255)
SET @toLookFor = '[input your search criteria here]'
DECLARE cCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT
'[' + usr.name + '].[' + tbl.name + ']' AS tblName,
'[' + col.name + ']' AS colName,
LOWER(typ.name) AS typName
FROM
sysobjects tbl
INNER JOIN(
syscolumns col
INNER JOIN systypes typ
ON typ.xtype = col.xtype
)
ON col.id = tbl.id
--
LEFT OUTER JOIN sysusers usr
ON usr.uid = tbl.uid
WHERE tbl.xtype = 'U'
AND LOWER(typ.name) IN(
'char', 'nchar',
'varchar', 'nvarchar',
'text', 'ntext'
)
ORDER BY tbl.name, col.colorder
--
DECLARE @tblName VARCHAR(255)
DECLARE @colName VARCHAR(255)
DECLARE @typName VARCHAR(255)
--
DECLARE @sql NVARCHAR(4000)
DECLARE @crlf CHAR(2)
SET @crlf = CHAR(13) + CHAR(10)
OPEN cCursor
FETCH cCursor
INTO @tblName, @colName, @typName
WHILE @@fetch_status = 0
BEGIN
IF @typName IN('text', 'ntext')
BEGIN
SET @sql = ''
SET @sql = @sql + 'INSERT INTO #result(tblName, colName, qtRows)' + @crlf
SET @sql = @sql + 'SELECT @tblName, @colName, COUNT(*)' + @crlf
SET @sql = @sql + 'FROM ' + @tblName + @crlf
SET @sql = @sql + 'WHERE PATINDEX(''%'' + @toLookFor + ''%'', ' + @colName + ') > 0' + @crlf
END
ELSE
BEGIN
SET @sql = ''
SET @sql = @sql + 'INSERT INTO #result(tblName, colName, qtRows)' + @crlf
SET @sql = @sql + 'SELECT @tblName, @colName, COUNT(*)' + @crlf
SET @sql = @sql + 'FROM ' + @tblName + @crlf
SET @sql = @sql + 'WHERE ' + @colName + ' LIKE ''%'' + @toLookFor + ''%''' + @crlf
END
EXECUTE sp_executesql
@sql,
N'@tblName varchar(255), @colName varchar(255), @toLookFor varchar(255)',
@tblName, @colName, @toLookFor
FETCH cCursor
INTO @tblName, @colName, @typName
END
SELECT *
FROM #result
WHERE qtRows > 0
ORDER BY id
GO
DROP TABLE #result
go
The following links will be helpful-
For CLI C++ (compiled with /clr) see this MSDN link.
In short, a property can be given the name "default":
ref class Class
{
public:
property System::String^ default[int i]
{
System::String^ get(int i) { return "hello world"; }
}
};
Here is working example:
in head
<script type="text/javascript" src="jspdf.debug.js"></script>
script:
<script type="text/javascript">
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = $('#customers')[0];
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme': function(element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, {// y coord
'width': margins.width, // max width of content on PDF
'elementHandlers': specialElementHandlers
},
function(dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save('Test.pdf');
}
, margins);
}
</script>
and table:
<div id="customers">
<table id="tab_customers" class="table table-striped" >
<colgroup>
<col width="20%">
<col width="20%">
<col width="20%">
<col width="20%">
</colgroup>
<thead>
<tr class='warning'>
<th>Country</th>
<th>Population</th>
<th>Date</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Chinna</td>
<td>1,363,480,000</td>
<td>March 24, 2014</td>
<td>19.1</td>
</tr>
<tr>
<td>India</td>
<td>1,241,900,000</td>
<td>March 24, 2014</td>
<td>17.4</td>
</tr>
<tr>
<td>United States</td>
<td>317,746,000</td>
<td>March 24, 2014</td>
<td>4.44</td>
</tr>
<tr>
<td>Indonesia</td>
<td>249,866,000</td>
<td>July 1, 2013</td>
<td>3.49</td>
</tr>
<tr>
<td>Brazil</td>
<td>201,032,714</td>
<td>July 1, 2013</td>
<td>2.81</td>
</tr>
</tbody>
</table>
</div>
and button to run:
<button onclick="javascript:demoFromHTML()">PDF</button>
and working example online:
or try this: HTML Table Export
If you know the the name of the file and if you always want to download that specific file, then you can easily get the ID and other attributes for your desired file from: https://developers.google.com/drive/v2/reference/files/list (towards the bottom you will find a way to run queries). In the q field enter title = 'your_file_name' and run it. You should see some result show up right below and within it should be an "id" field. That is the id you are looking for.
You can also play around with additional parameters from: https://developers.google.com/drive/search-parameters
chown -Rv www-data:www-data
chmod -Rv 0755 wp-includes
chmod -Rv 0755 wp-admin/js
chmod -Rv 0755 wp-content/themes
chmod -Rv 0755 wp-content/plugins
chmod -Rv 0755 wp-admin
chmod -Rv 0755 wp-content
chmod -v 0644 wp-config.php
chmod -v 0644 wp-admin/index.php
chmod -v 0644 .htaccess
I agree that this isn't completely supported, but here's what I did. You can use a custom view for your action bar (it will display between your icon and your action items). I'm using a custom view and I have the native title disabled. All of my activities inherit from a single activity, which has this code in onCreate:
this.getActionBar().setDisplayShowCustomEnabled(true);
this.getActionBar().setDisplayShowTitleEnabled(false);
LayoutInflater inflator = LayoutInflater.from(this);
View v = inflator.inflate(R.layout.titleview, null);
//if you need to customize anything else about the text, do it here.
//I'm using a custom TextView with a custom font in my layout xml so all I need to do is set title
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());
//assign the view to the actionbar
this.getActionBar().setCustomView(v);
And my layout xml (R.layout.titleview in the code above) looks like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent" >
<com.your.package.CustomTextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:textSize="20dp"
android:maxLines="1"
android:ellipsize="end"
android:text="" />
</RelativeLayout>
Integer.valueOf()
returns an Integer object, while Integer.parseInt()
returns an int
primitive.
My preference is to utilize the inline
attribute. This will cause the icon to correctly scale with the size of the button.
<button mat-button>
<mat-icon inline=true>local_movies</mat-icon>
Movies
</button>
<!-- Link button -->
<a mat-flat-button color="accent" routerLink="/create"><mat-icon inline=true>add</mat-icon> Create</a>
I add this to my styles.css
to:
button.mat-button .mat-icon,
a.mat-button .mat-icon,
a.mat-raised-button .mat-icon,
a.mat-flat-button .mat-icon,
a.mat-stroked-button .mat-icon {
vertical-align: top;
font-size: 1.25em;
}
Handles either type of line break
str.replace(new RegExp('\r?\n','g'), '<br />');
If your test and webapp are in the same Maven project, you can use a property in the project POM. Then you can filter certain files which will allow Maven to set the property in those files. There are different ways to filter, but the most common is during the resources phase - http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-description.html
If the test and webapp are in different Maven projects, you can put the property in settings.xml, which is in your maven repository folder (C:\Documents and Settings\username.m2) on Windows. You will still need to use filtering or some other method to read the property into your test and webapp.
Windows and Linux:
Ctrl + Shift + I keys to open Developer Tools
Ctrl + Shift + J to open Developer Tools and bring focus to the Console.
Ctrl + Shift + C to toggle Inspect Element mode.
Mac:
? + ? + I keys to open Developer Tools
? + ? + J to open Developer Tools and bring focus to the Console.
? + ? + C to toggle Inspect Element mode.
Your purpose can be solved using following query -
Select Value , Substring(FullName, 1,Charindex(',', FullName)-1) as Name,
Substring(FullName, Charindex(',', FullName)+1, LEN(FullName)) as Surname
from Table1
There is no readymade Split function in sql server, so we need to create user defined function.
CREATE FUNCTION Split (
@InputString VARCHAR(8000),
@Delimiter VARCHAR(50)
)
RETURNS @Items TABLE (
Item VARCHAR(8000)
)
AS
BEGIN
IF @Delimiter = ' '
BEGIN
SET @Delimiter = ','
SET @InputString = REPLACE(@InputString, ' ', @Delimiter)
END
IF (@Delimiter IS NULL OR @Delimiter = '')
SET @Delimiter = ','
--INSERT INTO @Items VALUES (@Delimiter) -- Diagnostic
--INSERT INTO @Items VALUES (@InputString) -- Diagnostic
DECLARE @Item VARCHAR(8000)
DECLARE @ItemList VARCHAR(8000)
DECLARE @DelimIndex INT
SET @ItemList = @InputString
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
WHILE (@DelimIndex != 0)
BEGIN
SET @Item = SUBSTRING(@ItemList, 0, @DelimIndex)
INSERT INTO @Items VALUES (@Item)
-- Set @ItemList = @ItemList minus one less item
SET @ItemList = SUBSTRING(@ItemList, @DelimIndex+1, LEN(@ItemList)-@DelimIndex)
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
END -- End WHILE
IF @Item IS NOT NULL -- At least one delimiter was encountered in @InputString
BEGIN
SET @Item = @ItemList
INSERT INTO @Items VALUES (@Item)
END
-- No delimiters were encountered in @InputString, so just return @InputString
ELSE INSERT INTO @Items VALUES (@InputString)
RETURN
END -- End Function
GO
---- Set Permissions
--GRANT SELECT ON Split TO UserRole1
--GRANT SELECT ON Split TO UserRole2
--GO
Add .toUpperCase()
after referrer
. This method turns the string into an upper case string. Then, use .indexOf()
using RAL
instead of Ral
.
if (referrer.toUpperCase().indexOf("RAL") === -1) {
The same can also be achieved using a Regular Expression (especially useful when you want to test against dynamic patterns):
if (!/Ral/i.test(referrer)) {
// ^i = Ignore case flag for RegExp
Anywhere between your <body>
and </body>
tags, put in a button using the below code:
<button>
<a href="file.doc" download>Click to Download!</a>
</button>
This is sure to work!
Another way is to use the -t
switch to ssh
:
ssh -t user@server "sudo script"
See man ssh
:
-t Force pseudo-tty allocation. This can be used to execute arbi-
trary screen-based programs on a remote machine, which can be
very useful, e.g., when implementing menu services. Multiple -t
options force tty allocation, even if ssh has no local tty.
Zero is false, nonzero is true.
In php you can test more explicitly using the ===
operator.
if (0==false)
echo "works"; // will echo works
if (0===false)
echo "works"; // will not echo anything
You may wonder, why the syntax is valid (but not working as expected):
var func = p => { foo: "bar" }
It's because of JavaScript's label syntax:
So if you transpile the above code to ES5, it should look like:
var func = function (p) {
foo:
"bar"; //obviously no return here!
}
Below is the server side code that would call the handler and recieve the stream data and loads into xml doc
Stream stream = null;
**Create a web request with the specified URL**
WebRequest myWebRequest = WebRequest.Create(@"http://localhost/XMLProvider/XMLProcessorHandler.ashx");
**Senda a web request and wait for response.**
WebResponse webResponse = myWebRequest.GetResponse();
**Get the stream object from response object**
stream = webResponse.GetResponseStream();
XmlDocument xmlDoc = new XmlDocument();
**Load stream data into xml**
xmlDoc.Load(stream);
If using Python 3: In your print statement, finish with sep="". That will separate out all of the spaces.
EXAMPLE:
txt="potatoes"
print("I love ",txt,"",sep="")
This will print: I love potatoes.
Instead of: I love potatoes .
In your case, since you would be trying to get ride of the \t, do sep="\t"
In Windows CMD which
calls where
:
$ where php
C:\Program Files\PHP\php.exe
The Loic Sharma SQL profiler does support Laravel 4, I just installed it. The instructions are listed here. The steps are the following:
"loic-sharma/profiler": "1.1.*"
in the require section
in composer.jsonphp composer.phar self-update
in the console.php composer.phar update loic-sharma/profiler
in the console as well
`'Profiler\ProfilerServiceProvider',
in the provider array in
app.php'Profiler' => 'Profiler\Facades\Profiler',
in the
aliasses array in app.php as well php artisan config:publish loic-sharma/profiler
in the consoleOr use regex assertions: grep -oP '(?<=potato: ).*' file.txt
Per the PHP documentation, put this at the top of your php scripts:
<?php error_reporting(0); ?>
http://php.net/manual/en/function.error-reporting.php
If you do hide your errors, which you should in a live environment, make sure that you are logging any errors somewhere. How to log errors and warnings into a file? Otherwise, things will go wrong and you will have no idea why.
The better answers to this only work for specific lengths of lists that are provided.
Here's a version that works for any lengths of input. It also makes the algorithm clear in terms of the mathematical concepts of combination and permutation.
from itertools import combinations, permutations
list1 = ['1', '2']
list2 = ['A', 'B', 'C']
num_elements = min(len(list1), len(list2))
list1_combs = list(combinations(list1, num_elements))
list2_perms = list(permutations(list2, num_elements))
result = [
tuple(zip(perm, comb))
for comb in list1_combs
for perm in list2_perms
]
for idx, ((l11, l12), (l21, l22)) in enumerate(result):
print(f'{idx}: {l11}{l12} {l21}{l22}')
This outputs:
0: A1 B2
1: A1 C2
2: B1 A2
3: B1 C2
4: C1 A2
5: C1 B2
This doesn't exactly answer the question as posed, but it does create the same visual effect that you are trying to achieve.
<style>
body {
border:0;
padding:0;
margin:0;
padding-top:60px;
}
#header {
position:absolute;
top:0;
height:60px;
width:100%;
}
#wrapper {
height:100%;
width:100%;
}
</style>
"Any CPU" means that when the program is started, the .NET Framework will figure out, based on the OS bitness, whether to run your program in 32 bits or 64 bits.
There is a difference between x86 and Any CPU: on a x64 system, your executable compiled for X86 will run as a 32-bit executable.
As far as your suspicions go, just go to the Visual Studio 2008 command line and run the following.
dumpbin YourProgram.exe /headers
It will tell you the bitness of your program, plus a whole lot more.
You can use the search function available in the location object. The search function gives the parameter part of the URL. Details can be found in Location Object.
You will have to parse the resulting string for getting the variables and their values, e.g. splitting them on '='.
By Default angular return responseType as Json, but we can configure below types according to your requirement.
responseType: 'arraybuffer'|'blob'|'json'|'text'
Ex:
this.http.post(
'http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId, quantity },
{ headers, responseType: 'text'});
I don't think you can, apart from response.setContentType(..)
<div>
tags are always abused to create a web layout. Its symbolic purpose is to divide a section/portion in the page so that separate style can be added or applied to it. [w3schools Doc] [W3C]
some
and another
has.HTML5, has more logical meaning tags, instead of having plain layout tags. The section
, header
, nav
, aside
everything have their own semantic meaning to it. And are used against <div>
Also with option -T
from manual
Disable pseudo-tty allocation
In Windows Forms and WPF:
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;
Using Spring Framework , you can add many attachments :
package com.mkyong.common;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailMail
{
private JavaMailSender mailSender;
private SimpleMailMessage simpleMailMessage;
public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
this.simpleMailMessage = simpleMailMessage;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(String dear, String content) {
MimeMessage message = mailSender.createMimeMessage();
try{
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(simpleMailMessage.getFrom());
helper.setTo(simpleMailMessage.getTo());
helper.setSubject(simpleMailMessage.getSubject());
helper.setText(String.format(
simpleMailMessage.getText(), dear, content));
FileSystemResource file = new FileSystemResource("/home/abdennour/Documents/cv.pdf");
helper.addAttachment(file.getFilename(), file);
}catch (MessagingException e) {
throw new MailParseException(e);
}
mailSender.send(message);
}
}
To know how to configure your project to deal with this code , complete reading this tutorial .
It's very important to point out that view.layoutIfNeeded()
applies to the view subviews only.
Therefore to animate the view constraint, it is important to call it on the view-to-animate superview as follows:
topConstraint.constant = heightShift
UIView.animate(withDuration: 0.3) {
// request layout on the *superview*
self.view.superview?.layoutIfNeeded()
}
An example for a simple layout as follows:
class MyClass {
/// Container view
let container = UIView()
/// View attached to container
let view = UIView()
/// Top constraint to animate
var topConstraint = NSLayoutConstraint()
/// Create the UI hierarchy and constraints
func createUI() {
container.addSubview(view)
// Create the top constraint
topConstraint = view.topAnchor.constraint(equalTo: container.topAnchor, constant: 0)
view.translatesAutoresizingMaskIntoConstraints = false
// Activate constaint(s)
NSLayoutConstraint.activate([
topConstraint,
])
}
/// Update view constraint with animation
func updateConstraint(heightShift: CGFloat) {
topConstraint.constant = heightShift
UIView.animate(withDuration: 0.3) {
// request layout on the *superview*
self.view.superview?.layoutIfNeeded()
}
}
}
If you are using Python, I would suggest by exploring the request object:
dir(request)
Since the object support the method dict:
request.__dict__
It can be printed or saved. I use it to log 404 codes in Flask:
@app.errorhandler(404)
def not_found(e):
with open("./404.csv", "a") as f:
f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')
Add the framework required for the method used in the project target in the "Link Binaries With Libraries" list of Build Phases, it will work easily. Like I have imported to my project
QuartzCore.framework
For the bug
Undefined symbols for architecture i386:
System read-only variable %CD%
keeps the path of the caller of the batch, not the batch file location.
You can get the name of the batch script itself as typed by the user with %0
(e.g. scripts\mybatch.bat
). Parameter extensions can be applied to this so %~dp0
will return the Drive and Path to the batch script (e.g. W:\scripts\
) and %~f0
will return the full pathname (e.g. W:\scripts\mybatch.cmd
).
You can refer to other files in the same folder as the batch script by using this syntax:
CALL %0\..\SecondBatch.cmd
This can even be used in a subroutine, Echo %0
will give the call label but, echo "%~nx0"
will give you the filename of the batch script.
When the %0
variable is expanded, the result is enclosed in quotation marks.
Since you didn't mention the version of Eclipse, I advice you to download the latest version of Eclipse Luna
which comes with Java 8 support by default.
You need the <pre></pre>
tags for the line breaks, and the {@code ... }
inside them for generics. But then it's not allowed to place the opening brace on the same line as the <generic>
tag, because then everything will be displayed on 1 line again.
Displays on one line:
* ..
* <pre>
* {@code
* public List<Object> getObjects() {
* return objects;
* }
* </pre>
* ..
Displays with line breaks:
* ..
* <pre>
* {@code
* public List<Object> getObjects()
* {
* return objects;
* }
* </pre>
* ..
Another weird thing is when you paste the closing brace of {@code
, it gets displayed:
* ..
* <pre>
* {@code
* public List<Object> getObjects()
* {
* return objects;
* }
* }
* </pre>
* ..
Output:
public List<Object> getObjects()
{
return objects;
}
}
I found a purely Javascript solution here that seems to work for major browsers for both PC and Mac. I tested it in BrowserStack for both platforms and it works like a dream. The Javascript solution posted in this thread by Jason D'Souza is really nice because it gives you a lot of information about the browser, but it has an issue identifying Edge which seems to look like Chrome to it. His code could probably be modified a bit with this solution to make it work for Edge too. Here is the snippet of code I found:
var browser = (function (agent) {
switch (true) {
case agent.indexOf("edge") > -1: return "edge";
case agent.indexOf("edg") > -1: return "chromium based edge (dev or canary)";
case agent.indexOf("opr") > -1 && !!window.opr: return "opera";
case agent.indexOf("chrome") > -1 && !!window.chrome: return "chrome";
case agent.indexOf("trident") > -1: return "ie";
case agent.indexOf("firefox") > -1: return "firefox";
case agent.indexOf("safari") > -1: return "safari";
default: return "other";
}
})(window.navigator.userAgent.toLowerCase());
console.log(window.navigator.userAgent.toLowerCase() + "\n" + browser);
Try dtIngest, it's developed on top of Apache Apex platform. This tool copies data from different sources like HDFS, shared drive, NFS, FTP, Kafka to different destinations. Copying data from remote HDFS cluster to local HDFS cluster is supported by dtIngest. dtIngest runs yarn jobs to copy data in parallel fashion, so it's very fast. It takes care of failure handling, recovery etc. and supports polling directories periodically to do continious copy.
Usage: dtingest [OPTION]... SOURCEURL... DESTINATIONURL example: dtingest hdfs://nn1:8020/source hdfs://nn2:8020/dest
The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with import * as Rx from "rxjs/Rx"
Then make sure to access the Observable
class as Rx.Observable
.
What role do they play when exiting an application in C#?
The same as every other application. Basically they get returned to the caller. Irrelvant if ythe start was an iicon double click. Relevant is the call is a batch file that decides whether the app worked on the return code. SO, unless you write a program that needs this, the return dcode IS irrelevant.
But what is the difference?
One comes from environment one from the System.Windows.Forms?.Application. Functionall there should not bbe a lot of difference.
#Variables
$computername = Get-Content 'M:\Applications\Powershell\comp list\Test.txt'
$sourcefile = "\\server\Apps\LanSchool 7.7\Windows\Student.msi"
#This section will install the software
foreach ($computer in $computername)
{
$destinationFolder = "\\$computer\C$\download\LanSchool"
#This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it will create it.
if (!(Test-Path -path $destinationFolder))
{
New-Item $destinationFolder -Type Directory
}
Copy-Item -Path $sourcefile -Destination $destinationFolder
Invoke-Command -ComputerName $computer -ScriptBlock { & cmd /c "msiexec.exe /i c:\download\LanSchool\Student.msi" /qn ADVANCED_OPTIONS=1 CHANNEL=100}
}
I've searched all over for this myself and came up with zilch but have finally cobbled this working script together. It's working great! Thought I'd post here hopefully someone else can benefit. It pulls in a list of computers, copies the files down to the local machines and runs it. :) party on!
You can use strip() or split() to control the spaces values as in the following:
words = " first second "
# Remove end spaces
def remove_end_spaces(string):
return "".join(string.rstrip())
# Remove the first and end spaces
def remove_first_end_spaces(string):
return "".join(string.rstrip().lstrip())
# Remove all spaces
def remove_all_spaces(string):
return "".join(string.split())
# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
Robert Love's book LINUX System Programming 2nd Edition, specifically addresses your question at the beginning of Chapter 11, pg 363:
The important aspect of a monotonic time source is NOT the current value, but the guarantee that the time source is strictly linearly increasing, and thus useful for calculating the difference in time between two samplings
That said, I believe he is assuming the processes are running on the same instance of an OS, so you might want to have a periodic calibration running to be able to estimate drift.
well, there are two way to change max_execution_time.
1. You can directly set it in php.ini file.
2. Secondly, you can add following line in your code.
ini_set('max_execution_time', '100')
Add %CATALINA_HOME%/bin
to path system variable.
Go to Environment Variables
screen under System Variables
there will be a Path
variable edit the variable and add ;%CATALINA_HOME%\bin
to the variable then click OK
to save the changes. Close all opened command prompts then open a new command prompt and try to use the command startup.bat
.
We use groovy job file:
description('')
steps {
environmentVariables {
envs(PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: true)
}
}
keySet() only returns a set of keys from your hashmap, you should iterate this key set and the get the value from the hashmap using these keys.
In your example, the type of the hashmap's key is TypeKey
, but you specified TypeValue
in your generic for-loop, so it cannot be compiled. You should change it to :
for (TypeKey name: example.keySet()){
String key = name.toString();
String value = example.get(name).toString();
System.out.println(key + " " + value);
}
Update for Java8:
example.entrySet().forEach(entry->{
System.out.println(entry.getKey() + " " + entry.getValue());
});
If you don't require to print key value and just need the hashmap value, you can use others' suggestions.
Another question: Is this collection is zero base? I mean if it has 1 key and value will it size be 0 or 1?
The collection returned from keySet()
is a Set.You cannot get the value from a Set using an index, so it is not a question of whether it is zero-based or one-based. If your hashmap has one key, the keySet() returned will have one entry inside, and its size will be 1.
$('input[type=file]').change(function(e){
$(this).parents('.parent-selector').find('.element-to-paste-filename').text(e.target.files[0].name);
});
This code will not show C:\fakepath\
before file name in Google Chrome in case of using .val()
.
If you don't have the token at the time of the call is made, You will have to make two calls, one to get the token and the other to extract the token form the response, pay attention to
grep token | cut -d, -f1 | cut -d\" -f4
as it is the part which is dealing with extracting the token from the response.
echo "Getting token response and extracting token"
def token = sh (returnStdout: true, script: """
curl -S -i -k -X POST https://www.example.com/getToken -H \"Content-Type: application/json\" -H \"Accept: application/json\" -d @requestFile.json | grep token | cut -d, -f1 | cut -d\\" -f4
""").split()
After extracting the token you can use the token to make subsequent calls as follows.
echo "Token : ${token[-1]}"
echo "Making calls using token..."
curl -S -i -k -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer ${token[-1]}" https://www.example.com/api/resources
The problem with the solution suggested is that it can break some performance features built into the SessionState if you are using an out-of-process session storage. (either "State Server Mode" or "SQL Server Mode"). In oop modes the session data needs to be serialized at the end of the page request and deserialized at the beginning of the page request, which can be costly. To improve the performance the SessionState attempts to only deserialize what is needed by only deserialize variable when it is accessed the first time, and it only re-serializes and replaces variable which were changed. If you have alot of session variable and shove them all into one class essentially everything in your session will be deserialized on every page request that uses session and everything will need to be serialized again even if only 1 property changed becuase the class changed. Just something to consider if your using alot of session and an oop mode.
It is really easy to write text on a canvas. It was not clear if you want someone to enter text in the HTML page and then have that text appear on the canvas, or if you were going to use JavaScript to write the information to the screen.
The following code will write some text in different fonts and formats to your canvas. You can modify this as you wish to test other aspects of writing onto a canvas.
<canvas id="YourCanvasNameHere" width="500" height="500">Canvas not supported</canvas>
var c = document.getElementById('YourCanvasNameHere');
var context = c.getContext('2d'); //returns drawing functions to allow the user to draw on the canvas with graphic tools.
You can either place the canvas ID tag in the HTML and then reference the name or you can create the canvas in the JavaScript code. I think that for the most part I see the <canvas>
tag in the HTML code and on occasion see it created dynamically in the JavaScript code itself.
Code:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.font = 'bold 10pt Calibri';
context.fillText('Hello World!', 150, 100);
context.font = 'italic 40pt Times Roman';
context.fillStyle = 'blue';
context.fillText('Hello World!', 200, 150);
context.font = '60pt Calibri';
context.lineWidth = 4;
context.strokeStyle = 'blue';
context.strokeText('Hello World!', 70, 70);
Yes, you should use HTTP status codes. And also preferably return error descriptions in a somewhat standardized JSON format, like Nottingham’s proposal, see apigility Error Reporting:
The payload of an API Problem has the following structure:
- type: a URL to a document describing the error condition (optional, and "about:blank" is assumed if none is provided; should resolve to a human-readable document; Apigility always provides this).
- title: a brief title for the error condition (required; and should be the same for every problem of the same type; Apigility always provides this).
- status: the HTTP status code for the current request (optional; Apigility always provides this).
- detail: error details specific to this request (optional; Apigility requires it for each problem).
- instance: URI identifying the specific instance of this problem (optional; Apigility currently does not provide this).
Duck typing:
If it talks and walks like a duck, then it is a duck
This is typically called abduction (abductive reasoning or also called retroduction, a clearer definition I think):
from C (conclusion, what we see) and R (rule, what we know), we accept/decide/assume P (Premise, property) in other words a given fact
... the very basis of medical diagnosis
with ducks: C = walks, talks, R = like a duck, P = it's a duck
Back to programming:
object o has method/property mp1 and interface/type T requires/defines mp1
object o has method/property mp2 and interface/type T requires/defines mp2
...
So, more than simply accepting mp1... on any object as long has it meets some definition of mp1..., compiler/runtime should also be okay with the assertion o is of type T
And well, is it the case with examples above? Is Duck typing is essentially no typing at all? Or should we call it implicit typing?
This might be too late to answer. But this may help someone.
In my case there was problem of JDK path.
I just set proper JDK path for Android Studio 2.1
File -> Project Structure -> From Left Side Panel "SDK Location" -> JDK Location -> Click to select JDK Path
There many cases where script Manager may give problem like that. you Try This First add Script Manager in appropriate Placeholder or any place Holder which appears before the content in which Ajax Control is used.
We need to add ScriptManager while using any AJAX Control not only update Panel.
<asp:ScriptManager ID="ScriptManger1" runat="Server" />
If you are using Latest Ajax Control Toolkit (I am not sure about version 4.0 or 4.5) you need to use that Particular ToolkitScriptManager and not ScriptManager from default Ajax Extensions.
You can use only one ScriptManager or ToolKitScriptManager on page, If you have added it on Master Page you no need to add it again on Web Page.
The problem mentioned here may because of ContentPlaceHolder Please Check how many content place holders you have on your master page. Lets take an example if you have 2 content Placeholders "Head" and "ContentPlaceHolder1" on Master Page and ContentPlaceHolder1 is your Content Page.please check below code I added here my ScriptManager on Second Placeholder just below there is update panel.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="MainContent" runat="server">
<asp:ScriptManager ID="ScriptManger1" runat="Server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Most of us make mistake while designing web form when we choose masterpage by default on web page there are equal number of placeholders as of MasterPage.
<%@ Page Title="" Language="C#" MasterPageFile="~/Master Pages/Home.master" AutoEventWireup="true" CodeFile="frmCompanyLogin.aspx.cs" Inherits="Authentication_frmCompanyLogin" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
</asp:Content>
We no need to remove any PlaceHolder it is guiding structure but you must have to add the web form Contents in Same PlaceHolder where you added your ScriptManager(on Master Page) or add Script Manager in appropriate Placeholder or any place Holder which appears before the content in which Ajax Control is used.
The action bar now enhanced to app bar.So you have to add conditional check for getting height of action bar.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
height = getActivity().getActionBar().getHeight();
} else {
height = ((ActionBarActivity) getActivity()).getSupportActionBar().getHeight();
}
To sum up all the brilliant points of chrispy, Skurmedel, Ben Hoyt and Peter Hansen, this would be the optimal solution for processing a binary file one byte at a time:
with open("myfile", "rb") as f:
while True:
byte = f.read(1)
if not byte:
break
do_stuff_with(ord(byte))
For python versions 2.6 and above, because:
Or use J. F. Sebastians solution for improved speed
from functools import partial
with open(filename, 'rb') as file:
for byte in iter(partial(file.read, 1), b''):
# Do stuff with byte
Or if you want it as a generator function like demonstrated by codeape:
def bytes_from_file(filename):
with open(filename, "rb") as f:
while True:
byte = f.read(1)
if not byte:
break
yield(ord(byte))
# example:
for b in bytes_from_file('filename'):
do_stuff_with(b)
Works here:
$ TESTSTRINGONE="MOTEST"
$ NEWTESTSTRING=${TESTSTRINGONE:0:5}
$ echo ${NEWTESTSTRING}
MOTES
What shell are you using?
So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.
Try it this way...
I am considering the HashMap
with key and value of type String
, HashMap<String,String>
HashMap<String,String> hmap = new HashMap<String,String>();
hmap.put("key1","Val1");
hmap.put("key2","Val2");
ArrayList<String> arList = new ArrayList<String>();
for(Map.Entry<String,String> map : hmap.entrySet()){
arList.add(map.getValue());
}
It depends on the semantic of the primary key. If it's just autoincrement, then use something like:
insert into table1 (all columns except pk)
select all_columns_except_pk
from table2;
If PK means something, you need to find a way to determine which record should have priority. You could create a select query to find duplicates first (see answer by cpitis). Then eliminate the ones you don't want to keep and use the above insert to add records that remain.
Here this should help you
The below jsfiddle link will help you understand how to rotate a image.I used the same one to rotate the dial of a clock.
var rotation = function (){
$("#image").rotate({
angle:0,
animateTo:360,
callback: rotation,
easing: function (x,t,b,c,d){
return c*(t/d)+b;
}
});
}
rotation();
Where: • t: current time,
• b: begInnIng value,
• c: change In value,
• d: duration,
• x: unused
No easing (linear easing): function(x, t, b, c, d) { return b+(t/d)*c ; }
Just another way to do this:
=MID(A1, LEN(A1), 1)
If you want to pass variables to the server using GET that would be the way yes. Remember to escape (urlencode) them properly!
It is also possible to use POST, if you dont want your variables to be visible.
A complete sample would be:
var url = "bla.php";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function()
{
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
To test this, (using PHP) you could var_dump $_GET
to see what you retrieve.
Try this code. This does what you want.
LOGIC
""
with blanks and write to the new file at the same time.CODE (TRIED AND TESTED)
Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Const MAX_PATH As Long = 260
'~~> Change this where and how you want to save the file
Const FlName = "C:\Users\Siddharth Rout\Desktop\MyWorkbook.txt"
Sub Sample()
Dim tmpFile As String
Dim MyData As String, strData() As String
Dim entireline As String
Dim filesize As Integer
'~~> Create a Temp File
tmpFile = TempPath & Format(Now, "ddmmyyyyhhmmss") & ".txt"
ActiveWorkbook.SaveAs Filename:=tmpFile _
, FileFormat:=xlText, CreateBackup:=False
'~~> Read the entire file in 1 Go!
Open tmpFile For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
'~~> Get a free file handle
filesize = FreeFile()
'~~> Open your file
Open FlName For Output As #filesize
For i = LBound(strData) To UBound(strData)
entireline = Replace(strData(i), """", "")
'~~> Export Text
Print #filesize, entireline
Next i
Close #filesize
MsgBox "Done"
End Sub
Function TempPath() As String
TempPath = String$(MAX_PATH, Chr$(0))
GetTempPath MAX_PATH, TempPath
TempPath = Replace(TempPath, Chr$(0), "")
End Function
SNAPSHOTS
Actual Workbook
After Saving
Apache commons collections 4 has a CircularFifoQueue<> which is what you are looking for. Quoting the javadoc:
CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.
import java.util.Queue;
import org.apache.commons.collections4.queue.CircularFifoQueue;
Queue<Integer> fifo = new CircularFifoQueue<Integer>(2);
fifo.add(1);
fifo.add(2);
fifo.add(3);
System.out.println(fifo);
// Observe the result:
// [2, 3]
If you are using an older version of the Apache commons collections (3.x), you can use the CircularFifoBuffer which is basically the same thing without generics.
Update: updated answer following release of commons collections version 4 that supports generics.
My solution without using moment
is to convert it to a timestamp, add the timezone offset, then convert back to a date object, and then run the toISOString()
var date = new Date(); // Or the date you'd like converted.
var isoDateTime = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
I have found an excellent and relatively short explanation here.
A multipart request is a REST request containing several packed REST requests inside its entity.
First you need to publish the file by:
BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go.
Save your file to a particular folder.
Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug
folder below the project file (.csproj).
In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files.
(You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)
NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
I can see that the accepted answer uses position: absolute;
instead of float: left
. In case you want to use float: left
with the following structure,
<div class="parent">
<div class="child-left floatLeft"></div>
<div class="child-right floatLeft"></div>
</div>
Give position: auto;
to the parent so that it will contain its children height.
.parent {
position: auto;
}
.floatLeft {
float: left
}
The error "only length-1 arrays can be converted to Python scalars" is raised when the function expects a single value but you pass an array instead.
If you look at the call signature of np.int
, you'll see that it accepts a single value, not an array. In general, if you want to apply a function that accepts a single element to every element in an array, you can use np.vectorize
:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.int(x)
f2 = np.vectorize(f)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
plt.show()
You can skip the definition of f(x) and just pass np.int to the vectorize function: f2 = np.vectorize(np.int)
.
Note that np.vectorize
is just a convenience function and basically a for loop. That will be inefficient over large arrays. Whenever you have the possibility, use truly vectorized functions or methods (like astype(int)
as @FFT suggests).
Basic Idea of using Fragments (F) is to create reusable self sustaining UI components in android applications. These Fragments are contained in activities and there are common(best) way of creating communication path ways from A -> F and F-A, It is a must to Communicate between F-F through a Activity because then only the Fragments become decoupled and self sustaining.
So passing data from A -> F is going to be the same as explained by ??s???? K. In addition to that answer, After creation of the Fragments inside an Activity, we can also pass data to the fragments calling methods in Fragments.
For example:
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
articleFrag.updateArticleView(position);
The reset_index() is a pandas DataFrame method that will transfer index values into the DataFrame as columns. The default setting for the parameter is drop=False (which will keep the index values as columns).
All you have to do add .reset_index(inplace=True)
after the name of the DataFrame:
df.reset_index(inplace=True)
If use are already have Apache commons-io available on the classpath, you may use:
Process p = new ProcessBuilder("cat", "/etc/something").start();
String stderr = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
String stdout = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());
On my Gentoo/Funtoo linux system I am having similar problems:
I gotting always not the correct device description and insufficient permissions:
# sudo ./adb devices
List of devices attached
???????????? no permissions
# ./adb usb
error: insufficient permissions for device
For me helps the howto from Google. In my case I needed to add the udev rule:
# cat /etc/udev/rules.d/51-android.rules
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", MODE="0666", GROUP="plugdev"
and setting up the filesystem rights
# chmod a+r /etc/udev/rules.d/51-android.rules
After replugging my smartphone the access to the phone was successful, it also appears now in Eclipse' Android Device Chooser:
# sudo ./adb devices
List of devices attached
3XXXXXXXXXXXXXC device
# sudo ./adb usb
restarting in USB mode
You also have to check the membership of your user to the plugdev-group.
This question is vague, but if you want to make the image with Javascript. It is simple.
function loadImages(src) {
if (document.images) {
img1 = new Image();
img1.src = src;
}
loadImages("image.jpg");
The image will be requested but until you show it it will never be displayed. great for pre loading images you expect to be requests but delaying it until the document is loaded.
The core team responsible for Postgres is gradually phasing out OIDs.
The use of OID as an optional system column on your tables is now removed from Postgres 12. You can no longer use:
CREATE TABLE … WITH OIDS
commanddefault_with_oids (boolean)
compatibility settingThe data type OID
remains in Postgres 12. You can explicitly create a column of the type OID
.
After migrating to Postgres 12, any optionally-defined system column oid
will no longer be invisible by default. Performing a SELECT *
will now include this column. Note that this extra “surprise” column may break naïvely written SQL code.
All package managers have many downsides. You just have to pick which you can live with.
npm started out managing node.js modules (that's why packages go into node_modules
by default), but it works for the front-end too when combined with Browserify or webpack.
Bower is created solely for the front-end and is optimized with that in mind.
npm is much, much larger than bower, including general purpose JavaScript (like country-data
for country information or sorts
for sorting functions that is usable on the front end or the back end).
Bower has a much smaller amount of packages.
Bower includes styles etc.
npm is focused on JavaScript. Styles are either downloaded separately or required by something like npm-sass
or sass-npm
.
The biggest difference is that npm does nested dependencies (but is flat by default) while Bower requires a flat dependency tree (puts the burden of dependency resolution on the user).
A nested dependency tree means that your dependencies can have their own dependencies which can have their own, and so on. This allows for two modules to require different versions of the same dependency and still work. Note since npm v3, the dependency tree will be flat by default (saving space) and only nest where needed, e.g., if two dependencies need their own version of Underscore.
Some projects use both: they use Bower for front-end packages and npm for developer tools like Yeoman, Grunt, Gulp, JSHint, CoffeeScript, etc.
Apache MPM prefork with modphp is used because it is easy to configure/install. Performance-wise it is fairly inefficient. My preferred way to do the stack, FastCGI/PHP-FPM. That way you can use the much faster MPM Worker. The whole PHP remains non-threaded, but Apache serves threaded (like it should).
So basically, from bottom to top
Linux
Apache + MPM Worker + ModFastCGI (NOT FCGI) |(or)| Cherokee |(or)| Nginx
PHP-FPM + APC
ModFCGI does not correctly support PHP-FPM, or any external FastCGI applications. It only supports non-process managed FastCGI scripts. PHP-FPM is the PHP FastCGI process manager.
#include <iostream>
using namespace std;
int main () {
bool boolean;
boolean = true;
if (boolean == true) {
cout << "press any key to continue";
cin >> boolean;
}
return 0;
}
Here is the simple version
#one
a = [[0]*10]*10
#two
row, col = 10, 10
a = [[0]*row]*col
This code can also compare floats. It is using awk (it is not pure bash), however this shouldn't be a problem, as awk is a standard POSIX command that is most likely shipped by default with your operating system.
$ awk 'BEGIN {return_code=(-1.2345 == -1.2345) ? 0 : 1; exit} END {exit return_code}'
$ echo $?
0
$ awk 'BEGIN {return_code=(-1.2345 >= -1.2345) ? 0 : 1; exit} END {exit return_code}'
$ echo $?
0
$ awk 'BEGIN {return_code=(-1.2345 < -1.2345) ? 0 : 1; exit} END {exit return_code}'
$ echo $?
1
$ awk 'BEGIN {return_code=(-1.2345 < 2) ? 0 : 1; exit} END {exit return_code}'
$ echo $?
0
$ awk 'BEGIN {return_code=(-1.2345 > 2) ? 0 : 1; exit} END {exit return_code}'
$ echo $?
To make it shorter for use, use this function:
compare_nums()
{
# Function to compare two numbers (float or integers) by using awk.
# The function will not print anything, but it will return 0 (if the comparison is true) or 1
# (if the comparison is false) exit codes, so it can be used directly in shell one liners.
#############
### Usage ###
### Note that you have to enclose the comparison operator in quotes.
#############
# compare_nums 1 ">" 2 # returns false
# compare_nums 1.23 "<=" 2 # returns true
# compare_nums -1.238 "<=" -2 # returns false
#############################################
num1=$1
op=$2
num2=$3
E_BADARGS=65
# Make sure that the provided numbers are actually numbers.
if ! [[ $num1 =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then >&2 echo "$num1 is not a number"; return $E_BADARGS; fi
if ! [[ $num2 =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then >&2 echo "$num2 is not a number"; return $E_BADARGS; fi
# If you want to print the exit code as well (instead of only returning it), uncomment
# the awk line below and comment the uncommented one which is two lines below.
#awk 'BEGIN {print return_code=('$num1' '$op' '$num2') ? 0 : 1; exit} END {exit return_code}'
awk 'BEGIN {return_code=('$num1' '$op' '$num2') ? 0 : 1; exit} END {exit return_code}'
return_code=$?
return $return_code
}
$ compare_nums -1.2345 ">=" -1.2345 && echo true || echo false
true
$ compare_nums -1.2345 ">=" 23 && echo true || echo false
false
To convert an Array[Row] to DataFrame or Dataset, the following works elegantly:
Say, schema is the StructType for the row,then
val rows: Array[Row]=...
implicit val encoder = RowEncoder.apply(schema)
import spark.implicits._
rows.toDS
The code below works with Last, First M name strings. Substitute "Name" with your name string column name. Since you have a period as a final character when there is a middle initial, you would replace the 2's with 3's in each of the lines (2, 6, and 8)- and change "RIGHT(Name, 1)" to "RIGHT(Name, 2)" in line 8.
SELECT SUBSTRING(Name, 1, CHARINDEX(',', Name) - 1) LastName ,
CASE WHEN LEFT(RIGHT(Name, 2), 1) <> ' '
THEN LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99))
ELSE LEFT(LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99)),
LEN(LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99)))
- 2)
END FirstName ,
CASE WHEN LEFT(RIGHT(Name, 2), 1) = ' ' THEN RIGHT(Name, 1)
ELSE NULL
END MiddleName
The Swifty way is to use the new UIAlertController and closures:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.presentViewController(alertController, animated: true, completion: nil)
Swift 3:
// Create the alert controller
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
Another one answer
static class ImmutableArray<T> {
private final T[] array;
private ImmutableArray(T[] a){
array = Arrays.copyOf(a, a.length);
}
public static <T> ImmutableArray<T> from(T[] a){
return new ImmutableArray<T>(a);
}
public T get(int index){
return array[index];
}
}
{
final ImmutableArray<String> sample = ImmutableArray.from(new String[]{"a", "b", "c"});
}
FragmentActivity
gives you all of the functionality of Activity
plus the ability to use Fragments which are very useful in many cases, particularly when working with the ActionBar, which is the best way to use Tabs in Android.
If you are only targeting Honeycomb (v11) or greater devices, then you can use Activity
and use the native Fragments introduced in v11 without issue. FragmentActivity
was built specifically as part of the Support Library to back port some of those useful features (such as Fragments) back to older devices.
I should also note that you'll probably find the Backward Compatibility - Implementing Tabs training very helpful going forward.
There are different kinds of flags & masks you can use as well. Please refer http://www.cplusplus.com/reference/iostream/ios_base/setf/ for more information.
#include <iostream>
using namespace std;
int main()
{
int num = 255;
cout.setf(ios::hex, ios::basefield);
cout << "Hex: " << num << endl;
cout.unsetf(ios::hex);
cout << "Original format: " << num << endl;
return 0;
}
In Chrome, For "Selenium IDE", I was also struggling that it doesn't pause. It will pause, if you give as below:
This will pause for 10 seconds.
configure static ip on the raspberry pi:
sudo nano /etc/network/interfaces
and then add:
iface eth0 inet static
address 169.254.0.2
netmask 255.255.255.0
broadcast 169.254.0.255
then you can acces your raspberry via ssh
ssh [email protected]
Use the filename
property like this:
uriContent = "data:application/octet-stream;filename=filename.txt," +
encodeURIComponent(codeMirror.getValue());
newWindow=window.open(uriContent, 'filename.txt');
EDIT:
Apparently, there is no reliable way to do this. See: Is there any way to specify a suggested filename when using data: URI?
To customize the colors for the carousel controls, captions, and indicators using Sass you can include these variables
$carousel-control-color:
$carousel-caption-color:
$carousel-indicator-active-bg:
The C++ spec doesn't say exactly what algorithm you must use for the STL containers. It does, however, put certain constraints on their performance, which rules out the use of hash tables for map
and other associative containers. (They're most commonly implemented with red/black trees.) These constraints require better worst-case performance for these containers than hash tables can deliver.
Many people really do want hash tables, however, so hash-based STL associative containers have been a common extension for years. Consequently, they added unordered_map
and such to later versions of the C++ standard.
If you use jdk8 see @Nathaniel Johnson's answer as that is better.
I think that many of the answer here are complex or not easily read. With branch prediction so efficient why you simply not use a if statement?
public static String join(List<String> fooList){
if (fooList.isEmpty()) return "";
StringBuilder sb = null;
for (String element : fooList) {
if (sb == null) {
sb = new StringBuilder();
} else {
sb.append(", ");
}
sb.append(element);
}
return sb.toString();
}
Something that should be mentioned is that Apache uses a simple for loop with an if statement inside it like this (it uses an array as its index to know the first element), and openjdk 8 does the same but in separated methods calls instead of a simple loop.
You need to use ListBox.ItemContainerStyle.
ListBox.ItemTemplate specifies how the content of an item should be displayed. But WPF still wraps each item in a ListBoxItem control, which by default gets its Background set to the system highlight colour if it is selected. You can't stop WPF creating the ListBoxItem controls, but you can style them -- in your case, to set the Background to always be Transparent or Black or whatever -- and to do so, you use ItemContainerStyle.
juFo's answer shows one possible implementation, by "hijacking" the system background brush resource within the context of the item style; another, perhaps more idiomatic technique is to use a Setter
for the Background property.
For setting up virtualenv on a clean Ubuntu installation, I found this zookeeper tutorial to be the best - you can ignore the parts about zookeper itself. The virtualenvwrapper documentation offers similar content, but it's a bit scarce on telling you what exactly to put into your .bashrc
file.
Simply
$os = array("Mac", "NT", "Irix", "Linux");
if (!in_array("BB", $os)) {
echo "BB is not found";
}
If you are trying to login with SQL credentials, you can also try changing the LoginMode for SQL Server in the registry to allow both SQL Server and Windows Authentication.
This is because you are reading a cursor, not an array. This means that you are reading sequentially through the results and when you get to the end you would need to reset the cursor to the beginning of the results to read them again.
If you did want to read over the results multiple times, you could use fetchAll to read the results into a true array and then it would work as you are expecting.
I fixed this problem by uninstalling the 64-bit version and installing a 32-bit version of Git
All the answers above are correct, but I think this is the easiest example possible:
public class ExampleActivity extends Activity {
private Handler handler;
private ProgressBar progress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = (ProgressBar) findViewById(R.id.progressBar1);
handler = new Handler();
}
public void clickAButton(View view) {
// Do something that takes a while
Runnable runnable = new Runnable() {
@Override
public void run() {
handler.post(new Runnable() { // This thread runs in the UI
@Override
public void run() {
progress.setProgress("anything"); // Update the UI
}
});
}
};
new Thread(runnable).start();
}
}
What this does is update a progress bar in the UI thread from a completely different thread passed through the post() method of the handler declared in the activity.
Hope it helps!
All this talk about collation seem a bit over-complicated. Why not just use something like:
IF UPPER(@@VERSION) NOT LIKE '%AZURE%'
Then your check is case insensitive whatever the collation
I found the answers above didn't give me the guidance I needed (I too expected to be in the code for the .java file, and right-click on the tab and see a Refactor option). Here's what I did:
Try using .+
instead of [(\w)(\W)(\s)]+
.
Note that this actually includes more than you need - ASCII only defines the first 128 characters.
Instead of NOW()
you can use UNIX_TIMESTAMP()
also:
$update_query = "UPDATE db.tablename
SET insert_time=UNIX_TIMESTAMP()
WHERE username='$somename'";
This answer comes late but summarizes the concept involved in the "table not mapped" exception(in order to help those who come across this problem since its very common for hibernate newbies). This error can appear due to many reasons but the target is to address the most common one that is faced by a number of novice hibernate developers to save them hours of research. I am using my own example for a simple demonstration below.
The exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: subscriber is not mapped [ from subscriber]
In simple words, this very usual exception only tells that the query is wrong in the below code.
Session session = this.sessionFactory.getCurrentSession();
List<Subscriber> personsList = session.createQuery(" from subscriber").list();
This is how my POJO class is declared:
@Entity
@Table(name = "subscriber")
public class Subscriber
But the query syntax "from subscriber" is correct and the table subscriber
exists. Which brings me to a key point:
and how its explained here
HQL works with persistent objects and their properties not with the database tables and columns.
Since the above query is an HQL one, the subscriber
is supposed to be an entity name not a table name. Since I have my table subscriber
mapped with the entity Subscriber
. My problem solves if I change the code to this:
Session session = this.sessionFactory.getCurrentSession();
List<Subscriber> personsList = session.createQuery(" from Subscriber").list();
Just to keep you from getting confused. Please note that HQL is case sensitive in a number of cases. Otherwise it would have worked in my case.
Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.
https://www.tutorialspoint.com/hibernate/hibernate_query_language.htm
To further understand how hibernate mapping works, please read this
To know where Python is installed you can execute where python
in your cmd.exe.
If you want to use the primitive wrapper classes, this will work, but all java types are signed by default.
public static void main(String[] args) {
Integer i=5;
Byte b = Byte.valueOf(i+""); //converts i to String and calls Byte.valueOf()
System.out.println(b);
System.out.println(Integer.valueOf(b));
}
IF YOU ARE USING NGINX :
cd /etc/php/<PHP_VERSION>/fpm
example => cd /etc/php/7.2/fpm
nano php.ini
post_max_size = 1024M
upload_max_filesize = 1024M
max_execution_time = 3600
max_input_time = 3600
memory_limit = 1024M
after saving php.ini file , restart fpm using :
systemctl restart php<PHP_VERSION>-fpm
example => systemctl restart php7.2-fpm
ROWS UNBOUNDED PRECEDING
is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY
it defines the window on which the result is calculated.
Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.
Starting and ending rows might be fixed or relative to the current row based on the following keywords:
Possible kinds of calculation include:
So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING)
results in a Cumulative Sum or Running Total
11 -> 11
2 -> 11 + 2 = 13
3 -> 13 + 3 (or 11+2+3) = 16
44 -> 16 + 44 (or 11+2+3+44) = 60
Try adding JSON.stringify(result)
to convert the JS Object into a JSON string.
From your code I can see you are logging the result in error
which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).
Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.
In TortoiseSVN you can configure the proxy server under Settings=> Network
I had this problem, and the cause was that I had not added the Microsoft.Owin.Host.SystemWeb NuGet package to my project. Although the code in my startup class was correct, it was not being executed.
So if you're trying to solve this problem, put a breakpoint in the code where you do the Unity registrations. If you don't hit it, your dependency injection isn't going to work.
A Custom Laravel Validation Rule will allow developers to provide a custom message with each use case for a better UX experience.
php artisan make:rule IsValidPassword
namespace App\Rules;
use Illuminate\Support\Str;
use Illuminate\Contracts\Validation\Rule;
class isValidPassword implements Rule
{
/**
* Determine if the Length Validation Rule passes.
*
* @var boolean
*/
public $lengthPasses = true;
/**
* Determine if the Uppercase Validation Rule passes.
*
* @var boolean
*/
public $uppercasePasses = true;
/**
* Determine if the Numeric Validation Rule passes.
*
* @var boolean
*/
public $numericPasses = true;
/**
* Determine if the Special Character Validation Rule passes.
*
* @var boolean
*/
public $specialCharacterPasses = true;
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$this->lengthPasses = (Str::length($value) >= 10);
$this->uppercasePasses = (Str::lower($value) !== $value);
$this->numericPasses = ((bool) preg_match('/[0-9]/', $value));
$this->specialCharacterPasses = ((bool) preg_match('/[^A-Za-z0-9]/', $value));
return ($this->lengthPasses && $this->uppercasePasses && $this->numericPasses && $this->specialCharacterPasses);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
switch (true) {
case ! $this->uppercasePasses
&& $this->numericPasses
&& $this->specialCharacterPasses:
return 'The :attribute must be at least 10 characters and contain at least one uppercase character.';
case ! $this->numericPasses
&& $this->uppercasePasses
&& $this->specialCharacterPasses:
return 'The :attribute must be at least 10 characters and contain at least one number.';
case ! $this->specialCharacterPasses
&& $this->uppercasePasses
&& $this->numericPasses:
return 'The :attribute must be at least 10 characters and contain at least one special character.';
case ! $this->uppercasePasses
&& ! $this->numericPasses
&& $this->specialCharacterPasses:
return 'The :attribute must be at least 10 characters and contain at least one uppercase character and one number.';
case ! $this->uppercasePasses
&& ! $this->specialCharacterPasses
&& $this->numericPasses:
return 'The :attribute must be at least 10 characters and contain at least one uppercase character and one special character.';
case ! $this->uppercasePasses
&& ! $this->numericPasses
&& ! $this->specialCharacterPasses:
return 'The :attribute must be at least 10 characters and contain at least one uppercase character, one number, and one special character.';
default:
return 'The :attribute must be at least 10 characters.';
}
}
}
Then on your request validation:
$request->validate([
'email' => 'required|string|email:filter',
'password' => [
'required',
'confirmed',
'string',
new isValidPassword(),
],
]);
Though many have already answered the difference between Val and var. But one point to notice is that val is not exactly like final keyword.
We can change the value of val using recursion but we can never change value of final. Final is more constant than Val.
def factorial(num: Int): Int = {
if(num == 0) 1
else factorial(num - 1) * num
}
Method parameters are by default val and at every call value is being changed.
This can be done with PIL
. First, install it, then you can take a full screenshot like this:
import PIL.ImageGrab
im = PIL.ImageGrab.grab()
im.show()
You can do this:
$("form :input").change(function() {
$(this).closest('form').data('changed', true);
});
$('#mybutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
This rigs a change
event handler to inputs in the form, if any of them change it uses .data()
to set a changed
value to true
, then we just check for that value on the click, this assumes that #mybutton
is inside the form (if not just replace $(this).closest('form')
with $('#myForm')
), but you could make it even more generic, like this:
$('.checkChangedbutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
References: Updated
According to jQuery this is a filter to select all form controls.
http://api.jquery.com/input-selector/
The :input selector basically selects all form controls.
Here is some code that might not be optimal but at least actually finds the 2nd largest element:
if( val[ 0 ] > val[ 1 ] )
{
largest = val[ 0 ]
secondLargest = val[ 1 ];
}
else
{
largest = val[ 1 ]
secondLargest = val[ 0 ];
}
for( i = 2; i < N; ++i )
{
if( val[ i ] > secondLargest )
{
if( val[ i ] > largest )
{
secondLargest = largest;
largest = val[ i ];
}
else
{
secondLargest = val[ i ];
}
}
}
It needs at least N-1 comparisons if the largest 2 elements are at the beginning of the array and at most 2N-3 in the worst case (one of the first 2 elements is the smallest in the array).
let keyword defines a constant
let myNum = 7
so myNum can't be changed afterwards;
But var defines an ordinary variable.
The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once.
You can use almost any character you like for constant and variable names, including Unicode characters;
e.g.
var x = 7 // here x is instantiated with 7
x = 99 // now x is 99 it means it has been changed.
But if we take let then...
let x = 7 // here also x is instantiated with 7
x = 99 // this will a compile time error
TNSPing command line will show the version. similarly, sqlPlus.exe will print its version. You can also go to the readme files in the 'relnotes' directory of your client install. Version 10.2 has a file named README_jdbc.txt, for example, which will tell you which version has been installed.
Use command-line option -v
or --invert-match
,
ls -R |grep -v -E .*[\.exe]$\|.*[\.html]$
I've coded up a helper class for doing this. You can see the code at github: https://github.com/quiqueqs/Toast-Expander/blob/master/src/com/thirtymatches/toasted/ToastedActivity.java
This is how you'd display a toast for 5 seconds (or 5000 milliseconds):
Toast aToast = Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT);
ToastExpander.showFor(aToast, 5000);
I had this problem, after installing jdk7 next to Java 6. The binaries were correctly updated using update-alternatives --config java
to jdk7, but the $JAVA_HOME
environment variable still pointed to the old directory of Java 6.
It's hard to tell without knowing the HTML code, but I'd assume your div doesn't have a height set and/or doesn't allow overflow (e.g. through CSS height: 200px; overflow: auto
).
I've made a working sample on jsfiddle: http://jsfiddle.net/hu4zqq4x/
I created some dummy HTML markup inside a div that is a) overflowing and b) has a set height. Scrolling is done through calling the function
function getMessages(letter) {
var div = $("#messages");
div.scrollTop(div.prop('scrollHeight'));
}
, in this case once on 'documentReady'.
prop('scrollHeight')
will access the value of the property on the first element in the set of matched elements.
Just make regular link look like button :)
<a href="#" role="button" class="btn btn-success btn-large">Click here!</a>
"role" inside a href code makes it look like button, ofc you can add more variables such as class.
Your code works. If you don't have any output, you may have "forgotten" to add some values to the list:
// add values
list.add("one");
list.add("two");
// your code
for (String object: list) {
System.out.println(object);
}
Read about the super keyword (Scroll down the Subclass Constructors). If I understand your question, you probably want to call a superclass constructor?
It is worth noting that the Java compiler will automatically put in a no-arg constructor call to the superclass if you do not explicitly invoke a superclass constructor.
select * from mytable where mydate > now() - interval '1 year';
If you only care about the date and not the time, substitute current_date
for now()
the point can be if you are not using valid login for linked server. Problem is on destination server side.
There are few steps to try:
Align db user and login on destination server: alter user [DBUSER_of_linkedserverlogin] with login = [linkedserverlogin]
recreate login on destination server used by linked server.
Backup table and recreate it.
2nd resolved my issue with "The value violated the integrity constraints for the column.".
If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.
This is what operator.itemgetter
is for.
>>> a = [(1, u'abc'), (2, u'def')]
>>> import operator
>>> b = map(operator.itemgetter(0), a)
>>> b
[1, 2]
The itemgetter
statement returns a function that returns the index of the element you specify. It's exactly the same as writing
>>> b = map(lambda x: x[0], a)
But I find that itemgetter
is a clearer and more explicit.
This is handy for making compact sort statements. For example,
>>> c = sorted(a, key=operator.itemgetter(0), reverse=True)
>>> c
[(2, u'def'), (1, u'abc')]
A small and short way of doing the same
HTML
<div class="image">
<p>
<h3>Heading 3</h3>
<h5>Heading 5</h5>
</p>
</div>
CSS
.image {
position: relative;
margin-bottom: 20px;
width: 100%;
height: 300px;
color: white;
background: url('../../Images/myImg.jpg') no-repeat;
background-size: 250px 250px;
}
I had the same issue. Solved it simply; I have (2) google accounts linked to my Play Store. It just so happens that I installed "an" app from "account B", and I was trying to rate it from "account A". So, switched accounts, and voilá.
This happened to me when I was trying to push the develop branch (I am using git flow). Someone had push updates to master. to fix it I did:
git co master
git pull
Which fetched those changes. Then,
git co develop
git pull
Which didn't do anything. I think the develop branch already pushed despite the error message. Everything is up to date now and no errors.
In windows OS, you can open command prompt, change directory to your project directory.
Example,
My project directory
E:\xampp\htdocs\my_project
You can type into your Command prompt like this (hit enter each line):
E:
cd xampp\htdocs\my_project
Then you can type,
copy .env.example .env
If you are using Linux, you can type cp, instead of copy
I managed to install a Python3 kernel besides the Python2. Here is the way I did it:
The latest working link can be found here.
The actual code is:
! mkdir -p ~/.ipython/kernels/python3
%%file ~/.ipython/kernels/python3/kernel.json
{
"display_name": "IPython (Python 3)",
"language": "python",
"argv": [
"python3",
"-c", "from IPython.kernel.zmq.kernelapp import main; main()",
"-f", "{connection_file}"
],
"codemirror_mode": {
"version": 2,
"name": "ipython"
}
}
I get this problem caused for a package that don't update correctly with wildcards, I use directly the last version and it works finally.
"l3/cas-bundle": "~1.0" -------> "l3/cas-bundle": "1.1.13"
It was already posted but here it is with PDO (same query)...
$connection = new PDO ( "mysql:host=host_db; dbname=name_db", user_db, pass_db );
if ($connection->query ("DESCRIBE table_name" )) {
echo "exist";
} else {
echo "doesn't exist";
}
Works like a charm for me....
And here's another approach (i think it is slower)...
if ($connection->query ( "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'db_name' AND table_name ='tbl_name'" )->fetch ()) {
echo "exist";
} else {
echo "doesn't exist";
}
You can also play with this query:
SHOW TABLE STATUS FROM db_name LIKE 'tbl_name'
I think this was suggested to use in the mysql page.
You want to use:
git checkout --ours foo/bar.java
git add foo/bar.java
If you rebase a branch feature_x
against main
(i.e. running git rebase main
while on branch feature_x
), during rebasing ours
refers to main
and theirs
to feature_x
.
As pointed out in the git-rebase docs:
Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.
For further details read this thread.
The way i usually have my hierarchy of folder-
I've created the tiniest code to do exactly that. It's not only for counting but for any task that needs to run in a given time. (let's say, do something for 5 seconds):
var step = function(t, elapsed){
// easing
t = t*t*t;
// calculate new value
var value = 300 * t; // will count from 0 to 300
// limit value ("t" might be higher than "1")
if( t > 0.999 )
value = 300;
// print value (converts it to an integer)
someElement.innerHTML = value|0;
};
var done = function(){
console.log('done counting!');
};
// Do-in settings object
var settings = {
step : step,
duration : 3,
done : done,
fps : 24 // optional. Default is requestAnimationFrame
};
// initialize "Do-in" instance
var doin = new Doin(settings);
The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)
-Dlogging.config={file_location}\log4j2.xml
or this:
-Dlog4j.configurationFile={file_location}\log4j2.xml
The answers are correct but don't mention how to sync code between the public repo and the fork.
Here is the full workflow (we've done this before open sourcing React Native):
First, duplicate the repo as others said (details here):
Create a new repo (let's call it private-repo
) via the Github UI. Then:
git clone --bare https://github.com/exampleuser/public-repo.git
cd public-repo.git
git push --mirror https://github.com/yourname/private-repo.git
cd ..
rm -rf public-repo.git
Clone the private repo so you can work on it:
git clone https://github.com/yourname/private-repo.git
cd private-repo
make some changes
git commit
git push origin master
To pull new hotness from the public repo:
cd private-repo
git remote add public https://github.com/exampleuser/public-repo.git
git pull public master # Creates a merge commit
git push origin master
Awesome, your private repo now has the latest code from the public repo plus your changes.
Finally, to create a pull request private repo -> public repo:
Use the GitHub UI to create a fork of the public repo (the small "Fork" button at the top right of the public repo page). Then:
git clone https://github.com/yourname/the-fork.git
cd the-fork
git remote add private_repo_yourname https://github.com/yourname/private-repo.git
git checkout -b pull_request_yourname
git pull private_repo_yourname master
git push origin pull_request_yourname
Now you can create a pull request via the Github UI for public-repo, as described here.
Once project owners review your pull request, they can merge it.
Of course the whole process can be repeated (just leave out the steps where you add remotes).
I found one by Julian Bucknall on his blog here - http://www.boyet.com/Articles/PriorityQueueCSharp3.html
We modified it slightly so that low-priority items on the queue would eventually 'bubble-up' to the top over time, so they wouldn't suffer starvation.
You could programmatically add more -name
clauses, separated by -or
:
find Documents \( -name "*.py" -or -name "*.html" \)
Or, go for a simple loop instead:
for F in Documents/*.{py,html}; do ...something with each '$F'... ; done