Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below
intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);
intentClearCookies.setIntent(clearcookies);
intentClearCookies.setTitle(R.string.ClearCookies);
intentClearCookies.setEnabled(true);
launchPrefCat.addPreference(intentClearCookies);
And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.
public class ClearCookies extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
showDialog();
}
/**
* @throws NotFoundException
*/
private void showDialog() throws NotFoundException {
new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.ClearCookies))
.setMessage(
getResources().getString(R.string.ClearCookieQuestion))
.setIcon(
getResources().getDrawable(
android.R.drawable.ic_dialog_alert))
.setPositiveButton(
getResources().getString(R.string.PostiveYesButton),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
})
.setNegativeButton(
getResources().getString(R.string.NegativeNoButton),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
}).show();
}}
As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.
The answer that was mentioned in this post already several times I have adopted a little bit because I needed to search in only one table too:
(and also made input for the table name a bit more simpler)
ALTER PROC dbo.db_compare_SearchAllTables_sp
(
@SearchStr nvarchar(100),
@TableName nvarchar(256) = ''
)
AS
BEGIN
if PARSENAME(@TableName, 2) is null
set @TableName = 'dbo.' + QUOTENAME(@TableName, '"')
declare @results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @ColumnName nvarchar(128) = '', @SearchStr2 nvarchar(110)
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
IF @TableName <> ''
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO @results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' WITH (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
ELSE
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO @results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' WITH (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM @results
END
public class TestedClass {
public LoginContext login(String user, String password) {
LoginContext lc = new LoginContext("login", callbackHandler);
lc.doThis();
lc.doThat();
}
}
-- Test Class:
@RunWith(PowerMockRunner.class)
@PrepareForTest(TestedClass.class)
public class TestedClassTest {
@Test
public void testLogin() {
LoginContext lcMock = mock(LoginContext.class);
whenNew(LoginContext.class).withArguments(anyString(), anyString()).thenReturn(lcMock);
//comment: this is giving mock object ( lcMock )
TestedClass tc = new TestedClass();
tc.login ("something", "something else"); /// testing this method.
// test the login's logic
}
}
When calling the actual method tc.login ("something", "something else");
from the testLogin() {
- This LoginContext lc is set to null and throwing NPE while calling lc.doThis();
.init
/.fini
isn't deprecated. It's still part of the the ELF standard and I'd dare say it will be forever. Code in .init
/.fini
is run by the loader/runtime-linker when code is loaded/unloaded. I.e. on each ELF load (for example a shared library) code in .init
will be run. It's still possible to use that mechanism to achieve about the same thing as with __attribute__((constructor))/((destructor))
. It's old-school but it has some benefits.
.ctors
/.dtors
mechanism for example require support by system-rtl/loader/linker-script. This is far from certain to be available on all systems, for example deeply embedded systems where code executes on bare metal. I.e. even if __attribute__((constructor))/((destructor))
is supported by GCC, it's not certain it will run as it's up to the linker to organize it and to the loader (or in some cases, boot-code) to run it. To use .init
/.fini
instead, the easiest way is to use linker flags: -init & -fini (i.e. from GCC command line, syntax would be -Wl -init my_init -fini my_fini
).
On system supporting both methods, one possible benefit is that code in .init
is run before .ctors
and code in .fini
after .dtors
. If order is relevant that's at least one crude but easy way to distinguish between init/exit functions.
A major drawback is that you can't easily have more than one _init
and one _fini
function per each loadable module and would probably have to fragment code in more .so
than motivated. Another is that when using the linker method described above, one replaces the original _init and _fini
default functions (provided by crti.o
). This is where all sorts of initialization usually occur (on Linux this is where global variable assignment is initialized). A way around that is described here
Notice in the link above that a cascading to the original _init()
is not needed as it's still in place. The call
in the inline assembly however is x86-mnemonic and calling a function from assembly would look completely different for many other architectures (like ARM for example). I.e. code is not transparent.
.init
/.fini
and .ctors
/.detors
mechanisms are similar, but not quite. Code in .init
/.fini
runs "as is". I.e. you can have several functions in .init
/.fini
, but it is AFAIK syntactically difficult to put them there fully transparently in pure C without breaking up code in many small .so
files.
.ctors
/.dtors
are differently organized than .init
/.fini
. .ctors
/.dtors
sections are both just tables with pointers to functions, and the "caller" is a system-provided loop that calls each function indirectly. I.e. the loop-caller can be architecture specific, but as it's part of the system (if it exists at all i.e.) it doesn't matter.
The following snippet adds new function pointers to the .ctors
function array, principally the same way as __attribute__((constructor))
does (method can coexist with __attribute__((constructor)))
.
#define SECTION( S ) __attribute__ ((section ( S )))
void test(void) {
printf("Hello\n");
}
void (*funcptr)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;
One can also add the function pointers to a completely different self-invented section. A modified linker script and an additional function mimicking the loader .ctors
/.dtors
loop is needed in such case. But with it one can achieve better control over execution order, add in-argument and return code handling e.t.a. (In a C++ project for example, it would be useful if in need of something running before or after global constructors).
I'd prefer __attribute__((constructor))/((destructor))
where possible, it's a simple and elegant solution even it feels like cheating. For bare-metal coders like myself, this is just not always an option.
Some good reference in the book Linkers & loaders.
From python >= 3.5 onward, you can use **
, glob.iglob(path/**, recursive=True)
and it seems the most pythonic solution, i.e.:
import glob, os
for filename in glob.iglob('/pardadox-music/**', recursive=True):
if os.path.isfile(filename): # filter dirs
print(filename)
Output:
/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...
Notes:
1 - glob.iglob
glob.iglob(pathname, recursive=False)
Return an iterator which yields the same values as
glob()
without actually storing them all simultaneously.
2 - If recursive is True
, the pattern '**'
will match any files and
zero or more directories
and subdirectories
.
3 - If the directory contains files starting with .
they won’t be matched by default. For example, consider a directory containing card.gif
and .card.gif
:
>>> import glob
>>> glob.glob('*.gif') ['card.gif']
>>> glob.glob('.c*')['.card.gif']
4 - You can also use rglob(pattern)
,
which is the same as calling glob()
with **/
added in front of the given relative pattern.
To solve such kind of problems I created library in swift which is called Atributika.
let str = "<r>first</r><g>second</g><b>third</b>".style(tags:
Style("r").foregroundColor(.red),
Style("g").foregroundColor(.green),
Style("b").foregroundColor(.blue)).attributedString
label.attributedText = str
You can find it here https://github.com/psharanda/Atributika
In Spark 2.0 (I didn't tested with earlier versions). Simply:
print myRDD.take(n)
Where n is the number of lines and myRDD is wc in your case.
OMG I Got A Quick File Move Command form CMD
1)Command will move All Files and Sub Folders into another location in 1 second .
check command
C:\user>move "your source path " "your destination path"
Hint : For move all Files and Sub folders
C:\user>move "f:\wamp\www" "f:\wapm_3.2\www\old Projects"
you can see that it's before i try some other code that was not working due to more than 1 files and folder was there. when i try to execute code that is under line by red color then all folder move in 1 second.
now check this image. here Total 6.7GB data moved in 1 second... you can check date of post and move as well as Folder name.
i will soon make a windows app that will do same..
If you just have the xml
file of the color scheme you can:
Go to Preferences
-> Editor
-> Color and Fonts
and use the Import
button.
The solution is to put the modal directly under the body
tag. If that is not possible for some reason then just add a overflow: visible
property to the tag enclosing the modal, or use the following code:
<script>
$(document).on('show.bs.modal', '.modal', function () {
$('.div-wrapper-for-modal').css('overflow', 'visible');
});
$(document).on('hide.bs.modal', '.modal', function () {
$('.div-wrapper-for-modal').css('overflow', 'auto');
});
</script>
<div class="div-wrapper-for-modal">
<div class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<a href="#" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>
</div>
I suggest opening a python
shell in terminal (in the python version you are interested), importing the library, and getting its __version__
attribute.
>>> import statlib
>>> statlib.__version__
>>> import construct
>>> contruct.__version__
Note 1: We must regard the python version. If we have installed different versions of python, we have to open the terminal in the python version we are interested in. For example, opening the terminal with python3.8
can (surely will) give a different version of a library than opening with python3.5
or python2.7
.
Note 2: We avoid using the print
function, because its behavior depends on python2 or python3. We do not need it, the terminal will show the value of the expression.
I recommended an experimental new attribute CSS I tested on latest browser and it's good:
image-rendering: optimizeSpeed; /* */
image-rendering: -moz-crisp-edges; /* Firefox */
image-rendering: -o-crisp-edges; /* Opera */
image-rendering: -webkit-optimize-contrast; /* Chrome (and Safari) */
image-rendering: optimize-contrast; /* CSS3 Proposed */
-ms-interpolation-mode: nearest-neighbor; /* IE8+ */
With this the browser will know the algorithm for rendering
do adb pull \sdcard\log.txt C:Users\admin\Desktop
Take a look at your client/package.json. You have to have these scripts
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
thanks to Jim Petkus that did gave me a wonderful answer . but i was trying to solve my own script not to changing it to another plugin . My main focus was not using an independent plugin and do what i wanted just by using the jquery core !
and guess what i did find the problem .
var title = $("em").attr("title");
$("div").text(title);
this is what i add to my script and the blew codes to my html part :
<td> <em title=\"$weight\">$weight</em></td>
and found each row $weight value
thanks again to Jim Petkus
I find this lecture very valuable https://vimeo.com/190275665, in point 3 it summarizes these generators and also gives some performance analysis and guideline one when you use each one.
The first one should work:
> "a\nb".split("\n");
[ 'a', 'b' ]
> var a = "test.js\nagain.js"
undefined
> a.split("\n");
[ 'test.js', 'again.js' ]
Compiles under >=Swift 3. This example contains most of the syntax that we need.
QoS - new quality of service syntax
weak self
- to disrupt retain cycles
if self is not available, do nothing
async global utility queue
- for network query, does not wait for the result, it is a concurrent queue, the block (usually) does not wait when started. Exception for a concurrent queue could be, when its task limit has been previously reached, then the queue temporarily turns into a serial queue and waits until some previous task in that queue completes.
async main queue
- for touching the UI, the block does not wait for the result, but waits for its slot at the start. The main queue is a serial queue.
Of course, you need to add some error checking to this...
DispatchQueue.global(qos: .utility).async { [weak self] () -> Void in
guard let strongSelf = self else { return }
strongSelf.flickrPhoto.loadLargeImage { loadedFlickrPhoto, error in
if error != nil {
print("error:\(error)")
} else {
DispatchQueue.main.async { () -> Void in
activityIndicator.removeFromSuperview()
strongSelf.imageView.image = strongSelf.flickrPhoto.largeImage
}
}
}
}
enum NumberError: Error {
case NegativeNumber(number: Int)
case ZeroNumber
case OddNumber(number: Int)
}
extension NumberError: CustomStringConvertible {
var description: String {
switch self {
case .NegativeNumber(let number):
return "Negative number \(number) is Passed."
case .OddNumber(let number):
return "Odd number \(number) is Passed."
case .ZeroNumber:
return "Zero is Passed."
}
}
}
func validateEvenNumber(_ number: Int) throws ->Int {
if number == 0 {
throw NumberError.ZeroNumber
} else if number < 0 {
throw NumberError.NegativeNumber(number: number)
} else if number % 2 == 1 {
throw NumberError.OddNumber(number: number)
}
return number
}
Now Validate Number :
do {
let number = try validateEvenNumber(0)
print("Valid Even Number: \(number)")
} catch let error as NumberError {
print(error.description)
}
Gdb commands:
i r <register_name>
: print a single register, e.g i r rax
, i r eax
i r <register_name_1> <register_name_2> ...
: print multiple registers, e.g i r rdi rsi
,i r
: print all register except floating point & vector register (xmm, ymm, zmm).i r a
: print all register, include floating point & vector register (xmm, ymm, zmm).i r f
: print all FPU floating registers (st0-7
and a few other f*
) Other register groups besides a
(all
) and f
(float
) can be found with:
maint print reggroups
as documented at: https://sourceware.org/gdb/current/onlinedocs/gdb/Registers.html#Registers
Tips:
xmm0
~ xmm15
, are 128 bits, almost every modern machine has it, they are released in 1999.ymm0
~ ymm15
, are 256 bits, new machine usually have it, they are released in 2011.zmm0
~ zmm31
, are 512 bits, normal pc probably don't have it (as the year 2016), they are released in 2013, and mainly used in servers so far.You can get the multiple element by id by identifying what element it is. For example
<div id='id'></div>
<div id='id'></div>
<div id='id'></div>
I assume if you are using jQuery you can select all them all by
$("div#id")
. This will get you array of elements you loop them based on your logic.
If you want to remove multiple object from a list. There are various ways to delete an object from a list
Try this code. a is list with all object, b is list object you want to remove.
example :
a = [1,2,3,4,5,6]
b = [2,3]
for i in b:
if i in a:
a.remove(i)
print(a)
the output is [1,4,5,6]
I hope, it will work for you
The doxypy input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well.
One way would be to just escape the quotes properly:
<input type="button" value="click" id="mybtn"
onclick="myfunction('/myController/myAction',
'myfuncionOnOK(\'/myController2/myAction2\',
\'myParameter2\');',
'myfuncionOnCancel(\'/myController3/myAction3\',
\'myParameter3\');');">
In this case, though, I think a better way to handle this would be to wrap the two handlers in anonymous functions:
<input type="button" value="click" id="mybtn"
onclick="myfunction('/myController/myAction',
function() { myfuncionOnOK('/myController2/myAction2',
'myParameter2'); },
function() { myfuncionOnCancel('/myController3/myAction3',
'myParameter3'); });">
And then, you could call them from within myfunction
like this:
function myfunction(url, onOK, onCancel)
{
// Do whatever myfunction would normally do...
if (okClicked)
{
onOK();
}
if (cancelClicked)
{
onCancel();
}
}
That's probably not what myfunction
would actually look like, but you get the general idea. The point is, if you use anonymous functions, you have a lot more flexibility, and you keep your code a lot cleaner as well.
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
You could write something like that :
public static bool HasMethod(this object objectToCheck, string methodName)
{
var type = objectToCheck.GetType();
return type.GetMethod(methodName) != null;
}
Edit : you can even do an extension method and use it like this
myObject.HasMethod("SomeMethod");
I know this may be obvious for most people who use RegEx frequently, but in case any readers are new to RegEx, I thought I should point out an observation I made that was helpful for one of my projects.
In a previous answer from @kennytm:
^\d{5}(?:[-\s]\d{4})?$
…? = The pattern before it is optional (for condition 1)
If you want to allow both standard 5 digit and +4 zip codes, this is a great example.
To match only zip codes in the US 'Zip + 4' format as I needed to do (conditions 2 and 3 only), simply remove the last ?
so it will always match the last 5 character group.
A useful tool I recommend for tinkering with RegEx is linked below:
I use this tool frequently when I find RegEx that does something similar to what I need, but could be tailored a bit better. It also has a nifty RegEx reference menu and informative interface that keeps you aware of how your changes impact the matches for the sample text you entered.
If I got anything wrong or missed an important piece of information, please correct me.
You can use
grep 'string1' filename | grep 'string2'
Or
grep 'string1.*string2\|string2.*string1' filename
Try putting the e.Row.Cells[0].Visible = false;
inside the RowCreated
event of your grid.
protected void bla_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false; // hides the first column
}
This way it auto-hides the whole column.
You don't have access to the generated columns through grid.Columns[i]
in your gridview's DataBound
event.
I just modified your code. It works fine in my system. See if this helps
class round{
public static void main(String args[]){
double a = 123.13698;
double roundOff = Math.round(a*100)/100.00;
System.out.println(roundOff);
}
}
Then create your object with that index.
Note: this will still have same issues other answers have described with respect to enforcing the type of each item - but that's often exactly what you want.
You can make the generic type parameter whatever you need : ObjectIndexer< Dog | Cat>
// this should be global somewhere, or you may already be
// using a library that provides such a type
export interface ObjectIndexer<T> {
[id: string]: T;
}
interface ISomeObject extends ObjectIndexer<string>
{
firstKey: string;
secondKey: string;
thirdKey: string;
}
let someObject: ISomeObject = {
firstKey: 'firstValue',
secondKey: 'secondValue',
thirdKey: 'thirdValue'
};
let key: string = 'secondKey';
let secondValue: string = someObject[key];
You can even use this in a generic constraint when defining a generic type:
export class SmartFormGroup<T extends IndexableObject<any>> extends FormGroup
Then T
inside the class can be indexed :-)
Without any problems, I imported directly from the command line.
mysql -uroot -hURLServer -p DBName< filename.sql
Looks like Xcode 6.0 has moved this location once again, at least for iOS 8 simulators.
~/Library/Developer/CoreSimulator/Devices/[DeviceID]/data/Containers/Data/Application/[AppID]
Global working tested solution.
getSupportFragmentManager()
keeps the null reference some times and View pager does not create new since it find reference to same fragment. So to over come this use getChildFragmentManager()
solves problem in simple way.
Don't do this:
new PagerAdapter(getSupportFragmentManager(), fragments);
Do this:
new PagerAdapter(getChildFragmentManager() , fragments);
This is detailed with a reasonable amount of detail by Guido himself in his blog post Method Resolution Order (including two earlier attempts).
In your example, Third()
will call First.__init__
. Python looks for each attribute in the class's parents as they are listed left to right. In this case, we are looking for __init__
. So, if you define
class Third(First, Second):
...
Python will start by looking at First
, and, if First
doesn't have the attribute, then it will look at Second
.
This situation becomes more complex when inheritance starts crossing paths (for example if First
inherited from Second
). Read the link above for more details, but, in a nutshell, Python will try to maintain the order in which each class appears on the inheritance list, starting with the child class itself.
So, for instance, if you had:
class First(object):
def __init__(self):
print "first"
class Second(First):
def __init__(self):
print "second"
class Third(First):
def __init__(self):
print "third"
class Fourth(Second, Third):
def __init__(self):
super(Fourth, self).__init__()
print "that's it"
the MRO would be [Fourth, Second, Third, First].
By the way: if Python cannot find a coherent method resolution order, it'll raise an exception, instead of falling back to behavior which might surprise the user.
Edited to add an example of an ambiguous MRO:
class First(object):
def __init__(self):
print "first"
class Second(First):
def __init__(self):
print "second"
class Third(First, Second):
def __init__(self):
print "third"
Should Third
's MRO be [First, Second]
or [Second, First]
? There's no obvious expectation, and Python will raise an error:
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution order (MRO) for bases Second, First
Edit: I see several people arguing that the examples above lack super()
calls, so let me explain: The point of the examples is to show how the MRO is constructed. They are not intended to print "first\nsecond\third" or whatever. You can – and should, of course, play around with the example, add super()
calls, see what happens, and gain a deeper understanding of Python's inheritance model. But my goal here is to keep it simple and show how the MRO is built. And it is built as I explained:
>>> Fourth.__mro__
(<class '__main__.Fourth'>,
<class '__main__.Second'>, <class '__main__.Third'>,
<class '__main__.First'>,
<type 'object'>)
To count all lines use:
$ wc -l file
To filter and count only lines with pattern use:
$ grep -w "pattern" -c file
Or use -v to invert match:
$ grep -w "pattern" -c -v file
See the grep man page to take a look at the -e,-i and -x args...
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
See the following methods:
~ : Changes the case of current character
guu : Change current line from upper to lower.
gUU : Change current LINE from lower to upper.
guw : Change to end of current WORD from upper to lower.
guaw : Change all of current WORD to lower.
gUw : Change to end of current WORD from lower to upper.
gUaw : Change all of current WORD to upper.
g~~ : Invert case to entire line
g~w : Invert case to current WORD
guG : Change to lowercase until the end of document.
This fixes the problem on both Safari and Chrome
if(navigator.userAgent.toLowerCase().indexOf("chrome") >= 0 || navigator.userAgent.toLowerCase().indexOf("safari") >= 0){
window.setInterval(function(){
$('input:-webkit-autofill').each(function(){
var clone = $(this).clone(true, true);
$(this).after(clone).remove();
});
}, 20);
}
These are all close to the right answer, but I wouldn't say any solve the problem while remaining most readable to others reading your code. I'd say that answer is a combination of BrenBarn's Answer and tuomasttik's comment below that answer. BrenBarn's answer utilizes isspace
builtin, but does not support removing empty strings, as OP requested, and I would tend to attribute that as the standard use case of replacing strings with null.
I rewrote it with .apply
, so you can call it on a pd.Series
or pd.DataFrame
.
Python 3:
To replace empty strings or strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, str) and (x.isspace() or not x) else x)
To replace strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, str) and x.isspace() else x)
To use this in Python 2, you'll need to replace str
with basestring
.
Python 2:
To replace empty strings or strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, basestring) and (x.isspace() or not x) else x)
To replace strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x)
You need to change the import of your class:
import org.apache.commons.codec.binary.Base64;
And then change your class to use the Base64 class.
Here's some example code:
byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
Then read why you shouldn't use sun.* packages.
You can now use java.util.Base64
with Java 8. First, import it as you normally do:
import java.util.Base64;
Then use the Base64 static methods as follows:
byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
If you directly want to encode string and get the result as encoded string, you can use this:
String encodeBytes = Base64.getEncoder().encodeToString((userName + ":" + password).getBytes());
See Java documentation for Base64 for more.
You don't want a string, you really want a JS map of key value pairs. E.g., change:
data: myDataVar.toString(),
with:
var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: myKeyVals,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.
UPDATE: Code fixed.
There are 2 scenario's where Bash performance is at least equal I believe:
That said, I usually don't really concern myself with performance of the scripting language itself. If performance is a real issue you don't script but program (possibly in Python).
You can use git rebase --interactive
, using the edit
command on the commit you want to amend.
@JigarJoshi it's the good answer, and of course also @Tim recommendation to use .joda-time.
I only want to add more possibilities to subtract days from a java.util.Date
.
One possibility is to use apache-commons-lang. You can do it using DateUtils
as follows:
Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
Of course add the commons-lang
dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang
it's a good choice. There is also convenient methods to addYears
,addMonths
,addWeeks
and so on, take a look at the api here.
Another possibility is to take advantage of new LocalDate
from Java 8 using minusDays(long days)
method:
LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);
To be totally exhaustive, things are different if you're using a JPA 1.0 or a JPA 2.0 implementation.
With JPA 1.0, you'd have to use EntityManager#getDelegate()
. But keep in mind that the result of this method is implementation specific i.e. non portable from application server using Hibernate to the other. For example with JBoss you would do:
org.hibernate.Session session = (Session) manager.getDelegate();
But with GlassFish, you'd have to do:
org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession();
I agree, that's horrible, and the spec is to blame here (not clear enough).
With JPA 2.0, there is a new (and much better) EntityManager#unwrap(Class<T>)
method that is to be preferred over EntityManager#getDelegate()
for new applications.
So with Hibernate as JPA 2.0 implementation (see 3.15. Native Hibernate API), you would do:
Session session = entityManager.unwrap(Session.class);
You can use tools own browser (Firefox, IE, Chrome...) to debug your JavaScript.
As for resizing, Firefox/Chrome has own resources accessible via Ctrl + Shift + I OR F12. Going tab "style editor" and clicking "adaptive/responsive design" icon.
Old Firefox versions
New Firefox/Firebug
Chrome
*Another way is to install an addon like "Web Developer"
Case Insensitive Substring Example
This is an extension of Eugene's answer, which converts the strings to lower case before checking for the substring:
if (index(lc($str), lc($substr)) != -1) {
print "$str contains $substr\n";
}
In C# I did:
alert('Text\\n\\nSome more text');
It display as:
Text
Some more text
I had a problem like this whereby I had specified the width of my Window, but had the height set to Auto
. The child DockPanel
had it's VerticalAlignment
set to Top and the Window had it's VerticalContentAlignment set to Top, yet the Window would still be much taller than the contents.
Using Snoop, I discovered that the ContentPresenter
within the Window (part of the Window, not something I had put there) has it's VerticalAlignment
set to Stretch
and can't be changed without retemplating the entire Window!
After a lot of frustration, I discovered the SizeToContent
property - you can use this to specify whether you want the Window to size vertically, horizontally or both, according to the size of the contents - everything is sizing nicely now, I just can't believe it took me so long to find that property!
Try this one
where datediff(month, datetime_column, getdate()) <= 6
To exclude or filter out future dates
where datediff(month, datetime_column, getdate()) between 0 and 6
This part datediff(month, datetime_column, getdate())
will get the month difference in number of current date and Datetime_Column and will return Rows like:
Result
1
2
3
4
5
6
7
8
9
10
This is Our final condition to get last 6 months data
where result <= 6
Make sure no other apache servers are running as it generates an error when you try to access it on the browser even with a different port. Go to Finder and below Device you will usually see the lampp icon. You can also open the htdocs from any of the ide or code editor by opening files or project once you locate the lampp icon. Make sure you mount the stack.
This worked for me as well:
Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"
It seems that in PHP 7.1, a Warning will be emitted if a non-numeric value is encountered. See this link.
Here is the relevant portion that pertains to the Warning notice you are getting:
New E_WARNING and E_NOTICE errors have been introduced when invalid strings are coerced using operators expecting numbers or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.
I'm guessing either $item['quantity'] or $product['price'] does not contain a numeric value, so make sure that they do before trying to multiply them. Maybe use some sort of conditional before calculating the $sub_total, like so:
<?php
if (is_numeric($item['quantity']) && is_numeric($product['price'])) {
$sub_total += ($item['quantity'] * $product['price']);
} else {
// do some error handling...
}
First off, when I went into cmd and typed "netsh wlan show drivers", I had a NO for hosted network support too. Doesn't matter, you can still do it. Just not in cmd.
I think this problem happens because they changed the way hosted networks work in windows 10. Don't use command line.
Just go on your pc to settings>Network>Mobile Hotspot and you should see all the necessary settings there. Turn it on, set up your network.
If it's still not working, go to Control panel>Network and Internet>Network and Sharing Center>Change Adapter Options> and then click on the properties of the network adapter that you want to share. Go to the sharing tab, and share that internet connection, selecting the name of the adapter you want to use to share it with.
I think the touch command is the right answer e.g. do something like
touch --date="`date`" aclocal.m4 Makefile.am configure Makefile.in
before [./configure && make].
Sidebar I: Otherwise, I agree with @kaz: adding dependencies for aclocal.m4 and/or configure and/or Makefile.am and/or Makefile.in makes assumptions about the target system that may be invalid. Specifically, those assumptions are
1) that all target systems have autotools,
2) that all target systems have the same version of autotools (e.g. automake.1.15 in this case).
3) that if either (1) or (2) are not true for any user, that the user is extracting the package from a maintainer-produced TAR or ZIP format that maintains timestamps of the relevant files, in which case all autotool/configure/Makefile.am/Makefile.in dependencies in the configure-generated Makefile will be satisfied before the make command is issued.
The second assumption fails on many Mac systems because automake.1.14 is the "latest" for OSX (at least that is what I see in MacPorts, and apparently the same is true for brew).
The third assumption fails spectacularly in a world with Github. This failure is an example of an "everyone thinks they are normative" mindset; specifically, the maintainers, who are the only class of users that should need to edit Makefile.am, have now put everyone into that class.
Perhaps there is an option in autowhatever that keeps these dependencies from being added to Makefile.in and/or Makefile.
Sidebar II [Why @kaz is right]: of course it is obvious, to me and other cognoscenti, to simply try a sequence of [touch] commands to fool the configure-created Makefile from re-running configure and the autotools. But that is not the point of configure; the point of configure is to ensure as many users on as many different systems as as possible can simply do [./configure && make] and move on; most users are not interested in "shaving the yak" e.g. debugging faulty assumptions of the autotools developers.
Sidebar III: it could be argued that ./configure, now that autotools adds these dependencies, is the wrong build tool to use with Github-distributed packages.
Sidebar IV: perhaps configure-based Github repos should put the necessary touch command into their readme, e.g. https://github.com/drbitboy/Tycho2_SQLite_RTree.
You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.
Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.
This was a very handy page as I have a requirement to DELETE records from a mySQL table where the expiry date is < Today.
I am on a shared host and CRON did not like the suggestion AndrewKDay. it also said (and I agree) that exposing the password in this way could be insecure.
I then tried turning Events ON in phpMyAdmin but again being on a shared host this was a no no. Sorry fancyPants.
So I turned to embedding the SQL script in a PHP file. I used the example [here][1]
[1]: https://www.w3schools.com/php/php_mysql_create_table.asp stored it in a sub folder somewhere safe and added an empty index.php for good measure. I was then able to test that this PHP file (and my SQL script) was working from the browser URL line.
All good so far. On to CRON. Following the above example almost worked. I ended up calling PHP before the path for my *.php file. Otherwise CRON didn't know what to do with the file.
my cron is set to run once per day and looks like this, modified for security.
00 * * * * php mywebsiteurl.com/wp-content/themes/ForteChildTheme/php/DeleteExpiredAssessment.php
For the final testing with CRON I initially set it to run each minute and had email alerts turned on. This quickly confirmed that it was running as planned and I changed it back to once per day.
Hope this helps.
in continuation to @ Cuong Le's answer , my approach to prevent replay attack would be
// Encrypt the Unix Time at Client side using the shared private key(or user's password)
// Send it as part of request header to server(WEB API)
// Decrypt the Unix Time at Server(WEB API) using the shared private key(or user's password)
// Check the time difference between the Client's Unix Time and Server's Unix Time, should not be greater than x sec
// if User ID/Hash Password are correct and the decrypted UnixTime is within x sec of server time then it is a valid request
You need to use an iframe
.
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#content").attr("src","http://vnexpress.net");
})
</script>
</head>
<body>
<iframe id="content" src="about:blank"></iframe>
</body>
</html
You can add a hook function to intercept all calls to addEventHandler
. The hook will push the handler to a list that can be used for cleanup. For example,
if (EventTarget.prototype.original_addEventListener == null) {
EventTarget.prototype.original_addEventListener = EventTarget.prototype.addEventListener;
function addEventListener_hook(typ, fn, opt) {
console.log('--- add event listener',this.nodeName,typ);
this.all_handlers = this.all_handlers || [];
this.all_handlers.push({typ,fn,opt});
this.original_addEventListener(typ, fn, opt);
}
EventTarget.prototype.addEventListener = addEventListener_hook;
}
You should insert this code near the top of your main web page (e.g. index.html
). During cleanup, you can loop thru all_handlers, and call removeEventHandler for each. Don't worry about calling removeEventHandler multiple times with the same function. It is harmless.
For example,
function cleanup(elem) {
for (let t in elem) if (t.startsWith('on') && elem[t] != null) {
elem[t] = null;
console.log('cleanup removed listener from '+elem.nodeName,t);
}
for (let t of elem.all_handlers || []) {
elem.removeEventListener(t.typ, t.fn, t.opt);
console.log('cleanup removed listener from '+elem.nodeName,t.typ);
}
}
Note: for IE use Element instead of EventTarget, and change => to function, and various other things.
if using avast go for virus chest,will find adb,restore it by clicking right button..thats all,perfectly works
<?php
header('Location: B.php');
exit();
?>
Suppose we want to route from A.php file to B.php than we have to take help of <button>
or <a>
. Lets see an example
<?php
if(isset($_GET['go_to_page_b'])) {
header('Location: B.php');
exit();
}
?>
<p>I am page A</p>
<button name='go_to_page_b'>Page B</button>
B.php
<p> I am Page B</p>
overflow-x: scroll;
overflow-y: hidden;
EDIT:
It works for me:
<div style='overflow-x:scroll;overflow-y:hidden;width:250px;height:200px'>
<div style='width:400px;height:250px'></div>
</div>
Open it in a hex editor and make sure that the first three bytes are a UTF8 BOM (EF BB BF
)
node-supervisor is awesome
usage to restart on save:
npm install supervisor -g supervisor app.js
by isaacs - http://github.com/isaacs/node-supervisor
[DataType(DataType.PhoneNumber)]
does not come with any validation logic out of the box.
According to the docs:
When you apply the
DataTypeAttribute
attribute to a data field you must do the following:
- Issue validation errors as appropriate.
The [Phone]
Attribute inherits from [DataType]
and was introduced in .NET Framework 4.5+ and is in .NET Core which does provide it's own flavor of validation logic. So you can use like this:
[Phone()]
public string PhoneNumber { get; set; }
However, the out-of-the-box validation for Phone numbers is pretty permissive, so you might find yourself wanting to inherit from DataType and implement your own IsValid
method or, as others have suggested here, use a regular expression & RegexValidator
to constrain input.
Note: Use caution with Regex against unconstrained input per the best practices as .NET has made the pivot away from regular expressions in their own internal validation logic for phone numbers
HTTP and HTTPS:
const getScript = (url) => {
return new Promise((resolve, reject) => {
const http = require('http'),
https = require('https');
let client = http;
if (url.toString().indexOf("https") === 0) {
client = https;
}
client.get(url, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
resolve(data);
});
}).on("error", (err) => {
reject(err);
});
});
};
(async (url) => {
console.log(await getScript(url));
})('https://sidanmor.com/');
You can't determine the amount of data in a stream without reading it; you can, however, ask for the size of a file:
http://java.sun.com/javase/6/docs/api/java/io/File.html#length()
If that isn't possible, you can write the bytes you read from the input stream to a ByteArrayOutputStream which will grow as required.
@echo off
cls
MD %homedrive%\TEMPBBDVD\
CLS
TIMEOUT /T 1 >NUL
CLS
systeminfo >%homedrive%\TEMPBBDVD\info.txt
cls
timeout /t 3 >nul
cls
find "x64-based PC" %homedrive%\TEMPBBDVD\info.txt >nul
if %errorlevel% equ 1 goto 32bitsok
goto 64bitsok
cls
:commandlineerror
cls
echo error, command failed or you not are using windows OS.
pause >nul
cls
exit
:64bitsok
cls
echo done, system of 64 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit
:32bitsok
cls
echo done, system of 32 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit
Swift 4 update comparing with swift 3
Swift 4 removes the need for a characters array on String. This means that you can directly call count
on a string without getting characters array first.
"hello".count // 5
Whereas in swift 3, you will have to get characters array and then count element in that array. Note that this following method is still available in swift 4.0 as you can still call characters
to access characters array of the given string
"hello".characters.count // 5
Swift 4.0 also adopts Unicode 9 and it can now interprets grapheme clusters. For example, counting on an emoji will give you 1 while in swift 3.0, you may get counts greater than 1.
"".count // Swift 4.0 prints 1, Swift 3.0 prints 2
"?????".count // Swift 4.0 prints 1, Swift 3.0 prints 4
You can check if your string starts with http or https using the small function below.
function has_prefix($string, $prefix) {
return substr($string, 0, strlen($prefix)) == $prefix;
}
$url = 'http://www.google.com';
echo 'the url ' . (has_prefix($url, 'http://') ? 'does' : 'does not') . ' start with http://';
echo 'the url ' . (has_prefix($url, 'https://') ? 'does' : 'does not') . ' start with https://';
I see that you tagged bash, but Perl would also be a good way to do this:
perl -p -e '`chmod 755 $_`' file.txt
You could also apply a regex to make sure you're getting the right files, e.g. to only process .txt files:
perl -p -e 'if(/\.txt$/) `chmod 755 $_`' file.txt
To "preview" what's happening, just replace the backticks with double quotes and prepend print
:
perl -p -e 'if(/\.txt$/) print "chmod 755 $_"' file.txt
You could make the process faster, if you use gradle from command line. There is a lot of optimization to do for the IDE developers. But it is just an early version.
For more information read this discussion on g+ with some of the devs.
css:
img.modal-img {
cursor: pointer;
transition: 0.3s;
}
img.modal-img:hover {
opacity: 0.7;
}
.img-modal {
display: none;
position: fixed;
z-index: 99999;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.9);
}
.img-modal img {
margin: auto;
display: block;
width: 80%;
max-width: 700%;
}
.img-modal div {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
height: 150px;
}
.img-modal img, .img-modal div {
animation: zoom 0.6s;
}
.img-modal span {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
cursor: pointer;
}
@media only screen and (max-width: 700px) {
.img-modal img {
width: 100%;
}
}
@keyframes zoom {
0% {
transform: scale(0);
}
100% {
transform: scale(1);
}
}
Javascript:
$('img.modal-img').each(function() {_x000D_
var modal = $('<div class="img-modal"><span>×</span><img /><div></div></div>');_x000D_
modal.find('img').attr('src', $(this).attr('src'));_x000D_
if($(this).attr('alt'))_x000D_
modal.find('div').text($(this).attr('alt'));_x000D_
$(this).after(modal);_x000D_
modal = $(this).next();_x000D_
$(this).click(function(event) {_x000D_
modal.show(300);_x000D_
modal.find('span').show(0.3);_x000D_
});_x000D_
modal.find('span').click(function(event) {_x000D_
modal.hide(300);_x000D_
});_x000D_
});_x000D_
$(document).keyup(function(event) {_x000D_
if(event.which==27)_x000D_
$('.img-modal>span').click();_x000D_
});
_x000D_
img.modal-img {_x000D_
cursor: pointer;_x000D_
transition: 0.3s;_x000D_
}_x000D_
img.modal-img:hover {_x000D_
opacity: 0.7;_x000D_
}_x000D_
.img-modal {_x000D_
display: none;_x000D_
position: fixed;_x000D_
z-index: 99999;_x000D_
padding-top: 100px;_x000D_
left: 0;_x000D_
top: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
overflow: auto;_x000D_
background-color: rgba(0,0,0,0.9);_x000D_
}_x000D_
.img-modal img {_x000D_
margin: auto;_x000D_
display: block;_x000D_
width: 80%;_x000D_
max-width: 700%;_x000D_
}_x000D_
.img-modal div {_x000D_
margin: auto;_x000D_
display: block;_x000D_
width: 80%;_x000D_
max-width: 700px;_x000D_
text-align: center;_x000D_
color: #ccc;_x000D_
padding: 10px 0;_x000D_
height: 150px;_x000D_
}_x000D_
.img-modal img, .img-modal div {_x000D_
animation: zoom 0.6s;_x000D_
}_x000D_
.img-modal span {_x000D_
position: absolute;_x000D_
top: 15px;_x000D_
right: 35px;_x000D_
color: #f1f1f1;_x000D_
font-size: 40px;_x000D_
font-weight: bold;_x000D_
transition: 0.3s;_x000D_
cursor: pointer;_x000D_
}_x000D_
@media only screen and (max-width: 700px) {_x000D_
.img-modal img {_x000D_
width: 100%;_x000D_
}_x000D_
}_x000D_
@keyframes zoom {_x000D_
0% {_x000D_
transform: scale(0);_x000D_
}_x000D_
100% {_x000D_
transform: scale(1);_x000D_
}_x000D_
}_x000D_
Javascript:_x000D_
_x000D_
$('img.modal-img').each(function() {_x000D_
var modal = $('<div class="img-modal"><span>×</span><img /><div></div></div>');_x000D_
modal.find('img').attr('src', $(this).attr('src'));_x000D_
if($(this).attr('alt'))_x000D_
modal.find('div').text($(this).attr('alt'));_x000D_
$(this).after(modal);_x000D_
modal = $(this).next();_x000D_
$(this).click(function(event) {_x000D_
modal.show(300);_x000D_
modal.find('span').show(0.3);_x000D_
});_x000D_
modal.find('span').click(function(event) {_x000D_
modal.hide(300);_x000D_
});_x000D_
});_x000D_
$(document).keyup(function(event) {_x000D_
if(event.which==27)_x000D_
$('.img-modal>span').click();_x000D_
});_x000D_
_x000D_
HTML:
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<img src="http://www.google.com/favicon.ico" class="modal-img">
_x000D_
2019's answer as this is still actively seen today
You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.
original hack from 2015 that still works in some situations
You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.
If you cannot pull it out of the div for some reason, you should change the position style with this css:
.full-width-div {
position: absolute;
width: 100%;
left: 0;
}
Instead of absolute, you could also use fixed, but then it will not move as you scroll.
For static text:
For long text that needs to be updated once in a while:
For a number (formatted 00.0):
In your onDraw event only update the value variable sent to the shader.
precision highp float;
precision highp sampler2D;
uniform float uTime;
uniform float uValue;
uniform vec3 iResolution;
varying vec4 v_Color;
varying vec2 vTextureCoord;
uniform sampler2D s_texture;
void main() {
vec4 fragColor = vec4(1.0, 0.5, 0.2, 0.5);
vec2 uv = vTextureCoord;
float devisor = 10.75;
float digit;
float i;
float uCol;
float uRow;
if (uv.y < 0.45) {
if (uv.x > 0.75) {
digit = floor(uValue*10.0);
digit = digit - floor(digit/10.0)*10.0;
i = 48.0 - 32.0 + digit;
uRow = floor(i / 10.0);
uCol = i - 10.0 * uRow;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.5) / devisor, uRow / devisor) );
} else if (uv.x > 0.5) {
uCol = 4.0;
uRow = 1.0;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.0) / devisor, uRow / devisor) );
} else if (uv.x > 0.25) {
digit = floor(uValue);
digit = digit - floor(digit/10.0)*10.0;
i = 48.0 - 32.0 + digit;
uRow = floor(i / 10.0);
uCol = i - 10.0 * uRow;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.5) / devisor, uRow / devisor) );
} else if (uValue >= 10.0) {
digit = floor(uValue/10.0);
digit = digit - floor(digit/10.0)*10.0;
i = 48.0 - 32.0 + digit;
uRow = floor(i / 10.0);
uCol = i - 10.0 * uRow;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.0) / devisor, uRow / devisor) );
} else {
fragColor = vec4(0.0, 0.0, 0.0, 0.0);
}
} else {
fragColor = vec4(0.0, 0.0, 0.0, 0.0);
}
gl_FragColor = fragColor;
}
Above code works for a texture atlas where numbers start from 0 at the 7th column of the 2nd row of the font atlas (texture).
Refer to https://www.shadertoy.com/view/Xl23Dw for demonstration (with wrong texture though)
//assuming you have a map called 'map'
var infowindow = new google.maps.InfoWindow();
var latlng1 = new google.maps.LatLng(0,0);
var marker1 = new google.maps.Marker({position:latlng1, map:map});
google.maps.event.addListener(marker1, 'click',
function(){
infowindow.close();//hide the infowindow
infowindow.setContent('Marker #1');//update the content for this marker
infowindow.open(map, marker1);//"move" the info window to the clicked marker and open it
}
);
var latlng2 = new google.maps.LatLng(10,10);
var marker2 = new google.maps.Marker({position:latlng2, map:map});
google.maps.event.addListener(marker2, 'click',
function(){
infowindow.close();//hide the infowindow
infowindow.setContent('Marker #2');//update the content for this marker
infowindow.open(map, marker2);//"move" the info window to the clicked marker and open it
}
);
This will "move" the info window around to each clicked marker, in effect closing itself, then reopening (and panning to fit the viewport) in its new location. It changes its contents before opening to give the desired effect. Works for n markers.
In coffee if anyone needs it.
$(window).bind 'orientationchange', ->
if window.orientation % 180 == 0
$(document.body).css
"-webkit-transform-origin" : ''
"-webkit-transform" : ''
else
if window.orientation > 0
$(document.body).css
"-webkit-transform-origin" : "200px 190px"
"-webkit-transform" : "rotate(-90deg)"
else
$(document.body).css
"-webkit-transform-origin" : "280px 190px"
"-webkit-transform" : "rotate(90deg)"
As mentioned, display:inline is probably what you want. Some browsers also support inline-blocks.
Also if you want selected field from table and aggregated then as array .
SELECT json_agg(json_build_object('data_a',a,
'data_b',b,
)) from t;
The result will come .
[{'data_a':1,'data_b':'value1'}
{'data_a':2,'data_b':'value2'}]
Given your factorGenerator
function, here is a divisorGen
that should work:
def divisorGen(n):
factors = list(factorGenerator(n))
nfactors = len(factors)
f = [0] * nfactors
while True:
yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
i = 0
while True:
f[i] += 1
if f[i] <= factors[i][1]:
break
f[i] = 0
i += 1
if i >= nfactors:
return
The overall efficiency of this algorithm will depend entirely on the efficiency of the factorGenerator
.
If you are not allowed to change the buffer limit at the server level, you will need to use the <%Response.Buffer = False%> method.
HOWEVER, if you are still getting this error and have a large table on the page, the culprit may be table itself. By design, some versions of Internet Explorer will buffer the entire content between before it is rendered to the page. So even if you are telling the page to not buffer the content, the table element may be buffered and causing this error.
Some alternate solutions may be to paginate the table results, but if you must display the entire table and it has thousands of rows, throw this line of code in the middle of the table generation loop: <% Response.Flush %>. For speed considerations, you may also want to consider adding a basic counter so that the flush only happens every 25 or 100 lines or so.
Drawbacks of not buffering the output:
See this KB article for more information http://support.microsoft.com/kb/925764
Hope that helps.
You could try shifting the number space upward so they both become positive.
To calculate a gain between any two positive or negative numbers, you're going to have to keep one foot in the magnitude-growth world and the other foot in the volume-growth world. You can lean to one side or the other depending on how you want the result gains to appear, and there are consequences to each choice.
Strategy
Create a shift equation that generates a positive number relative to the old and new numbers.
Add the custom shift to the old and new numbers to get new_shifted and old_shifted.
Take the (new_shifted - old_shifted) / old_shifted) calculation to get the gain.
For example:
old -> new
-50 -> 30 //Calculate a shift like (2*(50 + 30)) = 160
shifted_old -> shifted_new
110 -> 190
= (new-old)/old
= (190-110)/110 = 72.73%
How to choose a shift function
If your shift function shifts the numbers too far upward, like for example adding 10000 to each number, you always get a tiny growth/decline. But if the shift is just big enough to get both numbers into positive territory, you'll get wild swings in the growth/decline on edge cases. You'll need to dial in the shift function so it makes sense for your particular application. There is no totally correct solution to this problem, you must take the bitter with the sweet.
Add this to your excel to see how the numbers and gains move about:
shift function
old new abs_old abs_new 2*abs(old)+abs(new) shiftedold shiftednew gain
-50 30 50 30 160 110 190 72.73%
-50 40 50 40 180 130 220 69.23%
10 20 10 20 60 70 80 14.29%
10 30 10 30 80 90 110 22.22%
1 10 1 10 22 23 32 39.13%
1 20 1 20 42 43 62 44.19%
-10 10 10 10 40 30 50 66.67%
-10 20 10 20 60 50 80 60.00%
1 100 1 100 202 203 302 48.77%
1 1000 1 1000 2002 2003 3002 49.88%
The gain percentage is affected by the magnitude of the numbers. The numbers above are a bad example and result from a primitive shift function.
You have to ask yourself which critter has the most productive gain:
Evaluate the growth of critters A, B, C, and D:
A used to consume 0.01 units of energy and now consumes 10 units.
B used to consume 500 units and now consumes 700 units.
C used to consume -50 units (Producing units!) and now consumes 30 units.
D used to consume -0.01 units (Producing) and now consumes -30 units (producing).
In some ways arguments can be made that each critter is the biggest grower in their own way. Some people say B is best grower, others will say D is a bigger gain. You have to decide for yourself which is better.
The question becomes, can we map this intuitive feel of what we label as growth into a continuous function that tells us what humans tend to regard as "awesome growth" vs "mediocre growth".
Growth a mysterious thing
You then have to take into account that Critter B may have had a far more difficult time than critter D. Critter D may have far more prospects for it in the future than the others. It had an advantage! How do you measure the opportunity
, difficulty
, velocity
and acceleration
of growth? To be able to predict the future, you need to have an intuitive feel for what constitutes a "major home run" and a "lame advance in productivity".
The first and second derivatives of a function will give you the "velocity of growth" and "acceleration of growth". Learn about those in calculus, they are super important.
Which is growing more? A critter that is accelerating its growth minute by minute, or a critter that is decelerating its growth? What about high and low velocity and high/low rate of change? What about the notion of exhausting opportunities for growth. Cost benefit analysis and ability/inability to capitalize on opportunity. What about adversarial systems (where your success comes from another person's failure) and zero sum games?
There is exponential growth, liner growth. And unsustainable growth. Cost benefit analysis and fitting a curve to the data. The world is far queerer than we can suppose. Plotting a perfect line to the data does not tell you which data point comes next because of the black swan effect. I suggest all humans listen to this lecture on growth, the University of Colorado At Boulder gave a fantastic talk on growth, what it is, what it isn't, and how humans completely misunderstand it. http://www.youtube.com/watch?v=u5iFESMAU58
Fit a line to the temperature of heated water, once you think you've fit a curve, a black swan happens, and the water boils. This effect happens all throughout our universe, and your primitive function (new-old)/old is not going to help you.
Here is Java code that accomplishes most of the above notions in a neat package that suits my needs:
Critter growth - (a critter can be "radio waves", "beetles", "oil temprature", "stock options", anything).
public double evaluate_critter_growth_return_a_gain_percentage(
double old_value, double new_value) throws Exception{
double abs_old = Math.abs(old_value);
double abs_new = Math.abs(new_value);
//This is your shift function, fool around with it and see how
//It changes. Have a full battery of unit tests though before you fiddle.
double biggest_absolute_value = (Math.max(abs_old, abs_new)+1)*2;
if (new_value <= 0 || old_value <= 0){
new_value = new_value + (biggest_absolute_value+1);
old_value = old_value + (biggest_absolute_value+1);
}
if (old_value == 0 || new_value == 0){
old_value+=1;
new_value+=1;
}
if (old_value <= 0)
throw new Exception("This should never happen.");
if (new_value <= 0)
throw new Exception("This should never happen.");
return (new_value - old_value) / old_value;
}
Result
It behaves kind-of sort-of like humans have an instinctual feel for critter growth. When our bank account goes from -9000 to -3000, we say that is better growth than when the account goes from 1000 to 2000.
1->2 (1.0) should be bigger than 1->1 (0.0)
1->2 (1.0) should be smaller than 1->4 (3.0)
0->1 (0.2) should be smaller than 1->3 (2.0)
-5-> -3 (0.25) should be smaller than -5->-1 (0.5)
-5->1 (0.75) should be smaller than -5->5 (1.25)
100->200 (1.0) should be the same as 10->20 (1.0)
-10->1 (0.84) should be smaller than -20->1 (0.91)
-10->10 (1.53) should be smaller than -20->20 (1.73)
-200->200 should not be in outer space (say more than 500%):(1.97)
handle edge case 1-> -4: (-0.41)
1-> -4: (-0.42) should be bigger than 1-> -9:(-0.45)
If my shift function makes sense for your needs, use it. Be sure to battle test this, if you crash the space shuttle its totally NOT my fault. This method is a heuristic.
path
is simply new in Django 2.0, which was only released a couple of weeks ago. Most tutorials won't have been updated for the new syntax.
It was certainly supposed to be a simpler way of doing things; I wouldn't say that URL is more powerful though, you should be able to express patterns in either format.
It's depend on your li height just call one more thing line height
* {
padding: 0;
margin: 0;
}
html,
body {
height: 100%;
}
ul {
height: 100%;
}
li {
display: flex;
justify-content: center;
align-self: center;
background: silver;
width: 100%;
height:50px;line-height:50px;
}
_x000D_
<ul>
<li>This is the text</li>
</ul>
_x000D_
You can accomplish this using the function FILL to create filled polygons under the sections of your plots. You will want to plot the lines and polygons in the order you want them to be stacked on the screen, starting with the bottom-most one. Here's an example with some sample data:
x = 1:100; %# X range
y1 = rand(1,100)+1.5; %# One set of data ranging from 1.5 to 2.5
y2 = rand(1,100)+0.5; %# Another set of data ranging from 0.5 to 1.5
baseLine = 0.2; %# Baseline value for filling under the curves
index = 30:70; %# Indices of points to fill under
plot(x,y1,'b'); %# Plot the first line
hold on; %# Add to the plot
h1 = fill(x(index([1 1:end end])),... %# Plot the first filled polygon
[baseLine y1(index) baseLine],...
'b','EdgeColor','none');
plot(x,y2,'g'); %# Plot the second line
h2 = fill(x(index([1 1:end end])),... %# Plot the second filled polygon
[baseLine y2(index) baseLine],...
'g','EdgeColor','none');
plot(x(index),baseLine.*ones(size(index)),'r'); %# Plot the red line
And here's the resulting figure:
You can also change the stacking order of the objects in the figure after you've plotted them by modifying the order of handles in the 'Children'
property of the axes object. For example, this code reverses the stacking order, hiding the green polygon behind the blue polygon:
kids = get(gca,'Children'); %# Get the child object handles
set(gca,'Children',flipud(kids)); %# Set them to the reverse order
Finally, if you don't know exactly what order you want to stack your polygons ahead of time (i.e. either one could be the smaller polygon, which you probably want on top), then you could adjust the 'FaceAlpha'
property so that one or both polygons will appear partially transparent and show the other beneath it. For example, the following will make the green polygon partially transparent:
set(h2,'FaceAlpha',0.5);
Use dev.new()
. (See this related question.)
plot(1:10)
dev.new(width=5, height=4)
plot(1:20)
To be more specific which units are used:
dev.new(width=5, height=4, unit="in")
plot(1:20)
dev.new(width = 550, height = 330, unit = "px")
plot(1:15)
edit additional argument for Rstudio (May 2020), (thanks user Soren Havelund Welling)
For Rstudio, add dev.new(width=5,height=4,noRStudioGD = TRUE)
Run the httpd.exe from the command line, as Tim mentioned. The path to PostgreSQL changed, nothing else was running on Port 80 and I didn't see anything in the error.log
file.
I clone my boot drive/partition once the base is setup so I don't have to spend three days installing and retweaking everything. Turns I had reinstalled my WAPP stack and used very specific names/versions for PostgreSQL. Windows will not return a specific error message unless you run the command from the command line.
Is numeric can be achieved via many ways, but i use my way
public bool IsNumeric(string value)
{
bool isNumeric = true;
char[] digits = "0123456789".ToCharArray();
char[] letters = value.ToCharArray();
for (int k = 0; k < letters.Length; k++)
{
for (int i = 0; i < digits.Length; i++)
{
if (letters[k] != digits[i])
{
isNumeric = false;
break;
}
}
}
return isNumeric;
}
As of Python 3.2+, you can also accomplish this using the to_bytes
native int method:
newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
newFile.write(byte.to_bytes(1, byteorder='big'))
I.e., each single call to to_bytes
in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte
. You can also shorten the last two lines into a single one:
newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))
I use an Android Studio plug-in called "adb idea" -- has a drop down menu for various functions (Uninstall, Kill, Start, etc) that you can target at any connected or simulated device. One could argue it takes me a step away from having a deeper understanding of the power of adb commands and I'd probably agree....though I'm really operating at a lower level of understanding anyway so for me it helps to have a helper. ADB Idea
Per the documentation from GitHub regarding GFM syntax highlighted code blocks
We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.
Rendered on GitHub, console
makes the lines after the console blue. bash
, sh
, or shell
don't seem to "highlight" much ...and you can use posh
for PowerShell or CMD.
Alternative approach: http://www.thecssninja.com/css/real-text-rotation-with-css
p { writing-mode: tb-rl; }
I have answered this question here..Covariant virtual functions return type problem
See if it helps for some one.
Try uninstalling Python and then install it again, but this time make sure that the option Add Python to Path is marked as checked during the installation process.
I had the same problem and for me it was because the vc2010 redist x86 was too recent.
Check your temp folder (C:\Users\\AppData\Local\Temp) for the most recent file named
and check if you have the following error
Installation Blockers:
A newer version of Microsoft Visual C++ 2010 Redistributable has been detected on the machine.
Final Result: Installation failed with error code: (0x000013EC), "A StopBlock was hit or a System >Requirement was not met." (Elapsed time: 0 00:00:00).
then go to Control Panel>Program & Features and uninstall all the
After successful installation of DXSDK, simply run Windows Update and it will update the redistributables back to the latest version.
I was able to fix this by installing the typings
module.
npm install -g typings
typings install
(Using ng 2.0.0-rc.1)
On linux you can create a symbolic link from your package to a directory of the PYTHONPATH without having to deal with the environment variables. Something like:
ln -s /your/path /usr/lib/pymodules/python2.7/
*args
just means that the function takes a number of arguments, generally of the same type.
Check out this section in the Python tutorial for more info.
Yeap, you just need to make .
match newline :
$string =~ /(START)(.+?)(END)/s;
For those who use docker-compose
, it’s really easy to set a password without any config file like redis.conf
. Here’s how you would normally use the official Redis image:
redis:
image: 'redis:4-alpine'
ports:
- '6379:6379'
And here’s all you need to change to set a custom password:
redis:
image: 'redis:4-alpine'
command: redis-server --requirepass yourpassword
ports:
- '6379:6379'
Everything will start up as normal and your Redis server will be protected by a password.
For details, this blog post seems to support the idea.
Most Easiest Way
$url = 'https://www.youtube.com/embed/ROipDjNYK4k?rel=0&autoplay=1';
$url_arr = parse_url($url);
$query = $url_arr['query'];
print $url = str_replace(array($query,'?'), '', $url);
//output
https://www.youtube.com/embed/ROipDjNYK4k
You need to set Div2 to Div1's innerHTML. Also, JavaScript is case sensitive - in your HTML, the id Div2
is DIV2
. Also, you should use document
, not Document
:
var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
Here is a JSFiddle: http://jsfiddle.net/gFN6r/.
This is code in xml of how to center an ImageView, I used "layout_centerHorizontal".
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_centerHorizontal="true"
>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/img2"
/>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/img1"
/>
</LinearLayout>
or this other example...
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal"
>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/img2"
/>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/img1"
/>
</LinearLayout>
Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?
best way I know
window.onbeforeunload = function (e) {
var e = e || window.event;
var msg = "Do you really want to leave this page?"
// For IE and Firefox
if (e) {
e.returnValue = msg;
}
// For Safari / chrome
return msg;
};
This worked for me
df.sort_values(by='Column_name', inplace=True, ascending=False)
Following the documentation of fopen
:
``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.
So if you pFile2=fopen("myfile2.txt", "a");
the stream is positioned at the end to append automatically. just do:
FILE *pFile;
FILE *pFile2;
char buffer[256];
pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
perror("Error opening file.");
}
else {
while(fgets(buffer, sizeof(buffer), pFile)) {
fprintf(pFile2, "%s", buffer);
}
}
fclose(pFile);
fclose(pFile2);
To get the path, you can use:
console.log('document.location', document.location.href);_x000D_
console.log('location.pathname', window.location.pathname); // Returns path only_x000D_
console.log('location.href', window.location.href); // Returns full URL
_x000D_
You should check the parent process name, see The Code Project article about a .NET based solution**.
A non-programmatic way to check:
c:\windows\notepad.exe
)The same can be checked by getting the parent process name.
Sub Button167_Click()
If ThisWorkbook.Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value = 1 Then
Range("Y12").Value = 1
Else
Range("Y12").Value = 0
End If
End Sub
1 is checked, -4146 is unchecked, 2 is mixed (grey box)
You can use a for loop with window.scrollTo and setTimeout to scroll smoothly with plain Javascript. To scroll to an element with my scrollToSmoothly
function: scrollToSmoothly(elem.offsetTop)
(assuming elem
is a DOM element). You can use this to scroll smoothly to any y-position in the document.
function scrollToSmoothly(pos, time){
/*Time is only applicable for scrolling upwards*/
/*Code written by hev1*/
/*pos is the y-position to scroll to (in pixels)*/
if(isNaN(pos)){
throw "Position must be a number";
}
if(pos<0){
throw "Position can not be negative";
}
var currentPos = window.scrollY||window.screenTop;
if(currentPos<pos){
var t = 10;
for(let i = currentPos; i <= pos; i+=10){
t+=10;
setTimeout(function(){
window.scrollTo(0, i);
}, t/2);
}
} else {
time = time || 2;
var i = currentPos;
var x;
x = setInterval(function(){
window.scrollTo(0, i);
i -= 10;
if(i<=pos){
clearInterval(x);
}
}, time);
}
}
Demo:
<button onClick="scrollToDiv()">Scroll To Element</button>_x000D_
<div style="margin: 1000px 0px; text-align: center;">Div element<p/>_x000D_
<button onClick="scrollToSmoothly(Number(0))">Scroll back to top</button>_x000D_
</div>_x000D_
<script>_x000D_
function scrollToSmoothly(pos, time){_x000D_
/*Time is only applicable for scrolling upwards*/_x000D_
/*Code written by hev1*/_x000D_
/*pos is the y-position to scroll to (in pixels)*/_x000D_
if(isNaN(pos)){_x000D_
throw "Position must be a number";_x000D_
}_x000D_
if(pos<0){_x000D_
throw "Position can not be negative";_x000D_
}_x000D_
var currentPos = window.scrollY||window.screenTop;_x000D_
if(currentPos<pos){_x000D_
var t = 10;_x000D_
for(let i = currentPos; i <= pos; i+=10){_x000D_
t+=10;_x000D_
setTimeout(function(){_x000D_
window.scrollTo(0, i);_x000D_
}, t/2);_x000D_
}_x000D_
} else {_x000D_
time = time || 2;_x000D_
var i = currentPos;_x000D_
var x;_x000D_
x = setInterval(function(){_x000D_
window.scrollTo(0, i);_x000D_
i -= 10;_x000D_
if(i<=pos){_x000D_
clearInterval(x);_x000D_
}_x000D_
}, time);_x000D_
}_x000D_
}_x000D_
function scrollToDiv(){_x000D_
var elem = document.querySelector("div");_x000D_
scrollToSmoothly(elem.offsetTop);_x000D_
}_x000D_
</script>
_x000D_
It seems like overkill but you can use supervisor to start and stop your simpleHttpserver, and completely manage it as a service.
Or just run it in the foreground as suggested and kill it with control c
If you want to store the hex values in a char *
string, you can use snprintf
. You need to allocate space for all the printed characters, including the leading zeros and colon.
Expanding on Mark's answer:
char str_buf* = malloc(3*X + 1); // X is the number of bytes to be converted
int i;
for (i = 0; i < x; i++)
{
if (i > 0) snprintf(str_buf, 1, ":");
snprintf(str_buf, 2, "%02X", num_buf[i]); // need 2 characters for a single hex value
}
snprintf(str_buf, 2, "\n\0"); // dont forget the NULL byte
So now str_buf
will contain the hex string.
In SQL Server
You can do this using With CTE
WITH common_table_expression (Transact-SQL)
CREATE TABLE tab(ColumnA DECIMAL(10,2), ColumnB DECIMAL(10,2), ColumnC DECIMAL(10,2))
INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (2, 10, 2),(3, 15, 6),(7, 14, 3)
WITH tab_CTE (ColumnA, ColumnB, ColumnC,calccolumn1)
AS
(
Select
ColumnA,
ColumnB,
ColumnC,
ColumnA + ColumnB As calccolumn1
from tab
)
SELECT
ColumnA,
ColumnB,
calccolumn1,
calccolumn1 / ColumnC AS calccolumn2
FROM tab_CTE
If you identify a page that takes time to load, use SharePoint's Developer Dashboard to see which component takes time.
I had this error for two weeks, and the majority of the solutions stated 'chmod -R' as the the answer, unfortunately for me my git repos (local / remote / shared - with team) were all on Windows OS, and even though chmod -Rv showed all the files changed to 'rwxrwxrwx', a subsequent 'ls -l' still showed all files as 'rwxr-xr-x' and the error repeated itself. I eventually saw this solution by Ariejan de Vroom. It worked and we were all able to pull and push again.
On both local (the local that is having trouble pushing) and remote repos, run the following commands:
$ git fsck
$ git prune
$ git repack
$ git fsck
On a side note, I tried using Windows' native file permissions / ACL and even resorted to elevating the problem user to Administrator, but none of that seemed to help. Not sure if the environment is important, but it may help someone with a similar setup - problem team member and remote (Windows Server 2008 R2 Standard), my local (Windows 7 VM).
This worked for me:
On terminal type the following
$ sudo mysql -u root -p
Enter password://just press enter
mysql>
Very nice example using paste and substitute to typeset both symbols (mathplot) and variables at http://vis.supstat.com/2013/04/mathematical-annotation-in-r/
Here is a ggplot adaptation
library(ggplot2)
x_mean <- 1.5
x_sd <- 1.2
N <- 500
n <- ggplot(data.frame(x <- rnorm(N, x_mean, x_sd)),aes(x=x)) +
geom_bar() + stat_bin() +
labs(title=substitute(paste(
"Histogram of random data with ",
mu,"=",m,", ",
sigma^2,"=",s2,", ",
"draws = ", numdraws,", ",
bar(x),"=",xbar,", ",
s^2,"=",sde),
list(m=x_mean,xbar=mean(x),s2=x_sd^2,sde=var(x),numdraws=N)))
print(n)
Bootstrap 2.3.x and later supports the dropdown-submenu
..
<ul class="dropdown-menu">
<li><a href="#">Login</a></li>
<li class="dropdown-submenu">
<a tabindex="-1" href="#">More options</a>
<ul class="dropdown-menu">
<li><a tabindex="-1" href="#">Second level</a></li>
<li><a href="#">Second level</a></li>
<li><a href="#">Second level</a></li>
</ul>
</li>
<li><a href="#">Logout</a></li>
</ul>
Another way of solving this problem is by not relying on the correct return value from the display but relying on the Android resources resolving.
Create the file layouts.xml
in the folders res/values-land
and res/values-port
with the following content:
res/values-land/layouts.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="is_landscape">true</bool>
</resources>
res/values-port/layouts.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="is_landscape">false</bool>
</resources>
In your source code you can now access the current orientation as follows:
context.getResources().getBoolean(R.bool.is_landscape)
By using the List
property.
ListBox1.AddItem "foo"
ListBox1.List(ListBox1.ListCount - 1, 1) = "bar"
This is my work around to fail safe in case if i will need to move to python 3 in future.
def _input(msg):
return raw_input(msg)
I've encountered this problem with a input[type="datetime-local"]
, which is similar to this problem.
And I've found a way to overcome this kind of problems.
First, you must turn on chrome's shadow-root feature by "DevTools -> Settings -> General -> Elements -> Show user agent shadow DOM"
Then you can see all shadowed DOM elements, for example, for <input type="number">
, the full element with shadowed DOM is:
<input type="number">_x000D_
<div id="text-field-container" pseudo="-webkit-textfield-decoration-container">_x000D_
<div id="editing-view-port">_x000D_
<div id="inner-editor"></div>_x000D_
</div>_x000D_
<div pseudo="-webkit-inner-spin-button" id="spin"></div>_x000D_
</div>_x000D_
</input>
_x000D_
And according to these info, you can draft some CSS to hide unwanted elements, just as @Josh said.
I use this function datetime_to_local_timezone()
, which seems overly convoluted but I found no simpler version of a function that converts a datetime
instance to the local time zone, as configured in the operating system, with the UTC offset that was in effect at that time:
import time, datetime
def datetime_to_local_timezone(dt):
epoch = dt.timestamp() # Get POSIX timestamp of the specified datetime.
st_time = time.localtime(epoch) # Get struct_time for the timestamp. This will be created using the system's locale and it's time zone information.
tz = datetime.timezone(datetime.timedelta(seconds = st_time.tm_gmtoff)) # Create a timezone object with the computed offset in the struct_time.
return dt.astimezone(tz) # Move the datetime instance to the new time zone.
utc = datetime.timezone(datetime.timedelta())
dt1 = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, utc) # DST was in effect
dt2 = datetime.datetime(2009, 1, 10, 18, 44, 59, 193982, utc) # DST was not in effect
print(dt1)
print(datetime_to_local_timezone(dt1))
print(dt2)
print(datetime_to_local_timezone(dt2))
This example prints four dates. For two moments in time, one in January and one in July 2009, each, it prints the timestamp once in UTC and once in the local time zone. Here, where CET (UTC+01:00) is used in the winter and CEST (UTC+02:00) is used in the summer, it prints the following:
2009-07-10 18:44:59.193982+00:00
2009-07-10 20:44:59.193982+02:00
2009-01-10 18:44:59.193982+00:00
2009-01-10 19:44:59.193982+01:00
For int and long, as primitives, not really. For Integer, it is possible someone wrote one.
Given that BigInteger is a (mathematical/functional) superset of int, Integer, long, and Long, if you need to use these types, convert them to a BigInteger, do the GCD, and convert the result back.
private static int gcdThing(int a, int b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.intValue();
}
It would probably be easiest to implement this using JavaScript ... Here's a JQuery script to demo ... As the others mentioned ... we have a class named 'active' to indicate the active tab - NOT the pseudo-class ':active.' We could have just as easily named it anything though ... selected, current, etc., etc.
/* CSS */
#nav { width:480px;margin:1em auto;}
#nav ul {margin:1em auto; padding:0; font:1em "Arial Black",sans-serif; }
#nav ul li{display:inline;}
#nav ul li a{text-decoration:none; margin:0; padding:.25em 25px; background:#666; color:#ffffff;}
#nav ul li a:hover{background:#ff9900; color:#ffffff;}
#nav ul li a.active {background:#ff9900; color:#ffffff;}
/* JQuery Example */
<script type="text/javascript">
$(function (){
$('#nav ul li a').each(function(){
var path = window.location.href;
var current = path.substring(path.lastIndexOf('/')+1);
var url = $(this).attr('href');
if(url == current){
$(this).addClass('active');
};
});
});
</script>
/* HTML */
<div id="nav" >
<ul>
<li><a href='index.php?1'>One</a></li>
<li><a href='index.php?2'>Two</a></li>
<li><a href='index.php?3'>Three</a></li>
<li><a href='index.php?4'>Four</a></li>
</ul>
</div>
I previously came up with a different workaround that doesn't use stored procedures, but instead uses a parameter table and some connection_id() magic.
EDIT (Copied up from comments)
create a table that contains a column called connection_id
(make it a bigint). Place columns in that table for parameters for the view. Put a primary key on the connection_id
. replace into the parameter table and use CONNECTION_ID()
to populate the connection_id value. In the view use a cross join to the parameter table and put WHERE param_table.connection_id = CONNECTION_ID()
. This will cross join with only one row from the parameter table which is what you want. You can then use the other columns in the where clause for example where orders.order_id = param_table.order_id
.
Many solutions come to mind, depending on what you want to achive:
Every List item is key and value
for( Object o : list ) {
map.put(o,o);
}
List elements have something to look them up, maybe a name:
for( MyObject o : list ) {
map.put(o.name,o);
}
List elements have something to look them up, and there is no guarantee that they are unique: Use Googles MultiMaps
for( MyObject o : list ) {
multimap.put(o.name,o);
}
Giving all the elements the position as a key:
for( int i=0; i<list.size; i++ ) {
map.put(i,list.get(i));
}
...
It really depends on what you want to achive.
As you can see from the examples, a Map is a mapping from a key to a value, while a list is just a series of elements having a position each. So they are simply not automatically convertible.
if(strcmp(sr1,str2)) // this returns 0 if strings r equal
flag=0;
else flag=1; // then last check the variable flag value and print the message
OR
char str1[20],str2[20];
printf("enter first str > ");
gets(str1);
printf("enter second str > ");
gets(str2);
for(int i=0;str1[i]!='\0';i++)
{
if(str[i]==str2[i])
flag=0;
else {flag=1; break;}
}
//check the value of flag if it is 0 then strings r equal simple :)
use global scope on your $con and put it inside your getPosts() function like so.
function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
{
echo "<div class=\"blogsnippet\">";
echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
echo "</div>";
}
}
On the user action:
// you have to do something along the lines of
myJFrame.getContentPane().removeAll()
myJFrame.getContentPane().invalidate()
myJFrame.getContentPane().add(newContentPanel)
myJFrame.getContentPane().revalidate()
Then you can resize your wndow as needed.
CSS Solutuion
#left{
float:right;
width:200px;
height:500px;
background:red;
}
#right{
margin-right: 200px;
height:500px;
background:blue;
}
Check working example at http://jsfiddle.net/NP4vb/3/
jQuery Solution
var parentw = $('#parent').width();
var rightw = $('#right').width();
$('#left').width(parentw - rightw);
Check working example http://jsfiddle.net/NP4vb/
May I suggest a pure CSS solution altogether?
Just have a Div that you want to show the image in. Set the image as background. Then have the property background-size: cover
or background-size: contain
depending on how you want it.
cover
will crop the image until smaller sides cover the box.
contain
will keep the entire image inside the div, leaving you with spaces on sides.
Check the snippet below.
div {_x000D_
height: 300px;_x000D_
width: 300px;_x000D_
border: 3px dashed grey;_x000D_
background-position: center;_x000D_
background-repeat: no-repeat;_x000D_
}_x000D_
_x000D_
.cover-image {_x000D_
background-size: cover;_x000D_
}_x000D_
_x000D_
.contain-image {_x000D_
background-size: contain;_x000D_
}
_x000D_
<div class="cover-image" style="background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)">_x000D_
</div>_x000D_
<br/>_x000D_
<div class="contain-image" style="background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)">_x000D_
</div>
_x000D_
In Go 1.13 and later, you can use Value.IsZero
method offered in reflect
package.
if reflect.ValueOf(v).IsZero() {
// v is zero, do something
}
Apart from basic types, it also works for Array, Chan, Func, Interface, Map, Ptr, Slice, UnsafePointer, and Struct. See this for reference.
For .nupkg files I like to use:
Install-Package C:\Path\To\Some\File.nupkg
var file = form.getForm().findField("file").getValue();
var fileLen = file.length;
var lastValue = file.substring(fileLen - 3, fileLen);
if (lastValue == 'doc') {//check same for other file format}
You need xlutils.copy
. Try something like this:
from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')
Keep in mind you can't overwrite cells by default as noted in this question.
this issue can be resolved using 2 ways:
netstat -ao | find "8080" Taskkill /PID 1342 /F
server.port=8081
I've had this sort of problem.....
The solve: cmd
/ powershell
run as ADMINISTRATOR! I always forget.
Notice: In powershell
, you need to put .\
for example:
.\httpd -k shutdown .\httpd -k stop .\httpd -k uninstall
Result: Removing the apache2.4
service The Apache2.4
service has been removed successfully.
assertNotNull
asserts that the object is not null. If it is null the test fails, so you want that.
You would need to say which version of Ant and which JVM version.
You can run ant -v
to see which settings Ant is using as per the doc
Ant 1.8* requires JDK 1.4 or higher.
The 'Unsupported major.minor version 51.0' means somewhere code was compiled for a version of the JDK, and that you are trying to run those classes under an older version of the JDK. (see here)
No, according to Apple here:
Note: You cannot install apps from the App Store in simulation environments.
I made my own version here : http://androidblogger.blogspot.com/2009/12/how-to-improve-your-application-crash.html
It's basically the same thing, but I'm using a mail rather than a http connexion to send the report, and, more important, I added some informations like application version, OS version, Phone model, or avalaible memory to my report...
I have tried different kinds of maps and the Conversion Box worked. I have used your map and have pasted an example below with some inner maps. Hope it is helpful to you ....
import java.util.HashMap;
import java.util.Map;
import cjm.component.cb.map.ToMap;
import cjm.component.cb.xml.ToXML;
public class Testing
{
public static void main(String[] args)
{
try
{
Map<String, Object> map = new HashMap<String, Object>(); // ORIGINAL MAP
map.put("name", "chris");
map.put("island", "faranga");
Map<String, String> mapInner = new HashMap<String, String>(); // SAMPLE INNER MAP
mapInner.put("a", "A");
mapInner.put("b", "B");
mapInner.put("c", "C");
map.put("innerMap", mapInner);
Map<String, Object> mapRoot = new HashMap<String, Object>(); // ROOT MAP
mapRoot.put("ROOT", map);
System.out.println("Map: " + mapRoot);
System.out.println();
ToXML toXML = new ToXML();
String convertedXML = String.valueOf(toXML.convertToXML(mapRoot, true)); // CONVERTING ROOT MAP TO XML
System.out.println("Converted XML: " + convertedXML);
System.out.println();
ToMap toMap = new ToMap();
Map<String, Object> convertedMap = toMap.convertToMap(convertedXML); // CONVERTING CONVERTED XML BACK TO MAP
System.out.println("Converted Map: " + convertedMap);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output:
Map: {ROOT={name=chris, innerMap={b=B, c=C, a=A}, island=faranga}}
-------- Map Detected --------
-------- XML created Successfully --------
Converted XML: <ROOT><name>chris</name><innerMap><b>B</b><c>C</c><a>A</a></innerMap><island>faranga</island></ROOT>
-------- XML Detected --------
-------- Map created Successfully --------
Converted Map: {ROOT={name=chris, innerMap={b=B, c=C, a=A}, island=faranga}}
using @quick_sliv answer:
function insertAtCaret(el, text) {
var caretPos = el.selectionStart;
var textAreaTxt = el.value;
el.value = textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos);
};
My issue was that I was on a machine with node version 0.12.2
, but that had an old 1.x.x
version of npm
. Be sure to update your version of npm: sudo npm install -g npm
Once that is done, remove any existing node-sass
and reinstall it via npm.
This works for me :
CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int ,
IN bus_fun_temp_id int , OUT o_message VARCHAR (50) ,
OUT o_number INT )
BEGIN
DECLARE v_pkg_name varchar(50) ;
DECLARE v_pkg_temp_id int(10) ;
DECLARE v_workflow_count INT(10);
-- checking if workflow created for package
select count(*) INTO v_workflow_count from workflow w where w.package_id =
package_id ;
this_proc:BEGIN -- this_proc block start here
IF v_workflow_count = 0 THEN
select 'no work flow ' as 'workflow_status' ;
SET o_message ='Work flow is not created for this package.';
SET o_number = -2 ;
LEAVE this_proc;
END IF;
select 'work flow created ' as 'workflow_status' ;
-- To send some message
SET o_message ='SUCCESSFUL';
SET o_number = 1 ;
END ;-- this_proc block end here
END
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,_x000D_
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),_x000D_
msg = document.getElementById('msg'),_x000D_
onChange = function(ev){_x000D_
ev.preventDefault();_x000D_
let _this = this,_x000D_
arrVal = Array.prototype.slice.call(_x000D_
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))_x000D_
.map(function(cur){return cur.value});_x000D_
_x000D_
if(arrVal.length){_x000D_
msg.innerHTML = JSON.stringify(arrVal);_x000D_
} else {_x000D_
_this.checked=true;_x000D_
msg.innerHTML = "At least one value must be checked!";_x000D_
}_x000D_
};_x000D_
_x000D_
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
_x000D_
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>_x000D_
<div id="msg"></div>
_x000D_
most of the problems cause by .NET Framework. So just go to project properties and change .Net version same as your reference dll.
Done!!!
Hope it's help :)
I have a scenario where I use the BannerViewController written by Apple to display my ads and a ScrollViewController embedded in the BannerViewController.
To prevent the navigation bar from hiding my content, I had to make two changes.
1) Modify BannerViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
if (systemVersion >= 7.0) {
self.edgesForExtendedLayout = UIRectEdgeNone;
}
}
2) Modify my ScrollViewContoller
- (void)viewDidLoad
{
[super viewDidLoad];
float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
if (systemVersion >= 7.0) {
self.edgesForExtendedLayout = UIRectEdgeBottom;
}
}
Now the ads show up correctly at the bottom of the view instead of being covered by the Navigation bar and the content on the top is not cut off.
Also $( "#container" ).find( "div.robotarm" );
is equal to: $( "div.robotarm", "#container" )
If you are running in a local server, such as wamp or xampp, make sure it's using the php.ini you think it is. These servers usually default to a php.ini that's not in your html docs folder.
Use git revert like so:
git revert <insert bad commit hash here>
git revert
creates a new commit with the changes that are rolled back. git reset
erases your git history instead of making a new commit.
The steps after are the same as any other commit.
As per the HTML:
<html>
<body>
<p class="content">Link1.</p>
</body>
<html>
<html>
<body>
<p class="content">Link2.</p>
</body>
<html>
Two(2) <p>
elements are having the same class content
.
So to filter the elements having the same class i.e. content
and create a list you can use either of the following Locator Strategies:
Using class_name
:
elements = driver.find_elements_by_class_name("content")
Using css_selector
:
elements = driver.find_elements_by_css_selector(".content")
Using xpath
:
elements = driver.find_elements_by_xpath("//*[@class='content']")
Ideally, to click on the element you need to induce WebDriverWait for the visibility_of_all_elements_located()
and you can use either of the following Locator Strategies:
Using CLASS_NAME
:
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "content")))
Using CSS_SELECTOR
:
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".content")))
Using XPATH
:
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@class='content']")))
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
You can find a couple of relevant discussions in:
select * from *tablename* where 1 having length(*fieldname*)=*fieldlength*
Example if you want to select from customer the entry's with a name shorter then 2 chars.
select * from customer where 1 **having length(name)<2**
It's my solution to save local data to txt file.
function export2txt() {_x000D_
const originalData = {_x000D_
members: [{_x000D_
name: "cliff",_x000D_
age: "34"_x000D_
},_x000D_
{_x000D_
name: "ted",_x000D_
age: "42"_x000D_
},_x000D_
{_x000D_
name: "bob",_x000D_
age: "12"_x000D_
}_x000D_
]_x000D_
};_x000D_
_x000D_
const a = document.createElement("a");_x000D_
a.href = URL.createObjectURL(new Blob([JSON.stringify(originalData, null, 2)], {_x000D_
type: "text/plain"_x000D_
}));_x000D_
a.setAttribute("download", "data.txt");_x000D_
document.body.appendChild(a);_x000D_
a.click();_x000D_
document.body.removeChild(a);_x000D_
}
_x000D_
<button onclick="export2txt()">Export data to local txt file</button>
_x000D_
#! /bin/bash
file="$@"
realpath "$file" 2>/dev/null || eval realpath $(echo $file | sed 's/ /\\ /g')
This makes up for the shortcomings of realpath
, store it in a shell script fullpath
. You can now call:
$ cd && touch a\ a && rm A 2>/dev/null
$ fullpath "a a"
/home/user/a a
$ fullpath ~/a\ a
/home/user/a a
$ fullpath A
A: No such file or directory.
I get the error in another situation, and here are the problem and the solution:
I have 2 classes derived from a same base class named LevledItem:
public partial class Team : LeveledItem
{
//Everything is ok here!
}
public partial class Story : LeveledItem
{
//Everything is ok here!
}
But in their DbContext, I copied some code but forget to change one of the class name:
public class MFCTeamDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Other codes here
modelBuilder.Entity<LeveledItem>()
.Map<Team>(m => m.Requires("Type").HasValue(ItemType.Team));
}
public class ProductBacklogDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Other codes here
modelBuilder.Entity<LeveledItem>()
.Map<Team>(m => m.Requires("Type").HasValue(ItemType.Story));
}
Yes, the second Map< Team> should be Map< Story>. And it cost me half a day to figure it out!
TimeSpan.FromSeconds(80);
http://msdn.microsoft.com/en-us/library/system.timespan.fromseconds.aspx
If you are using the version 5.* or greater, then you have to use the
all.css or all.min.css
Including the fontawesome.css does not work as it has no reference to the webfonts folder and there is no reference to the @font-face or font-family
You can inspect this by searching the code for the font-family property in fontawesome.css or fontawesome.min.css
I agree with many here, but I also think it depends.
Recently I did this code:
private void animate(FlowLayoutPanel element, int start, int end)
{
bool asc = end > start;
element.Show();
while (start != end) {
start += asc ? 1 : -1;
element.Height = start;
Thread.Sleep(1);
}
if (!asc)
{
element.Hide();
}
element.Focus();
}
It was a simple animate-function, and I used Thread.Sleep
on it.
My conclusion, if it does the job, use it.
It happens because of not very straight forward Servlet specification. If you are working with a native HttpServletRequest
implementation you cannot get both the URL encode body and the parameters. Spring does some workarounds, which make it even more strange and nontransparent.
In such cases Spring (version 3.2.4) re-renders a body for you using data from the getParameterMap()
method. It mixes GET and POST parameters and breaks the parameter order. The class, which is responsible for the chaos is ServletServerHttpRequest
. Unfortunately it cannot be replaced, but the class StringHttpMessageConverter
can be.
The clean solution is unfortunately not simple:
StringHttpMessageConverter
. Copy/Overwrite the original class adjusting method readInternal()
.HttpServletRequest
overwriting getInputStream()
, getReader()
and getParameter*()
methods.In the method StringHttpMessageConverter#readInternal following code must be used:
if (inputMessage instanceof ServletServerHttpRequest) {
ServletServerHttpRequest oo = (ServletServerHttpRequest)inputMessage;
input = oo.getServletRequest().getInputStream();
} else {
input = inputMessage.getBody();
}
Then the converter must be registered in the context.
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true/false">
<bean class="my-new-converter-class"/>
</mvc:message-converters>
</mvc:annotation-driven>
The step two is described here: Http Servlet request lose params from POST body after read it once
A simple way of reading variables from a text file using the standard library:
# Get vars from conf file
var = {}
with open("myvars.conf") as conf:
for line in conf:
if ":" in line:
name, value = line.split(":")
var[name] = str(value).rstrip()
globals().update(var)
Instant
corresponds to time on the prime meridian (Greenwich).
Whereas LocalDateTime
relative to OS time zone settings, and
cannot represent an instant without additional information such as an offset or time-zone.
There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.
There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)
The article is definitely worth a read.
for i in growthRates:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear
should be:
for i in growthRates:
fund = fund * (1 + 0.01 * i) + depositPerYear
You are multiplying 0.01 with the growthRates list object. Multiplying a list by an integer is valid (it's overloaded syntactic sugar that allows you to create an extended a list with copies of its element references).
Example:
>>> 2 * [1,2]
[1, 2, 1, 2]
I would use DBA_SOURCE (if you have access to it) because if the object you require is not owned by the schema under which you are logged in you will not see it.
If you need to know the functions and Procs inside the packages try something like this:
select * from all_source
where type = 'PACKAGE'
and (upper(text) like '%FUNCTION%' or upper(text) like '%PROCEDURE%')
and owner != 'SYS';
The last line prevents all the sys stuff (DBMS_ et al) from being returned. This will work in user_source if you just want your own schema stuff.
SELECT
(CASE
WHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'
ELSE 'NO'
END) as Salable
, *
FROM Product
Adding a header with add_header
works fine with proxy pass, but if there is an existing header value in the response it will stack the values.
If you want to set or replace a header value (for example replace the Access-Control-Allow-Origin
header to match your client for allowing cross origin resource sharing) then you can do as follows:
# 1. hide the Access-Control-Allow-Origin from the server response
proxy_hide_header Access-Control-Allow-Origin;
# 2. add a new custom header that allows all * origins instead
add_header Access-Control-Allow-Origin *;
So proxy_hide_header
combined with add_header
gives you the power to set/replace response header values.
Similar answer can be found here on ServerFault
Note: proxy_set_header
is for setting request headers before the request is sent further, not for setting response headers (these configuration attributes for headers can be a bit confusing).
From the Java tutorial, you need to create a new font and register it in the graphics environment:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
After this step is done, the font is available in calls to getAvailableFontFamilyNames()
and can be used in font constructors.
I needed something similar for a task. This is the code I wrote: It calculates the next day and changes the time to whatever is required and finds seconds between currentTime and next scheduled time.
import datetime as dt
def my_job():
print "hello world"
nextDay = dt.datetime.now() + dt.timedelta(days=1)
dateString = nextDay.strftime('%d-%m-%Y') + " 01-00-00"
newDate = nextDay.strptime(dateString,'%d-%m-%Y %H-%M-%S')
delay = (newDate - dt.datetime.now()).total_seconds()
Timer(delay,my_job,()).start()
Thymeleaf has an equivalent to <c:choose>
and <c:when>
: the th:switch
and th:case
attributes introduced in Thymeleaf 2.0.
They work as you'd expect, using *
for the default case:
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>
</div>
See this for a quick explanation of syntax (or the Thymeleaf tutorials).
Disclaimer: As required by StackOverflow rules, I'm the author of Thymeleaf.
This is how I add to a string when needed:
string[] myList;
myList = new string[100];
for (int i = 0; i < 100; i++)
{
myList[i] = string.Format("List string : {0}", i);
}
Without reading your code but just your scenario, I would solve by using localStorage
.
Here's an example, I'll use prompt()
for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
The JQuery code is fine. You must execute in the ready handler not in the window load event.
<script type="text/javascript">
$(function(){
var aspForm = $("form#aspnetForm");
var firstInput = $(":input:not(input[type=button],input[type=submit],button):visible:first", aspForm);
firstInput.focus();
});
</script>
Update
I tried with the example of Karim79(thanks for the example) and it works fine: http://jsfiddle.net/2sMfU/
Changing the data frames list into a list of tuples.
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})
print(df)
OUTPUT
col1 col2
0 1 4
1 2 5
2 3 6
records = df.to_records(index=False)
result = list(records)
print(result)
OUTPUT
[(1, 4), (2, 5), (3, 6)]
i assume you are working with nullable datatypes, you can do something like this:
var t = things.Where(x => x!=null && x.Value.ID == long.Parse(options.ID)).FirstOrDefault();
var res = t == null ? "" : t.Value;
It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.
However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.
Perhaps have a look at http://www.plupload.com/ - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c.
Blazemonger's reply (above or below) needs voting up - but I don't have enough points.
I wanted to add a grey bar across some 20px wide CSS round buttons to indicate "not available" and tweaked Blazemonger's css:
.round_btn:after {
content:""; /* required property */
position: absolute;
top: 6px;
left: -1px;
border-top: 6px solid rgba(170,170,170,0.65);
height: 6px;
width: 19px;
}
#include <string.h>
#include <stdio.h>
int main()
{
int a,l;
char str[50],str1[50],str3[100];
printf("\nEnter a string: ");
scanf("%s",str);
str3[0]='\0';
printf("\nEnter the string which you want to concat with string one: ");
scanf("%s",str1);
strcat(str3,str);
strcat(str3,str1);
printf("\nThe string is %s\n",str3);
}
Have you tried setOnFocusChangeListener
? Within the handler, you could change the text appearance.
For instance:
TextView text = (TextView)findViewById(R.id.text);
text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
((TextView)v).setXXXX();
} else {
((TextView)v).setXXXX();
}
}
});
You can then apply whatever changes you want when it's focused or not. You can also use the ViewTreeObserver to listen for Global focus changes.
For instance:
View all = findViewById(R.id.id_of_top_level_view_on_layout);
ViewTreeObserver vto = all.getViewTreeObserver();
vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
public void onGlobalFocusChanged(
View oldFocus, View newFocus) {
// xxxx
}
});
I hope this helps or gives you ideas.
You can use expandtabs
to specify the tabstop, like this:
>>> print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1'.expandtabs(30))
>>> print ('District: Tower'+'\t'+ 'Date: May 16, 2012'.expandtabs(30))
#Output:
Location:10-10-10-10 Revision: 1
District: Tower Date: May 16, 2012
For me it's Enterprise Architect from Sparx Systems. A very rounded UML tool for a very reasonable price.
Very strong feature list including: integrated project management, baselining, export/import (including export to html), documentation generation from the model, various templates (Zachman, TOGAF, etc.), IDE plugins, code generation (with IDE plugins available for Visual Studio, Eclipse & others), automation API - the list goes on.
Oh yeah, don't forget support for source control directly from inside the tool (SVN, CVS, TFS & SCC).
I would also stay away from Visio - you only get diagrams, not a model. Rename a class in one place in a UML modelling tool and you rename in all places. This is not the case in Visio!
var last_selected:IndexPath!
define last_selected:IndexPath inside the class
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! Cell
cell.contentView.backgroundColor = UIColor.lightGray
cell.txt.textColor = UIColor.red
if(last_selected != nil){
//deselect
let deselect_cell = tableView.cellForRow(at: last_selected) as! Cell
deselect_cell.contentView.backgroundColor = UIColor.white
deselect_cell.txt.textColor = UIColor.black
}
last_selected = indexPath
}
I would simply delete from schema_version the migration/s that deviates from migrations to be applied. This way you don't throw away any test data that you might have.
For example:
SELECT * from schema_version order by installed_on desc
V_005_five.sql
V_004_four.sql
V_003_three.sql
V_002_two.sql
V_001_one.sql
Migrations to be applied
V_005_five.sql
* V_004_addUserTable.sql *
V_003_three.sql
V_002_two.sql
V_001_one.sql
Solution here is to delete from schema_version
V_005_five.sql
V_004_four.sql
AND revert any database changes caused. for example if schema created new table then you must drop that table before you run you migrations.
when you run flyway it will only re apply
V_005_five.sql
* V_004_addUserTable.sql *
new schema_version will be
V_005_five.sql
* V_004_addUserTable.sql *
V_003_three.sql
V_002_two.sql
V_001_one.sql
Hope it helps
For example 1 and 2 you need to create static methods:
public static string InstanceMethod() {return "Hello World";}
Then for example 3 you need an instance of your object to invoke the method:
object o = new object();
string s = o.InstanceMethod();
Stop mysql completely.
mysql.server stop
<-- may need editing based on your versionps -ef | grep mysql
<-- lists processes with mysql in their namekill [PID]
<-- kill the processes by PIDRemove files. Instructions above are good. I'll add:
sudo find /. -name "*mysql*"
rm -rf
these files. Note that many programs have drivers for mysql which you do not want to remove. For example, don't delete stuff in a PHP install's directory. Do remove stuff in its own mysql directory.Hopefully you have homebrew. If not, download it.
I like to run brew as root, but I don't think you have to. Edit 2018: you can't run brew as root anymore
sudo brew update
sudo brew install cmake
<-- dependency for mysql, usefulsudo brew install openssl
<-- dependency for mysql, usefulsudo brew info mysql
<-- skim through this... it gives you some idea of what's coming nextsudo brew install mysql --with-embedded; say done
<-- Installs mysql with the embedded server. Tells you when it finishes (my install took 10 minutes)sudo chown -R mysql /usr/local/var/mysql/
<-- mysql wouldn't work for me until I ran this commandsudo mysql.server start
<-- once again, the exact syntax may varyIt's just common stuff for making cin input work faster.
For a quick explanation: the first line turns off buffer synchronization between the cin stream and C-style stdio tools (like scanf or gets) — so cin works faster, but you can't use it simultaneously with stdio tools.
The second line unties cin from cout — by default the cout buffer flushes each time when you read something from cin. And that may be slow when you repeatedly read something small then write something small many times. So the line turns off this synchronization (by literally tying cin to null instead of cout).
C++17 (upcoming standard) changes the synopsis of the template basic_string
adding a non const overload of data()
:
charT* data() noexcept;
Returns: A pointer p such that p + i == &operator for each i in [0,size()].
CharT const *
from std::basic_string<CharT>
std::string const cstr = { "..." };
char const * p = cstr.data(); // or .c_str()
CharT *
from std::basic_string<CharT>
std::string str = { "..." };
char * p = str.data();
CharT const *
from std::basic_string<CharT>
std::string str = { "..." };
str.c_str();
CharT *
from std::basic_string<CharT>
From C++11 onwards, the standard says:
- The char-like objects in a
basic_string
object shall be stored contiguously. That is, for anybasic_string
objects
, the identity&*(s.begin() + n) == &*s.begin() + n
shall hold for all values ofn
such that0 <= n < s.size()
.
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
Returns:
*(begin() + pos)
ifpos < size()
, otherwise a reference to an object of typeCharT
with valueCharT()
; the referenced value shall not be modified.
const charT* c_str() const noexcept;
const charT* data() const noexcept;
Returns: A pointer p such that
p + i == &operator[](i)
for eachi
in[0,size()]
.
There are severable possible ways to get a non const character pointer.
std::string foo{"text"};
auto p = &*foo.begin();
Pro
Cons
'\0'
is not to be altered / not necessarily part of the non-const memory.std::vector<CharT>
std::string foo{"text"};
std::vector<char> fcv(foo.data(), foo.data()+foo.size()+1u);
auto p = fcv.data();
Pro
Cons
std::array<CharT, N>
if N
is compile time constant (and small enough)std::string foo{"text"};
std::array<char, 5u> fca;
std::copy(foo.data(), foo.data()+foo.size()+1u, fca.begin());
Pro
Cons
std::string foo{ "text" };
auto p = std::make_unique<char[]>(foo.size()+1u);
std::copy(foo.data(), foo.data() + foo.size() + 1u, &p[0]);
Pro
Cons
std::string foo{ "text" };
char * p = nullptr;
try
{
p = new char[foo.size() + 1u];
std::copy(foo.data(), foo.data() + foo.size() + 1u, p);
// handle stuff with p
delete[] p;
}
catch (...)
{
if (p) { delete[] p; }
throw;
}
Pro
Con
Of course you could write a program that monitors the clipboard and displays an annoying SaveAs-dialog for every image in the clipboard ;-). I guess you can even find out if the last key pressed was PrintScreen to limit the number of false positives.
While I'm thinking about it.. you could also google for someone who already did exactly that.
EDIT: .. or just wait for someone to post the source here - as just happend :-)
The same error is produced in MariaDB (10.1.36-MariaDB) by using the combination of parenthesis and the COLLATE statement. My SQL was different, the error was the same, I had:
SELECT *
FROM table1
WHERE (field = 'STRING') COLLATE utf8_bin;
Omitting the parenthesis was solving it for me.
SELECT *
FROM table1
WHERE field = 'STRING' COLLATE utf8_bin;
Without single quotes around it, you are creating an array with two objects inside of it. This is JavaScript's own syntax. When you add the quotes, that object (array+2 objects) is now a string. You can use JSON.parse
to convert a string into a JavaScript object. You cannot use JSON.parse
to convert a JavaScript object into a JavaScript object.
//String - you can use JSON.parse on it
var jsonStringNoQuotes = '[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]';
//Already a javascript object - you cannot use JSON.parse on it
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
Furthermore, your last example fails because you are adding literal single quote characters to the JSON string. This is illegal. JSON specification states that only double quotes are allowed. If you were to console.log
the following...
console.log("'"+[{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}]+"'");
//Logs:
'[object Object],[object Object]'
You would see that it returns the string representation of the array, which gets converted to a comma separated list, and each list item would be the string representation of an object, which is [object Object]
. Remember, associative arrays in javascript are simply objects with each key/value pair being a property/value.
Why does this happen? Because you are starting with a string "'"
, then you are trying to append the array to it, which requests the string representation of it, then you are appending another string "'"
.
Please do not confuse JSON with Javascript, as they are entirely different things. JSON is a data format that is humanly readable, and was intended to match the syntax used when creating javascript objects. JSON is a string. Javascript objects are not, and therefor when declared in code are not surrounded in quotes.
See this fiddle: http://jsfiddle.net/NrnK5/
Essentially random access file wraps input and output streams in order to manage the random access. You don't open and close a file, you open and close streams to a file.
you use the scrollTop attribute
var position = document.getElementById('id').scrollTop;
In the RC you can also extract route data like the action method name like this
ViewContext.Controller.ValueProvider["action"].RawValue
ViewContext.Controller.ValueProvider["controller"].RawValue
ViewContext.Controller.ValueProvider["id"].RawValue
ViewContext.Controller.ValueProvider.GetValue("action").RawValue
ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
ViewContext.Controller.ValueProvider.GetValue("id").RawValue
ViewContext.Controller.RouteData.Values["action"]
ViewContext.Controller.RouteData.Values["controller"]
ViewContext.Controller.RouteData.Values["id"]
ViewContext.RouteData.Values["action"]
ViewContext.RouteData.Values["controller"]
ViewContext.RouteData.Values["id"]
You have the :nth-child()
pseudo-class:
table tr:nth-child(odd) td{
...
}
table tr:nth-child(even) td{
...
}
In the early days of :nth-child()
its browser support was kind of poor. That's why setting class="odd"
became such a common technique. In late 2013 I'm glad to say that IE6 and IE7 are finally dead (or sick enough to stop caring) but IE8 is still around — thankfully, it's the only exception.