I talk about what \b
-style regex boundaries actually are here.
The short story is that they’re conditional. Their behavior depends on what they’re next to.
# same as using a \b before:
(?(?=\w) (?<!\w) | (?<!\W) )
# same as using a \b after:
(?(?<=\w) (?!\w) | (?!\W) )
Sometimes that isn’t what you want. See my other answer for elaboration.
Use word boundaries:
/\b($word)\b/i
Or if you're searching for "S.P.E.C.T.R.E." like in Sinan Ünür's example:
/(?:\W|^)(\Q$word\E)(?:\W|$)/i
I had the same issue. I just closed and reopened the terminal, and it worked. That was because I installed anaconda with the terminal open.
I know it is old but according to my own theme editor with default light theme, default
textPrimaryColor = #000000
and
textColorPrimaryDark = #757575
I think it's asking you to do this:
SELECT ID
FROM (SELECT ID,
msisdn
FROM (SELECT * FROM TT2) as myalias
) as anotheralias;
But why would you write this query in the first place?
I had to delete all the rows and did it with the next script:
DECLARE @Nombre NVARCHAR(MAX);
DECLARE curso CURSOR FAST_FORWARD
FOR
Select Object_name(object_id) AS Nombre from sys.objects where type = 'U'
OPEN curso
FETCH NEXT FROM curso INTO @Nombre
WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF (@@FETCH_STATUS <> -2)
BEGIN
DECLARE @statement NVARCHAR(200);
SET @statement = 'DELETE FROM ' + @Nombre;
print @statement
execute sp_executesql @statement;
END
FETCH NEXT FROM curso INTO @Nombre
END
CLOSE curso
DEALLOCATE curso
Hope this helps!
I clear my screen using is function that
var clear_body = function (){
var lista = document.body.childNodes;
for (var i = lista.length - 1; i >= 0 ;i--){
document.body.removeChild(lista[i])
}
}
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
CMD doesn't have time arithmetic. The following code, however gives a workaround:
set vid_time=11:07:48
set srt_time=11:16:58
REM Get time difference
set length=%vid_time%
for /f "tokens=1-3 delims=:" %i in ("%length%") do (
set /a h=%i*3600
set /a m=%j*60
set /a s=%k
)
set /a t1=!h!+!m!+!s!
set length=%srt_time%
for /f "tokens=1-3 delims=:" %i in ("%length%") do (
set /a h=%i*3600
set /a m=%j*60
set /a s=%k
)
set /a t2=!h!+!m!+!s!
cls
set /a diff=!t2!-!t1!
Above code gives difference in seconds. To display in hh:mm:ss format, code below:
set ss=!diff!
set /a hh=!ss!/3600 >nul
set /a mm="(!ss!-3600*!hh!)/60" >nul
set /a ss="(!ss!-3600*!hh!)-!mm!*60" >nul
set "hh=0!hh!" & set "mm=0!mm!" & set "ss=0!ss!"
echo|set /p=!hh:~-2!:!mm:~-2!:!ss:~-2!
The problem in your code is that you want to apply the operation on every row. The way you've written it though takes the whole 'bar' and 'foo' columns, converts them to strings and gives you back one big string. You can write it like:
df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
It's longer than the other answer but is more generic (can be used with values that are not strings).
In response to MK_Dev, one is able to iterate, but not consecutively (for that, obviously an array is needed).
A quick Google search brings up hash tables in JavaScript.
Example code for looping over values in a hash (from the aforementioned link):
var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
// Show the values stored
for (var i in myArray) {
alert('key is: ' + i + ', value is: ' + myArray[i]);
}
In Objective-C, a @synchronized
block handles locking and unlocking (as well as possible exceptions) automatically for you. The runtime dynamically essentially generates an NSRecursiveLock that is associated with the object you're synchronizing on. This Apple documentation explains it in more detail. This is why you're not seeing the log messages from your NSLock subclass — the object you synchronize on can be anything, not just an NSLock.
Basically, @synchronized (...)
is a convenience construct that streamlines your code. Like most simplifying abstractions, it has associated overhead (think of it as a hidden cost), and it's good to be aware of that, but raw performance is probably not the supreme goal when using such constructs anyway.
A bit late to the party but I use my tried and trusted JS that takes advantage of Modernizr. Can be copy/pasted and applied to any project. Works every time:
// Placeholder fallback
if(!Modernizr.input.placeholder){
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}
conftest
solutionThe least invasive solution is adding an empty file named conftest.py
in the repo/
directory:
$ touch repo/conftest.py
That's it. No need to write custom code for mangling the sys.path
or remember to drag PYTHONPATH
along, or placing __init__.py
into dirs where it doesn't belong (using python -m pytest
as suggested in Apteryx's answer is a good solution though!).
The project directory afterwards:
repo
+-- conftest.py
+-- app.py
+-- settings.py
+-- models.py
+-- tests
+-- test_app.py
pytest
looks for the conftest
modules on test collection to gather custom hooks and fixtures, and in order to import the custom objects from them, pytest
adds the parent directory of the conftest.py
to the sys.path
(in this case the repo
directory).
If you have other project structure, place the conftest.py
in the package root dir (the one that contains packages but is not a package itself, so does not contain an __init__.py
), for example:
repo
+-- conftest.py
+-- spam
¦ +-- __init__.py
¦ +-- bacon.py
¦ +-- egg.py
+-- eggs
¦ +-- __init__.py
¦ +-- sausage.py
+-- tests
+-- test_bacon.py
+-- test_egg.py
src
layoutAlthough this approach can be used with the src
layout (place conftest.py
in the src
dir):
repo
+-- src
¦ +-- conftest.py
¦ +-- spam
¦ ¦ +-- __init__.py
¦ ¦ +-- bacon.py
¦ ¦ +-- egg.py
¦ +-- eggs
¦ +-- __init__.py
¦ +-- sausage.py
+-- tests
+-- test_bacon.py
+-- test_egg.py
beware that adding src
to PYTHONPATH
mitigates the meaning and benefits of the src
layout! You will end up with testing the code from repository and not the installed package. If you need to do it, maybe you don't need the src
dir at all.
Of course, conftest
modules are not just some files to help the source code discovery; it's where all the project-specific enhancements of the pytest
framework and the customization of your test suite happen. pytest
has a lot of information on conftest
modules scattered throughout their docs; start with conftest.py
: local per-directory plugins
Also, SO has an excellent question on conftest
modules: In py.test, what is the use of conftest.py files?
I am using XAMPP and came across the same error. I had done all those steps, added environmental variables path, copied the dll's every directory possible, to /php, /apache/bin, /system32, /syswow64, etc.. but still got this error.
Then after checking the apache error log, I noticed the issue with using brackets in path.
PHP: syntax error, unexpected '(' in C:\Program Files (other)\xampp\php\php.ini on line 707 0 server certificate does NOT include an ID which matches the server name
If you have installed the server in "Program Files (x86)" directory, the same error might occur due to the non-escaped brackets.
To fix this, open php.ini file and locate the line containing "include_path" and enclose the path with double quotes to fix this error.
include_path="C:\Program Files (other)\xampp\php\PEAR"
It is worth noting that despite the fact that you can SELECT INTO
global variables like:
SELECT ... INTO @XYZ ...
You can NOT use FETCH INTO
global variables like:
FETCH ... INTO @XYZ
Looks like it's not a bug. I hope it will be helpful to someone...
If you need a PEM file without any password you can use this solution.
Just copy and paste the private key and the certificate to the same file and save as .pem.
The file will look like:
-----BEGIN PRIVATE KEY-----
............................
............................
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
...........................
...........................
-----END CERTIFICATE-----
That's the only way I found to upload certificates to Cisco devices for HTTPS.
theString.substring(theString.length() - 2)
try:
foreach (var item in chlCompanies.CheckedItems){
item.Value //ID
item.Text //CompanyName
}
tar.exe -acf out.zip in.txt
out.zip is an output folder or filename and in.txt is an input folder or filename. To use this command you should be in the file existing folder.
This worked for me
$sql = 'INSERT INTO table(pk_pk1,pk_pk2,date,pk_3) VALUES ';
$qPart = array_fill(0, count($array), "(?, ?,UTC_TIMESTAMP(),?)");
$sql .= implode(",", $qPart);
$stmt = DB::prepare('base', $sql);
$i = 1;
foreach ($array as $value) {
$stmt->bindValue($i++, $value);
$stmt->bindValue($i++, $pk_pk1);
$stmt->bindValue($i++, $pk_pk2);
$stmt->bindValue($i++, $pk_pk3);
}
$stmt->execute();
With Python 3.6, sometimes I still run into this problem. For example, when getting response from a REST API and loading the response text to JSON, I still get the unicode strings. Found a simple solution using json.dumps().
response_message = json.loads(json.dumps(response.text))
print(response_message)
As @Sean said, fcntl()
is largely standardized, and therefore available across platforms. The ioctl()
function predates fcntl()
in Unix, but is not standardized at all. That the ioctl()
worked for you across all the platforms of relevance to you is fortunate, but not guaranteed. In particular, the names used for the second argument are arcane and not reliable across platforms. Indeed, they are often unique to the particular device driver that the file descriptor references. (The ioctl()
calls used for a bit-mapped graphics device running on an ICL Perq running PNX (Perq Unix) of twenty years ago never translated to anything else anywhere else, for example.)
What you are looking for is merging.
git merge master
With pull
you fetch changes from a remote repository and merge them into the current branch.
You need to create the instance of the RuntimeException, using new
the same way you would to create an instance of most other classes:
throw new RuntimeException(msg);
Here is another good link to refer to. http://csharpindepth.com/Articles/Chapter2/Events.aspx
Briefly, the take away from the article - Events are encapsulation over delegates.
Quote from article:
Suppose events didn't exist as a concept in C#/.NET. How would another class subscribe to an event? Three options:
A public delegate variable
A delegate variable backed by a property
A delegate variable with AddXXXHandler and RemoveXXXHandler methods
Option 1 is clearly horrible, for all the normal reasons we abhor public variables.
Option 2 is slightly better, but allows subscribers to effectively override each other - it would be all too easy to write someInstance.MyEvent = eventHandler; which would replace any existing event handlers rather than adding a new one. In addition, you still need to write the properties.
Option 3 is basically what events give you, but with a guaranteed convention (generated by the compiler and backed by extra flags in the IL) and a "free" implementation if you're happy with the semantics that field-like events give you. Subscribing to and unsubscribing from events is encapsulated without allowing arbitrary access to the list of event handlers, and languages can make things simpler by providing syntax for both declaration and subscription.
As something of an aside, MAXDOP can apparently be used as a workaround to a potentially nasty bug:
You could just style the input element in your css file. That is then independent of ASP.NET.
<form action="">
Name: <input type="text" class="input" />
Password: <input type="password" class="input" />
<input type="submit" value="Submit" class="button" />
</form>
CSS
.input {
border: 1px solid #006;
background: #ffc;
}
.button {
border: 1px solid #006;
background: #9cf;
}
With the CssClass
you can assign the "input"
class to it.
Also I want notice that if you want to check whether the type of a variable is a specific kind, you can compare the type of the variable to the type of a known object.
For string you can use this
type(s) == type('')
Modern processors are too fast to register the running time. Hence it may return zero. In this case, the time you started and ended is too small and therefore both the times are the same after round of.
See a better answer below: https://stackoverflow.com/a/10054088/308315
Old answer:
First, in your AppDelegate .h file:
#import <AVFoundation/AVFoundation.h>
@interface AppDelegate : NSObject <UIApplicationDelegate> {
AVCaptureSession *torchSession;
}
@property (nonatomic, retain) AVCaptureSession * torchSession;
@end
Then in your AppDelegate .m file:
@implementation AppDelegate
@synthesize torchSession;
- (void)dealloc {
[torchSession release];
[super dealloc];
}
- (id) init {
if ((self = [super init])) {
// initialize flashlight
// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
if (device.torchMode == AVCaptureTorchModeOff) {
NSLog(@"Setting up flashlight for later use...");
AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
AVCaptureSession *session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
[device lockForConfiguration:nil];
[session addInput:flashInput];
[session addOutput:output];
[device unlockForConfiguration];
[output release];
[session commitConfiguration];
[session startRunning];
[self setTorchSession:session];
[session release];
}
}
}
}
return self;
}
Then anytime you want to turn it on, just do something like this:
// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[device lockForConfiguration:nil];
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
[device unlockForConfiguration];
}
And similar for turning it off:
// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[device lockForConfiguration:nil];
[device setTorchMode:AVCaptureTorchModeOff];
[device setFlashMode:AVCaptureFlashModeOff];
[device unlockForConfiguration];
}
This is implementation dependent, as the C standard does NOT define the signed-ness of char
. Depending on the platform, char may be signed
or unsigned
, so you need to explicitly ask for signed char
or unsigned char
if your implementation depends on it. Just use char
if you intend to represent characters from strings, as this will match what your platform puts in the string.
The difference between signed char
and unsigned char
is as you'd expect. On most platforms, signed char
will be an 8-bit two's complement number ranging from -128
to 127
, and unsigned char
will be an 8-bit unsigned integer (0
to 255
). Note the standard does NOT require that char
types have 8 bits, only that sizeof(char)
return 1
. You can get at the number of bits in a char with CHAR_BIT
in limits.h
. There are few if any platforms today where this will be something other than 8
, though.
There is a nice summary of this issue here.
As others have mentioned since I posted this, you're better off using int8_t
and uint8_t
if you really want to represent small integers.
I would definitely use:
try
{
//some code
}
catch
{
//you should totally do something here, but feel free to rethrow
//if you need to send the exception up the stack.
throw;
}
That will preserve your stack.
Try Case
SELECT stock.name,
CASE
WHEN stock.quantity <20 THEN 'Buy urgent'
ELSE 'There is enough'
END
FROM stock
I am facing problems with composer because it consumes all the available memory, and then, the process get killed ( actualy, the output message is "Killed")
So, I was looking for a solution to limit composer memory usage.
I tried ( from @Sven answers )
$ php -d memory_limit=512M /usr/local/bin/composer update
But it didn't work because
"Composer internally increases the memory_limit to 1.5G."
-> Thats from composer oficial website.
Then I found a command that works :
$ COMPOSER_MEMORY_LIMIT=512M php composer.phar update
Althought, in my case 512mb is not enough !
Source : https://www.agileana.com/blog/composer-memory-limit-troubleshooting/
I found a little known but amazingly cool way to do it from Payette's Windows Powershell in Action. You can reference files like variables, similar to $env:path, but you need to add the curly braces.
${c:file.txt} = ${c:file.txt} -replace 'oldvalue','newvalue'
Try
\d \w |\d
or add a positive lookahead if you don't want to include the trailing space in the match
\d \w(?= )|\d
When you have two alternatives where one is an extension of the other, put the longer one first, otherwise it will have no opportunity to be matched.
If you add this to your web.config transformation file, you can also set certain publish options to have debugging enabled or disabled:
<system.web>
<customErrors mode="Off" defaultRedirect="~/Error.aspx" xdt:Transform="Replace"/>
</system.web>
res = request.GET['paymentid']
will raise a KeyError
if paymentid
is not in the GET data.
Your sample php code checks to see if paymentid
is in the POST data, and sets $payID
to '' otherwise:
$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''
The equivalent in python is to use the get()
method with a default argument:
payment_id = request.POST.get('payment_id', '')
while debugging, this is what I see in the
response.GET: <QueryDict: {}>
,request.POST: <QueryDict: {}>
It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.
Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.
Java does not allow abstract variables and/or constructor definitions in interfaces. Solution: Simply hang an abstract class between your interface and your implementation which only extends the abstract class like so:
public interface IMyClass {
void methodA();
String methodB();
Integer methodC();
}
public abstract class myAbstractClass implements IMyClass {
protected String varA, varB;
//Constructor
myAbstractClass(String varA, String varB) {
this.varA = varA;
this.varB = VarB;
}
//Implement (some) interface methods here or leave them for the concrete class
protected void methodA() {
//Do something
}
//Add additional methods here which must be implemented in the concrete class
protected abstract Long methodD();
//Write some completely new methods which can be used by all subclasses
protected Float methodE() {
return 42.0;
}
}
public class myConcreteClass extends myAbstractClass {
//Constructor must now be implemented!
myClass(String varA, String varB) {
super(varA, varB);
}
//All non-private variables from the abstract class are available here
//All methods not implemented in the abstract class must be implemented here
}
You can also use an abstract class without any interface if you are SURE that you don't want to implement it along with other interfaces later. Please note that you can't create an instance of an abstract class you MUST extend it first.
(The "protected" keyword means that only extended classes can access these methods and variables.)
spyro
Use Following Method to Update GUI.
Public Void UpdateUI()
{
//Here update your label, button or any string related object.
//Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
}
Keep it in Mind when you use this method at that time do not Update same object direct from dispatcher thread otherwise you get only that updated string and this method is helpless/useless. If still not working then Comment that line inside method and un-comment commented one both have nearly same effect just different way to access it.
Just use a bytearray
(Python 2.6 and later) which represents a mutable sequence of bytes
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')
Indexing get and sets the individual bytes
>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')
and if you need it as a str
(or bytes
in Python 3), it's as simple as
>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'
This isn't the prettiest way to do it, but in my opinion, it's the best way.
def loop():
while True:
#snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y": return
if ok == "n" or ok == "N": break
#do more processing with menus and stuff
I'm pretty sure you could work out something using recursion here as well, but I don't know if that's a good option for you.
$("#bchange").click(function() {
$("body, this").css("background-color","yellow");
});
Encountered a similar problem today. Did not see my fix listed here, so I thought I'd share.
Root could not erase a file.
I did my research. Turns out there's something called an immutable bit.
# lsattr /path/file
----i-------- /path/file
#
This bit being configured prevents even root from modifying/removing it.
To remove this I did:
# chattr -i /path/file
After that I could rm the file.
In reverse, it's a neat trick to know if you have something you want to keep from being gone.
:)
The eval
function will evaluate a string that is passed to it.
But the use of eval
can be dangerous, so use with caution.
Edit: annakata has a good point -- Not only is eval
dangerous, it is slow. This is because the code to be evaluated must be parsed on the spot, so that will take some computing resources.
Java 9
public static void main(String[] args) {
Map<Integer,String> map = Map.ofEntries(entry(1,"A"), entry(2,"B"), entry(3,"C"));
}
The main answer worked for me but made the app extremely unresponsive in IE, so I used a timer as suggested. Code looks something like this ($(#contentColumn)
is the div that the JQGrid sits in):
function resizeGrids() {
var reportObjectsGrid = $("#ReportObjectsGrid");
reportObjectsGrid.setGridWidth($("#contentColumn").width());
};
var resizeTimer;
$(window).bind('resize', function () {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(resizeGrids, 60);
});
JS (in your AngularJS controller)
$scope.range = new Array(MAX_REPEATS); // set MAX_REPEATS to the most repetitions you will ever need in a single ng-repeat that makes use of this strategy
HTML
<div ng-repeat="i in range.slice(0,repeatCount) track by $index"></div>
...where repeatCount
is the number of repetitions that should appear in this location.
This is an old thread but I stumbled onto second highest answer (custom listeners) while looking for a solution using Angular. While the solution works, angular has a better built in way to resolve this using @Output
and event emitters. Going off of the example in custom listener answer:
ChildComponent.html
<button (click)="increment(1)">Increment</button>
ChildComponent.ts
import {EventEmitter, Output } from '@angular/core';
@Output() myEmitter: EventEmitter<number> = new EventEmitter<number>();
private myValue: number = 0;
public increment(n: number){
this.myValue += n;
// Send a change event to the emitter
this.myEmitter.emit(this.myValue);
}
ParentComponent.html
<child-component (myEmitter)="monitorChanges($event)"></child-component>
<br/>
<label>{{n}}</label>
ParentComponent.ts
public n: number = 0;
public monitorChanges(n: number){
this.n = n;
console.log(n);
}
This will now update n
on parent each time the child button is clicked. Working stackblitz
Although Martijin's answer is prob best. Here is a more intuitive way to process large csv files for beginners. This allows you to process groups of rows, or chunks, at a time.
import pandas as pd
chunksize = 10 ** 8
for chunk in pd.read_csv(filename, chunksize=chunksize):
process(chunk)
As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.
You need to wrap your .myTestClass
inside an element and apply the styles to descendants by adding .wrapper *
descendant selector. Then, add .myTestClass > *
child selector to apply the style to the elements children, not its grand children. For example like this:
JSFiddle - DEMO
.wrapper * {_x000D_
color: blue;_x000D_
margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
color:red;_x000D_
margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="myTestClass">Text 0_x000D_
<div>Text 1</div>_x000D_
<span>Text 1</span>_x000D_
<div>Text 1_x000D_
<p>Text 2</p>_x000D_
<div>Text 2</div>_x000D_
</div>_x000D_
<p>Text 1</p>_x000D_
</div>_x000D_
<div>Text 0</div>_x000D_
</div>
_x000D_
EDIT: I had not realized this was about the data format. You could use
import pandas as pd
import scipy
two_data = pd.DataFrame(data, index=data['Category'])
Then accessing the categories is as simple as
scipy.stats.ttest_ind(two_data.loc['cat'], two_data.loc['cat2'], equal_var=False)
The loc operator
accesses rows by label.
one sided or two sided dependent or independent
If you have two independent samples but you do not know that they have equal variance, you can use Welch's t-test. It is as simple as
scipy.stats.ttest_ind(cat1['values'], cat2['values'], equal_var=False)
For reasons to prefer Welch's test, see https://stats.stackexchange.com/questions/305/when-conducting-a-t-test-why-would-one-prefer-to-assume-or-test-for-equal-vari.
For two dependent samples, you can use
scipy.stats.ttest_rel(cat1['values'], cat2['values'])
Here's one approach. By default the radio buttons were about twice as large as labels.
(See CSS and HTML code at end of answer)
Safari: 10.0.3
Chrome: 56.0.2924.87
Firefox: 50.1.0
Internet Explorer: 9
(Fuzziness not IE's fault, hosted test on netrenderer.com)
CSS:
.sortOptions > label {
font-size: 8px;
}
.sortOptions > input[type=radio] {
width: 10px;
height: 10px;
}
HTML:
<div class="rightColumn">Answers
<span class="sortOptions">
<input type="radio" name="answerSortList" value="credate"/>
<label for="credate">Creation</label>
<input type="radio" name="answerSortList" value="lastact"/>
<label for="lastact">Activity</label>
<input type="radio" name="answerSortList" value="score"/>
<label for="score">Score</label>
<input type="radio" name="answerSortList" value="upvotes"/>
<label for="upvotes">Up votes</label>
<input type="radio" name="answerSortList" value="downvotes"/>
<label for="downvotes">Down Votes</label>
<input type="radio" name="answerSortList" value="accepted"/>
<label for="downvotes">Accepted</label>
</span>
</div>
I suggest the NavUtils.navigateUpFromSameTask(), it's easy and very simple, you can learn it from the google developer.Wish I could help you!
Include the script from dhtmlgoodies and initialize like this:
<input type="text" name="myText" value="Norway"
selectBoxOptions="Canada;Denmark;Finland;Germany;Mexico">
createEditableSelect(document.forms[0].myText);
Here's a custom solution which combines a <select>
element and <input>
element, styles them, and toggles back and forth via JavaScript
<div style="position:relative;width:200px;height:25px;border:0;padding:0;margin:0;">
<select style="position:absolute;top:0px;left:0px;width:200px; height:25px;line-height:20px;margin:0;padding:0;"
onchange="document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
<option></option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
<input type="text" name="displayValue" id="displayValue"
placeholder="add/select a value" onfocus="this.select()"
style="position:absolute;top:0px;left:0px;width:183px;width:180px\9;#width:180px;height:23px; height:21px\9;#height:18px;border:1px solid #556;" >
<input name="idValue" id="idValue" type="hidden">
</div>
Regular expression is the most effective way of checking for a domain validation. If you're dead set on not using a Regular Expression (which IMO is stupid), then you could split each part of a domain:
You would then have to check each character in some sort of a loop to see that it matches a valid domain.
Like I said, it's much more effective to use a regular expression.
Dang this is hard. Here is what I did to reject/delete/replace my ios build before it was released. The app was approved how ever I found found a bug I wanted to fix before releasing
To replace the bad build I did the following
To replace from the right:
def replace_right(source, target, replacement, replacements=None):
return replacement.join(source.rsplit(target, replacements))
In use:
>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'
You can get value of id,name or value in this way. class name my_class
var id_value = $('.my_class').$(this).attr('id'); //get id value
var name_value = $('.my_class').$(this).attr('name'); //get name value
var value = $('.my_class').$(this).attr('value'); //get value any input or tag
You can cast your JToken
to a JObject
and then use the Properties()
method to get a list of the object properties. From there, you can get the names rather easily.
Something like this:
string json =
@"{
""ADDRESS_MAP"":{
""ADDRESS_LOCATION"":{
""type"":""separator"",
""name"":""Address"",
""value"":"""",
""FieldID"":40
},
""LOCATION"":{
""type"":""locations"",
""name"":""Location"",
""keyword"":{
""1"":""LOCATION1""
},
""value"":{
""1"":""United States""
},
""FieldID"":41
},
""FLOOR_NUMBER"":{
""type"":""number"",
""name"":""Floor Number"",
""value"":""0"",
""FieldID"":55
},
""self"":{
""id"":""2"",
""name"":""Address Map""
}
}
}";
JToken outer = JToken.Parse(json);
JObject inner = outer["ADDRESS_MAP"].Value<JObject>();
List<string> keys = inner.Properties().Select(p => p.Name).ToList();
foreach (string k in keys)
{
Console.WriteLine(k);
}
Output:
ADDRESS_LOCATION
LOCATION
FLOOR_NUMBER
self
Applying a selector from the .nav-tabs
seems to be working:
See this demo.
$(document).ready(function(){
activaTab('aaa');
});
function activaTab(tab){
$('.nav-tabs a[href="#' + tab + '"]').tab('show');
};
I would prefer @codedme's answer, since if you know which tab you want prior to page load, you should probably change the page html and not use JS for this particular task.
I tweaked the demo for his answer, as well.
(If this is not working for you, please specify your setting - browser, environment, etc.)
If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:
_x000D_
var dateformat = /^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/;
_x000D_
Use form-inline
.
It only works on screen resolutions greater than 768px though. To test the snippet below make sure to click the "Expand snippet" link to get a wider viewing area.
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>_x000D_
<form class="form-inline">_x000D_
<input type="text" class="form-control"/>-<input type="text" class="form-control"/>_x000D_
</form>
_x000D_
Reference: https://getbootstrap.com/docs/3.3/css/#forms-inline
You could use the Morpha stemmer. UW has uploaded morpha stemmer to Maven central if you plan to use it from a Java application. There's a wrapper that makes it much easier to use. You just need to add it as a dependency and use the edu.washington.cs.knowitall.morpha.MorphaStemmer
class. Instances are threadsafe (the original JFlex had class fields for local variables unnecessarily). Instantiate a class and run morpha
and the word you want to stem.
new MorphaStemmer().morpha("climbed") // goes to "climb"
In general:
FileInputStream
for the file.InputStreamReader
wrapping the input stream, specifying the correct encodingBufferedReader
around the InputStreamReader
, which makes it simpler to read a line at a time.readLine
returns null)If you need more help than that, please be more specific in your question.
For HTML5, you can use the 'hidden' attribute.
<option hidden>Hidden option</option>
It is not supported by IE < 11. But if you need only to hide a few elements, maybe it would be better to just set the hidden attribute in combination with disabled in comparison to adding/removing elements or doing not semantically correct constructions.
<select> _x000D_
<option>Option1</option>_x000D_
<option>Option2</option>_x000D_
<option hidden>Hidden Option</option>_x000D_
</select>
_x000D_
In the case of Maven project
Try right click on the project then select Maven -> Update Project...
then Ok
.img-responsive {
margin: 0 auto;
}
you can write like above code in your document so no need to add one another class in image tag.
void inPlaceStrTrim(char* str) {
int k = 0;
int i = 0;
for (i=0; str[i] != '\0';) {
if (isspace(str[i])) {
// we have got a space...
k = i;
for (int j=i; j<strlen(str)-1; j++) {
str[j] = str[j+1];
}
str[strlen(str)-1] = '\0';
i = k; // start the loop again where we ended..
} else {
i++;
}
}
}
Step 1: Simply put all the required code in a "MAIN.BAT" file.
Step 2: Create another bat file, say MainCaller.bat, and just copy/paste these 3 lines of code:
REM THE MAIN FILE WILL BE CALLED FROM HERE..........
CD "File_Path_Where_Main.bat_is_located"
MAIN.BAT > log.txt
Step 3: Just double click "MainCaller.bat".
All the output will be logged into the text file named "log".
Thanks to @K. Shahzad This helps when you want the rewrited query string without any rewrite additions. Let say you rewrite the /test/?x=y to index.php?q=test&x=y and you want only want the query string.
function get_query_string(){
$arr = explode("?",$_SERVER['REQUEST_URI']);
if (count($arr) == 2){
return "";
}else{
return "?".end($arr)."<br>";
}
}
$query_string = get_query_string();
On changing the values of the source data, chart was not getting updated accordingly. Just closed all instances of excel and restarted, problem disappeared.
I would recommend giving the LI
a background-image
and padding-left
. The list-style-image
attribute is flakey in cross-browser environments, and adding an extra element, such as a span, is unneccessary. So your code would end up looking something like this:
li {
background:url(../images/bullet.png) 0 0 no-repeat;
list-style:none;
padding-left:10px;
}
This should work, since your state will change after the Ajax call, and the parent component will re-render.
render : function () {
var item;
if (this.state.isRequired) {
item = <MyOwnInput attribute={'whatever'} />
} else {
item = <MyOwnInput />
}
return (
<div>
{item}
</div>
);
}
Make sure that you're using the same Servlet API specification that your Web container supports. Refer to this chart if you're using Tomcat: http://tomcat.apache.org/whichversion.html
The Web container that you use will definitely have the API jars you require.
Tomcat 6 for example has it in apache-tomcat-6.0.26/lib/servlet-api.jar
Think of Web service as a web api. API is such a general term now so a web service is an interface to functionality, usually business related, that you can get to from the network over a variety of protocols.
Good evening,
The previous clues to get SQLManagementStudio_x64_ENU.exe runing didn't work as stated for me. After a while of searching, trying, retrying again and again, I finally figured it out. When executing SQLManagementStudio_x64_ENU.exe on my Windows seven system, I kept runing into compatibility issues. The trick is to run SQLManagementStudio_x64_ENU.exe in compatibility mode with Windows XP SP2. Edit the installer properties and enable compatibility mode with XP (service pack 2), then you'll be able to access Mr Doug (answered Mar 4 at 15:09) resolution.
Cheers.
Fiddled around with the Bakudan's code and other code in stackoverflow to get everything in one.
Update #1 : Added more options. Now Start, pause, resume, reset and restart. Mix the functions to get desired results.
Update #2 : Edited out previously used JQuery codes for pure JS and added as code snippet.
For previous Jquery based fiddle version : https://jsfiddle.net/wizajay/rro5pna3/305/
var Clock = {_x000D_
totalSeconds: 0,_x000D_
start: function () {_x000D_
if (!this.interval) {_x000D_
var self = this;_x000D_
function pad(val) { return val > 9 ? val : "0" + val; }_x000D_
this.interval = setInterval(function () {_x000D_
self.totalSeconds += 1;_x000D_
_x000D_
document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));_x000D_
document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));_x000D_
}, 1000);_x000D_
}_x000D_
},_x000D_
_x000D_
reset: function () {_x000D_
Clock.totalSeconds = null; _x000D_
clearInterval(this.interval);_x000D_
document.getElementById("min").innerHTML = "00";_x000D_
document.getElementById("sec").innerHTML = "00";_x000D_
delete this.interval;_x000D_
},_x000D_
pause: function () {_x000D_
clearInterval(this.interval);_x000D_
delete this.interval;_x000D_
},_x000D_
_x000D_
resume: function () {_x000D_
this.start();_x000D_
},_x000D_
_x000D_
restart: function () {_x000D_
this.reset();_x000D_
Clock.start();_x000D_
}_x000D_
};_x000D_
_x000D_
_x000D_
document.getElementById("startButton").addEventListener("click", function () { Clock.start(); });_x000D_
document.getElementById("pauseButton").addEventListener("click", function () { Clock.pause(); });_x000D_
document.getElementById("resumeButton").addEventListener("click", function () { Clock.resume(); });_x000D_
document.getElementById("resetButton").addEventListener("click", function () { Clock.reset(); });_x000D_
document.getElementById("restartButton").addEventListener("click", function () { Clock.restart(); });
_x000D_
<span id="min">00</span>:<span id="sec">00</span>_x000D_
_x000D_
<input id="startButton" type="button" value="Start">_x000D_
<input id="pauseButton" type="button" value="Pause">_x000D_
<input id="resumeButton" type="button" value="Resume">_x000D_
<input id="resetButton" type="button" value="Reset">_x000D_
<input id="restartButton" type="button" value="Restart">
_x000D_
You can use slice assignment if the original list must be modified, while still using an efficient list comprehension (or generator expression).
>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> x[:] = (value for value in x if value != 2)
>>> x
[1, 3, 4, 3]
You can close the current window just by using the following code:
Application.Current.Windows[0].Close();
<body>
<marquee direction="left" behavior=scroll scrollamount="2">This is basic example of marquee</marquee>
<marquee direction="up">The direction of text will be from bottom to top.</marquee>
</body>
use scrollamount to control speed..
You can use the @RequestHeader
annotation with HttpHeaders
method parameter to gain access to all request headers:
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
// Use headers to get the information about all the request headers
long contentLength = headers.getContentLength();
// ...
StreamSource source = new StreamSource(new StringReader(body));
YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
// ...
}
Please try this. This query can be used for date comparison
select * from [User] U where convert(varchar(10),U.DateCreated, 120) = '2014-02-07'
I am not a big fan of if...else; so I took a simpler approach.
$(document).ready(function(event) {
$('ul.nav.nav-tabs a:first').tab('show'); // Select first tab
$('ul.nav.nav-tabs a[href="'+ window.location.hash+ '"]').tab('show'); // Select tab by name if provided in location hash
$('ul.nav.nav-tabs a[data-toggle="tab"]').on('shown', function (event) { // Update the location hash to current tab
window.location.hash= event.target.hash;
})
});
Doesn't address scrolling to requested hash; but should it?
Query to Find the date difference between 2 rows of a single column
SELECT
Column name,
DATEDIFF(
(SELECT MAX(date) FROM table name WHERE Column name < b. Column name),
Column name) AS days_since_last
FROM table name AS b
I do this frequently using Table Types to ensure more consistency and simplify code. You can't technically return "a table", but you can return a result set and using INSERT INTO .. EXEC ...
syntax, you can clearly call a PROC and store the results into a table type. In the following example I'm actually passing a table into a PROC along with another param I need to add logic, then I'm effectively "returning a table" and can then work with that as a table variable.
/****** Check if my table type and/or proc exists and drop them ******/
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'returnTableTypeData')
DROP PROCEDURE returnTableTypeData
GO
IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'myTableType')
DROP TYPE myTableType
GO
/****** Create the type that I'll pass into the proc and return from it ******/
CREATE TYPE [dbo].[myTableType] AS TABLE(
[someInt] [int] NULL,
[somenVarChar] [nvarchar](100) NULL
)
GO
CREATE PROC returnTableTypeData
@someInputInt INT,
@myInputTable myTableType READONLY --Must be readonly because
AS
BEGIN
--Return the subset of data consistent with the type
SELECT
*
FROM
@myInputTable
WHERE
someInt < @someInputInt
END
GO
DECLARE @myInputTableOrig myTableType
DECLARE @myUpdatedTable myTableType
INSERT INTO @myInputTableOrig ( someInt,somenVarChar )
VALUES ( 0, N'Value 0' ), ( 1, N'Value 1' ), ( 2, N'Value 2' )
INSERT INTO @myUpdatedTable EXEC returnTableTypeData @someInputInt=1, @myInputTable=@myInputTableOrig
SELECT * FROM @myUpdatedTable
DROP PROCEDURE returnTableTypeData
GO
DROP TYPE myTableType
GO
With a simple JSON object, you don't need jQuery:
for (var i in json) {
for (var j in json[i]) {
console.log(json[i][j]);
}
}
Yes, they are very different in theory, and in implementation.
Lexers are used to recognize "words" that make up language elements, because the structure of such words is generally simple. Regular expressions are extremely good at handling this simpler structure, and there are very high-performance regular-expression matching engines used to implement lexers.
Parsers are used to recognize "structure" of a language phrases. Such structure is generally far beyond what "regular expressions" can recognize, so one needs "context sensitive" parsers to extract such structure. Context-sensitive parsers are hard to build, so the engineering compromise is to use "context-free" grammars and add hacks to the parsers ("symbol tables", etc.) to handle the context-sensitive part.
Neither lexing nor parsing technology is likely to go away soon.
They may be unified by deciding to use "parsing" technology to recognize "words", as is currently explored by so-called scannerless GLR parsers. That has a runtime cost, as you are applying more general machinery to what is often a problem that doesn't need it, and usually you pay for that in overhead. Where you have lots of free cycles, that overhead may not matter. If you process a lot of text, then the overhead does matter and classical regular expression parsers will continue to be used.
In short, a Service is a broader implementation for the developer to set up background operations, while an IntentService is useful for "fire and forget" operations, taking care of background Thread creation and cleanup.
From the docs:
Service A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
IntentService
Service is a base class for IntentService Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent)
calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
Refer this doc - http://developer.android.com/reference/android/app/IntentService.html
EOF means end of file. It's a sign that the end of a file is reached, and that there will be no data anymore.
Edit:
I stand corrected. In this case it's not an end of file. As mentioned, it is passed when CTRL+d (linux) or CTRL+z (windows) is passed.
Not sure why they removed the option to just right click on the database and restore like you could in SQL Server Management Studio 2008 and earlier, but as mentioned above you can restore from a .BAK
file with:
RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBaackUpFile.bak' WITH REPLACE
But you will want WITH REPLACE
instead of WITH RESTORE
if your moving it from one server to another.
How about
sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub
Try this
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Range("A" & i & ":" & "Z" & i)
Else
Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
IF you want to delete the entire row then use this code
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Rows(i)
Else
Set DelRange = Union(DelRange, Rows(i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
Use any number of times, to revert back to the last commit without deleting any files that you have recently created.
git reset --soft HEAD~1
Then use
git reset HEAD <name-of-file/files*>
to unstage, or untrack.
This applies if you are using it with an authguard
this.router.events.subscribe(event => {
if(event instanceof NavigationStart){
console.log('this is what your looking for ', event.url);
}
}
);
you can run something like this (paste the code bellow in a .bat, or if you want it to run interractively replace the %%
by %
:
for %%i in (c:\directory\*.xls) do ssconvert %%i %%i.xlsx
If you can run powershell it will be :
Get-ChildItem -Path c:\directory -filter *.xls | foreach {ssconvert $($_.FullName) $($_.baseName).xlsx }
new Date().toString();
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
Dateformatter can make it to any string you want
From the man read:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
Input parameters:
int fd
file descriptor is an integer and not a file pointer. The file descriptor for stdin
is 0
void *buf
pointer to buffer to store characters read by the read
function
size_t count
maximum number of characters to read
So you can read character by character with the following code:
char buf[1];
while(read(0, buf, sizeof(buf))>0) {
// read() here read from stdin charachter by character
// the buf[0] contains the character got by read()
....
}
Take a look at this tutorial on MDN: https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas (archived)
Alternate Link (2019) : https://reference.codeproject.com/book/dom/canvas_api/drawing_dom_objects_into_a_canvas
It uses a temporary SVG image to include the HTML content as a "foreign element", then renders said SVG image into a canvas element. There are significant restrictions on what you can include in an SVG image in this way, however. (See the "Security" section for details.)
I had the same problem. I tried to create a table in mysql and got the same error. I restarted mysql server and ran the command and was able to create/migrate table after restating.
If your form tag is like
<form action="" method="post" id="BookPackageForm">
Then fetch the form element by using forms object.
var formEl = document.forms.BookPackageForm;
Get the data from the form by using FormData objects.
var formData = new FormData(formEl);
Get the value of the fields by the form data object.
var name = formData.get('name');
You need to add a reference to your class library from your project. Right click on the references folder and click add reference. You can either browse for the DLL or, if your class libaray is a project in your solution you can add a project reference.
Also check if You don't change alpha on that view. I am investigating issue when i change alpha on some views, with elevation. They simply loose elevation when alpha is changed and changed back to 1f.
For Bootstrap 4 beta, sample navbar with elements aligned to the right side is:
<div id="app" class="container">
<nav class="navbar navbar-expand-md navbar-light bg-faded">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Navbar</a>
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricingg</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{{ url('/login') }}">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url('/register') }}">Register</a>
</li>
</ul>
</nav>
</div>
method 1 using ChildRef
:
public childRef: any = React.createRef<Hello>();
public onButtonClick= () => {
console.log(this.childRef.current); // this will have your child reference
}
<Hello ref = { this.childRef }/>
<button onclick="onButtonClick()">Click me!</button>
Method 2: using window register
public onButtonClick= () => {
console.log(window.yourRef); // this will have your child reference
}
<Hello ref = { (ref) => {window.yourRef = ref} }/>`
<button onclick="onButtonClick()">Click me!</button>
You can use PDFtoText https://github.com/jalan/pdftotext
PDF to text keeps text format indentation, doesn't matter if you have tables.
public static Bitmap decodeFile(String path) {
Bitmap b = null;
File f = new File(path);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int IMAGE_MAX_SIZE = 1024; // maximum dimension limit
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
public static Bitmap showBitmapFromFile(String file_path)
{
try {
File imgFile = new File(file_path);
if(imgFile.exists()){
Bitmap pic_Bitmap = decodeFile(file_path);
return pic_Bitmap;
}
} catch (Exception e) {
MyLog.e("Exception showBitmapFromFile");
return null;
}
return null;
}
if you are using image loading in List view then use Aquery concept .
https://github.com/AshishPsaini/AqueryExample
AQuery aq= new AQuery((Activity) activity, convertView);
//load image from file, down sample to target width of 250 pixels .gi
File file=new File("//pic/path/here/aaaa.jpg");
if(aq!=null)
aq.id(holder.pic_imageview).image(file, 250);
Webkit's support for scrollbars is quite sophisticated. This CSS gives a very minimal scrollbar, with a light grey track and a darker thumb:
::-webkit-scrollbar
{
width: 12px; /* for vertical scrollbars */
height: 12px; /* for horizontal scrollbars */
}
::-webkit-scrollbar-track
{
background: rgba(0, 0, 0, 0.1);
}
::-webkit-scrollbar-thumb
{
background: rgba(0, 0, 0, 0.5);
}
This answer is a fantastic source of additional information.
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@drawable/YOUR DRAWABLE XML" />
<item android:drawable="@drawable/YOUR DRAWABLE XML" />
</selector>
The Collection interface includes the toArray() method to convert a new collection into an array. There are two forms of this method. The no argument version will return the elements of the collection in an Object array: public Object[ ] toArray(). The returned array cannot cast to any other data type. This is the simplest version. The second version requires you to pass in the data type of the array you’d like to return: public Object [ ] toArray(Object type[ ]).
public static void main(String[] args) {
List<String> l=new ArrayList<String>();
l.add("A");
l.add("B");
l.add("C");
Object arr[]=l.toArray();
for(Object a:arr)
{
String str=(String)a;
System.out.println(str);
}
}
for reference, refer this link http://techno-terminal.blogspot.in/2015/11/how-to-obtain-array-from-arraylist.html
I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!
$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news);
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
}
else {
echo $news;
}
(.* word1.* word2.* )|(.* word2.* word1.*)
Dan, it's just you're accessing the protected field instead of properties.
See for example this line in your Main(...)
:
myClub.distance = Console.ReadLine();
myClub.distance
is the protected field, while you wanted to set the property mydistance.
I'm just giving you some hint, I'm not going to correct your code, since this is homework! ;)
This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:
>>> df[condition]
This will return a slice of your dataframe which you can index using iloc
. Here are your examples:
Get first row where A > 3 (returns row 2)
>>> df[df.A > 3].iloc[0]
A 4
B 6
C 3
Name: 2, dtype: int64
If what you actually want is the row number, rather than using iloc
, it would be df[df.A > 3].index[0]
.
Get first row where A > 4 AND B > 3:
>>> df[(df.A > 4) & (df.B > 3)].iloc[0]
A 5
B 4
C 5
Name: 4, dtype: int64
Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)
>>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
A 4
B 6
C 3
Name: 2, dtype: int64
Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:
>>> def series_or_default(X, condition, default_col, ascending=False):
... sliced = X[condition]
... if sliced.shape[0] == 0:
... return X.sort_values(default_col, ascending=ascending).iloc[0]
... return sliced.iloc[0]
>>>
>>> series_or_default(df, df.A > 6, 'A')
A 5
B 4
C 5
Name: 4, dtype: int64
As expected, it returns row 4.
Although the original post had other issues (i.e. the missing "-d"), the error message is more generic.
curl: (3) [globbing] nested braces not supported at pos X
This is because curly braces {} and square brackets [] are special globbing characters in curl. To turn this globbing off, use the "-g" option.
As an example, the following Solr facet query will fail without the "-g" to turn off curl globbing:
curl -g 'http://localhost:8983/solr/query?json.facet={x:{terms:"myfield"}}'
Another reason this could be happening is if you are using an iframe that has the sandbox attribute and allow-same-origin
isn't set e.g.:
// page.html
<iframe id="f" src="http://localhost:8000/iframe.html" sandbox="allow-scripts"></iframe>
<script type="text/javascript">
var f = document.getElementById("f").contentWindow;
// will throw exception
f.postMessage("hello world!", 'http://localhost:8000');
</script>
// iframe.html
<script type="text/javascript">
window.addEventListener("message", function(event) {
console.log(event);
}, false);
</script>
I haven't found a solution other than:
f.postMessage("hello world!", '*');
Based on the solution by Jason Bunting, here is what I use now.
The whole thing is for the jQuery tablesorter plug-in: For (nearly correct) sorting of non-English tables with tablesorter plugin it is necessary to make use of a custom textExtraction
function.
This one:
'dd.mm.yyyy'
) to a recognized format ('yyyy-mm-dd'
)Be careful to save the JavaScript file in UTF-8 encoding or it won't work.
// file encoding must be UTF-8!
function getTextExtractor()
{
return (function() {
var patternLetters = /[öäüÖÄÜáàâéèêúùûóòôÁÀÂÉÈÊÚÙÛÓÒÔß]/g;
var patternDateDmy = /^(?:\D+)?(\d{1,2})\.(\d{1,2})\.(\d{2,4})$/;
var lookupLetters = {
"ä": "a", "ö": "o", "ü": "u",
"Ä": "A", "Ö": "O", "Ü": "U",
"á": "a", "à": "a", "â": "a",
"é": "e", "è": "e", "ê": "e",
"ú": "u", "ù": "u", "û": "u",
"ó": "o", "ò": "o", "ô": "o",
"Á": "A", "À": "A", "Â": "A",
"É": "E", "È": "E", "Ê": "E",
"Ú": "U", "Ù": "U", "Û": "U",
"Ó": "O", "Ò": "O", "Ô": "O",
"ß": "s"
};
var letterTranslator = function(match) {
return lookupLetters[match] || match;
}
return function(node) {
var text = $.trim($(node).text());
var date = text.match(patternDateDmy);
if (date)
return [date[3], date[2], date[1]].join("-");
else
return text.replace(patternLetters, letterTranslator);
}
})();
}
You can use it like this:
$("table.sortable").tablesorter({
textExtraction: getTextExtractor()
});
Simply Add 'carousel-item' class in place of item class.
I found this below function for comparing objects.
static bool Compare<T>(T Object1, T object2)
{
//Get the type of the object
Type type = typeof(T);
//return false if any of the object is false
if (object.Equals(Object1, default(T)) || object.Equals(object2, default(T)))
return false;
//Loop through each properties inside class and get values for the property from both the objects and compare
foreach (System.Reflection.PropertyInfo property in type.GetProperties())
{
if (property.Name != "ExtensionData")
{
string Object1Value = string.Empty;
string Object2Value = string.Empty;
if (type.GetProperty(property.Name).GetValue(Object1, null) != null)
Object1Value = type.GetProperty(property.Name).GetValue(Object1, null).ToString();
if (type.GetProperty(property.Name).GetValue(object2, null) != null)
Object2Value = type.GetProperty(property.Name).GetValue(object2, null).ToString();
if (Object1Value.Trim() != Object2Value.Trim())
{
return false;
}
}
}
return true;
}
I am using it and it is working fine for me.
DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.
$xml = new DOMDocument();
$xml_album = $xml->createElement("Album");
$xml_track = $xml->createElement("Track");
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
$xml->save("/tmp/test.xml");
To re-open and write:
$xml = new DOMDocument();
$xml->load('/tmp/test.xml');
$nodes = $xml->getElementsByTagName('Album') ;
if ($nodes->length > 0) {
//insert some stuff using appendChild()
}
//re-save
$xml->save("/tmp/test.xml");
You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:
function PersonListCtrl($scope, $http) {
$scope.loadData = function () {
$http.get('/persons').success(function(data) {
$scope.persons = data;
});
};
//initial load
$scope.loadData();
}
then in your markup
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="loadData()">Refresh</button>
</div>
As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:
for example (just puedo code) in your controller:
$scope.addPerson = function() {
$scope.persons.push({ name: 'Test Monkey' });
};
Then you could use that in your view or whatever you'd want to do.
Little addition, to run an interpreter from the same folder, still using #!hashbang in scripts.
As example a php7.2 executable copied from /usr/bin is in a folder along a hello script.
#!./php7.2
<?php
echo "Hello!";
To run it:
./hello
Which behave just as equal as:
./php7.2 hello
The proper solutions with good documentation can be the tools linuxdeploy and/or appimage, this is using this method under the hood.
I assume you want to change values inside a query so you could write a function for it
void DoStuff()
{
Func<string, Foo, bool> test = (y, x) => { x.Bar = y; return true; };
List<Foo> mylist = new List<Foo>();
var v = from x in mylist
where test("value", x)
select x;
}
class Foo
{
string Bar { get; set; }
}
But not shure if this is what you mean.
Adding a custom hard-coded header may work (it also may get rejected at times) but it is totally the wrong way to do it. The purpose of the WSSE is security. Microsoft released the Microsoft Web Services Enhancements 2.0 and subsequently the WSE 3.0 for this exact reason. You need to install this package (http://www.microsoft.com/en-us/download/details.aspx?id=14089).
The documentation is not easy to understand, especially for those who have not worked with SOAP and the WS-Addressing. First of all the "BasicHttpBinding" is Soap 1.1 and it will not give you the same message header as the WSHttpBinding. Install the package and look at the examples. You will need to reference the DLL from WSE 3.0 and you will also need to setup your message correctly. There are a huge number or variations on the WS Addressing header. The one you are looking for is the UsernameToken configuration.
This is a longer explanation and I should write something up for everyone since I cannot find the right answer anywhere. At a minimum you need to start with the WSE 3.0 package.
This scenario is not so common in real-world programming, but not so strange too. It happens sometimes that two classes in different packages have same name and we need both of them.
It is not mandatory that if two classes have same name, then both will contain same functionalities and we should pick only one of them.
If we need both, then there is no harm in using that. And it's not a bad programming idea too.
But we should use fully qualified names of the classes (that have same name) in order to make it clear which class we are referring too.
:)
The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.
CONTIGUOUS NON-PRINTING Ruby Code
This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml
, etc.
This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>
DETAILS:
Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:
<%# if flash[:myErrors] %>
<%# if flash[:myErrors].any? %>
<%# if @post.id.nil? %>
<%# if @myPost!=-1 %>
<%# @post = @myPost %>
<%# else %>
<%# @post = Post.new %>
<%# end %>
<%# end %>
<%# end %>
<%# end %>
YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:
<%#
if flash[:myErrors] then
if flash[:myErrors].any? then
if @post.id.nil? then
if @myPost!=-1 then
@post = @myPost
else
@post = Post.new
end
end
end
end
%>
First: I assumed you already have Python 2.7 or 3.4 installed.
1: In the Control Panel, open the System option (alternately, you can right-click on My Computer and select Properties). Select the “Advanced system settings” link.
In the System Properties dialog, click “Environment Variables”.
In the Environment Variables dialog, click the New button underneath the “System variables” section.
if someone is there that above is not working, then kindly append to your PATH with the C:\Python27 then it should surely work. C:\Python27\Scripts
Run this command (Windows cmd terminal): pip install virtualenv
If you already have pip, you can upgrade them by running:
pip install --upgrade pip setuptools
Create your project. Then, run virtualenv flask
AS per my study in css place always inside .like:-
<head>
<link href="css/grid.css" rel="stylesheet" />
</head>
and for script its depen :-
Though it is answered above and it is right to use
<meta name="viewport" content="width=device-width, initial-scale=1">
but if you are using React and webpack then don't forget to close the element tag
<meta name="viewport" content="width=device-width, initial-scale=1" />
I have used wire shark tool for monitoring service calls from silver light app in browser to service. try the link gives clear info
It enables you to monitor the whole request and response contents.
Are you using standards mode? This solution depends on it I think.
If you're trying to make 2 columns you could do something like this:
<div id="outer">
<div id="left">
sidebar
</div>
<div id="main">
lorem ispsum etc...
</div>
</div>
Then use CSS to style it:
div#outer
{
width:100%;
height: 500px;
}
div#left
{
width: 100px;
height: 100%;
float:left;
background: green;
}
div#main
{
width: auto;
margin-left: 100px; /* same as div#left width */
height: 100%;
background:red;
}
If you don't want 2 columns you can probably remove <div id="left">
Sometimes if there's no any application associated with geo: protocal , you could use try-catch to get the ActivityNotFoundException to handle it.
It happens when you use some emulator like androVM which is not installed google map by default.
As described by others, a fast and also space efficient solution is using numpy (np) with it's built-in vector manipulation capability:
1. With Numpy
x = np.array([1,2,3])
y = np.array([2,3,4])
print x+y
2. With built-ins
2.1 Lambda
list1=[1, 2, 3]
list2=[4, 5, 6]
print map(lambda x,y:x+y, list1, list2)
Notice that map() supports multiple arguments.
2.2 zip and list comprehension
list1=[1, 2, 3]
list2=[4, 5, 6]
print [x + y for x, y in zip(list1, list2)]
For survivorship bias free data, the only reliable source I have found is QuantQuote (http://quantquote.com)
Data comes in minute, second, or tick resolution, link to their historical stock data.
There was a suggestion for kibot above. I would do a quick google search before buying from them, you'll find lots posts like this with warnings about kibot data quality problems. It is also telling that their supposedly survivorship bias free sp500 only has 570 symbols for 14 years. That's pretty much impossible, sp500 changes by 1-2 symbols per month....
you can use sort()
, limit()
,skip()
to get last N record start from any skipped value
db.collections.find().sort(key:value).limit(int value).skip(some int value);
I received the error "Unable to allocate memory for pool" after moving an OpenCart installation to a different server. I also tried raising the memory_limit.
The error stopped after I changed the permissions of the file in the error message to have write access by the user that apache runs as (apache, www-data, etc.). Instead of modifying /etc/group directly (or chmod-ing the files to 0777), I used usermod:
usermod -a -G vhost-user-group apache-user
Then I had to restart apache for the change to take effect:
apachectl restart
Or
sudo /etc/init.d/httpd restart
Or whatever your system uses to restart apache.
If the site is on shared hosting, maybe you must change the file permissions with an FTP program, or contact the hosting provider?
I could not find an appropriate answer to the question. There looks to be no solution to disable the specific tab. What I did is to pass the specific tab to a variable and in SelectedIndexChanged
event put it back to SelectedIndex
:
//variable for your specific tab
int _TAB = 0;
//here you specify your tab that you want to expose
_TAB = 1;
tabHolder.SelectedIndex = _TAB;
private void tabHolder_SelectedIndexChanged(object sender, EventArgs e)
{
if (_TAB != 0) tabHolder.SelectedIndex = _TAB;
}
So, you don't actually disable the tab, but when another tab is clicked it always returns you to the selected tab.
To add one more item to Spinner you can:
ArrayAdapter myAdapter =
((ArrayAdapter) mySpinner.getAdapter());
myAdapter.add(myValue);
myAdapter.notifyDataSetChanged();
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
ORDER_BY cast(registration_no as unsigned) ASC
explicitly converts the value to a number. Another possibility to achieve the same would be
ORDER_BY registration_no + 0 ASC
which will force an implicit conversation.
Actually you should check the table definition and change it. You can change the data type to int
like this
ALTER TABLE your_table MODIFY COLUMN registration_no int;
If you know you're always going to use bash, it's much easier to always use the double bracket conditional compound command [[ ... ]]
, instead of the Posix-compatible single bracket version [ ... ]
. Inside a [[ ... ]]
compound, word-splitting and pathname expansion are not applied to words, so you can rely on
if [[ $aug1 == "and" ]];
to compare the value of $aug1
with the string and
.
If you use [ ... ]
, you always need to remember to double quote variables like this:
if [ "$aug1" = "and" ];
If you don't quote the variable expansion and the variable is undefined or empty, it vanishes from the scene of the crime, leaving only
if [ = "and" ];
which is not a valid syntax. (It would also fail with a different error message if $aug1
included white space or shell metacharacters.)
The modern [[
operator has lots of other nice features, including regular expression matching.
You can use the cd
builtin, or the pushd
and popd
builtins for this purpose. For example:
# do something with /etc as the working directory
cd /etc
:
# do something with /tmp as the working directory
cd /tmp
:
You use the builtins just like any other command, and can change directory context as many times as you like in a script.
Map:- This method takes one Function as an argument and returns a new stream consisting of the results generated by applying the passed function to all the elements of the stream.
Let's imagine, I have a list of integer values ( 1,2,3,4,5 ) and one function interface whose logic is square of the passed integer. ( e -> e * e ).
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> newList = intList.stream().map( e -> e * e ).collect(Collectors.toList());
System.out.println(newList);
output:-
[1, 4, 9, 16, 25]
As you can see, an output is a new stream whose values are square of values of the input stream.
[1, 2, 3, 4, 5] -> apply e -> e * e -> [ 1*1, 2*2, 3*3, 4*4, 5*5 ] -> [1, 4, 9, 16, 25 ]
http://codedestine.com/java-8-stream-map-method/
FlatMap :- This method takes one Function as an argument, this function accepts one parameter T as an input argument and returns one stream of parameter R as a return value. When this function is applied to each element of this stream, it produces a stream of new values. All the elements of these new streams generated by each element are then copied to a new stream, which will be a return value of this method.
Let's image, I have a list of student objects, where each student can opt for multiple subjects.
List<Student> studentList = new ArrayList<Student>();
studentList.add(new Student("Robert","5st grade", Arrays.asList(new String[]{"history","math","geography"})));
studentList.add(new Student("Martin","8st grade", Arrays.asList(new String[]{"economics","biology"})));
studentList.add(new Student("Robert","9st grade", Arrays.asList(new String[]{"science","math"})));
Set<Student> courses = studentList.stream().flatMap( e -> e.getCourse().stream()).collect(Collectors.toSet());
System.out.println(courses);
output:-
[economics, biology, geography, science, history, math]
As you can see, an output is a new stream whose values are a collection of all the elements of the streams return by each element of the input stream.
[ S1 , S2 , S3 ] -> [ {"history","math","geography"}, {"economics","biology"}, {"science","math"} ] -> take unique subjects -> [economics, biology, geography, science, history, math]
Assuming this is for a C# project and assuming that you want to change the default namespace, you need to go to Project Properties, Application tab, and specify "Default Namespace".
Default namespace is the namespace that Visual studio sets when you create a new class. Next time you do Right Click > Add > Class it would use the namespace you specified in the above step.
if you dont want call filename.py
you can add .PY
to the PATHEXT, that way you will just call filename
gmdate("H:i:s", no_of_seconds);
Will not give time in H:i:s
format if no_of_seconds
is greater than 1 day (seconds in a day).
It will neglect day value and give only Hour:Min:Seconds
For example:
gmdate("H:i:s", 89922); // returns 0:58:42 not (1 Day 0:58:42) or 24:58:42
For databases that have a high number of tables you can use a simple php script to update the charset of the database and all of the tables using the following:
$conn = mysqli_connect($host, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$alter_database_charset_sql = "ALTER DATABASE ".$database." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
mysqli_query($conn, $alter_database_charset_sql);
$show_tables_result = mysqli_query($conn, "SHOW TABLES");
$tables = mysqli_fetch_all($show_tables_result);
foreach ($tables as $index => $table) {
$alter_table_sql = "ALTER TABLE ".$table[0]." CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci";
$alter_table_result = mysqli_query($conn, $alter_table_sql);
echo "<pre>";
var_dump($alter_table_result);
echo "</pre>";
}
While you can use a virtualenv
, you don't need to. The trick is passing the PEP370 --user
argument to the setup.py
script. With the latest version of pip
, one way to do it is:
pip install --user mercurial
This should result in the hg
script being installed in $HOME/.local/bin/hg
and the rest of the hg package in $HOME/.local/lib/pythonx.y/site-packages/
.
Note, that the above is true for Python 2.6. There has been a bit of controversy among the Python core developers about what is the appropriate directory location on Mac OS X for PEP370-style user
installations. In Python 2.7 and 3.2, the location on Mac OS X was changed from $HOME/.local
to $HOME/Library/Python
. This might change in a future release. But, for now, on 2.7 (and 3.2, if hg
were supported on Python 3), the above locations will be $HOME/Library/Python/x.y/bin/hg
and $HOME/Library/Python/x.y/lib/python/site-packages
.
This is much easier than you're making it. The text node will not have the literal string " "
in it, it'll have have the corresponding character with code 160.
function replaceNbsps(str) {
var re = new RegExp(String.fromCharCode(160), "g");
return str.replace(re, " ");
}
textNode.nodeValue = replaceNbsps(textNode.nodeValue);
UPDATE
Even easier:
textNode.nodeValue = textNode.nodeValue.replace(/\u00a0/g, " ");
I found that functions cannot be written in ~/.cshrc
file. Here in alias which takes arguments
for example, arguments passed to 'find' command
alias fl "find . -name '\!:1'"
Ex: >fl abc
where abc is the argument passed as !:1
The error you have is because -credential
without -computername
can't exist.
You can try this way:
Invoke-Command -Credential $migratorCreds -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show and hide div with JavaScript</title>
<script>
var button_beg = '<button id="button" onclick="showhide()">', button_end = '</button>';
var show_button = 'Show', hide_button = 'Hide';
function showhide() {
var div = document.getElementById( "hide_show" );
var showhide = document.getElementById( "showhide" );
if ( div.style.display !== "none" ) {
div.style.display = "none";
button = show_button;
showhide.innerHTML = button_beg + button + button_end;
} else {
div.style.display = "block";
button = hide_button;
showhide.innerHTML = button_beg + button + button_end;
}
}
function setup_button( status ) {
if ( status == 'show' ) {
button = hide_button;
} else {
button = show_button;
}
var showhide = document.getElementById( "showhide" );
showhide.innerHTML = button_beg + button + button_end;
}
window.onload = function () {
setup_button( 'hide' );
showhide(); // if setup_button is set to 'show' comment this line
}
</script>
</head>
<body>
<div id="showhide"></div>
<div id="hide_show">
<p>This div will be show and hide on button click</p>
</div>
</body>
</html>
I'm using out of the box MVC4 with this code (note the two parameters inside ToDictionary
)
var result = new JsonResult()
{
Data = new
{
partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
}
};
I get what's expected:
{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}
Important: WebAPI in MVC4 uses JSON.NET serialization out of the box, but the standard web JsonResult
action result doesn't. Therefore I recommend using a custom ActionResult to force JSON.NET serialization. You can also get nice formatting
Here's a simple actionresult JsonNetResult
http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx
You'll see the difference (and can make sure you're using the right one) when serializing a date:
Microsoft way:
{"wireTime":"\/Date(1355627201572)\/"}
JSON.NET way:
{"wireTime":"2012-12-15T19:07:03.5247384-08:00"}
This format is used to get current timestamp and stored in mysql
$date = date("Y-m-d H:i:s");
$update_query = "UPDATE db.tablename SET insert_time=".$date." WHERE username='" .$somename . "'";
The easiest correct way to convert JS Date to SQL datetime format that occur to me is this one. It correctly handles timezone offset.
const toSqlDatetime = (inputDate) => {
const date = new Date(inputDate)
const dateWithOffest = new Date(date.getTime() - (date.getTimezoneOffset() * 60000))
return dateWithOffest
.toISOString()
.slice(0, 19)
.replace('T', ' ')
}
toSqlDatetime(new Date()) // 2019-08-07 11:58:57
toSqlDatetime(new Date('2016-6-23 1:54:16')) // 2016-06-23 01:54:16
Beware that @Paulo Roberto answer will produce incorrect results at the turn on new day (i can't leave comments). For example:
var d = new Date('2016-6-23 1:54:16'),
finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
console.log(finalDate); // 2016-06-22 01:54:16
We've got 22 June instead of 23!
If Symfony 4 or 5, juste use this code (Where name is the name of your field):
$request->request->get('name');
for simple Scroll, use following style
height: 200px; overflow: scroll;
and use this style class which div or section you want to show scroll
Calculate the length of your text line and create a block which is the same size as the line of text. Center the block. If you have two lines you will need two blocks if they are different lengths. You could use a span tag and a br tag if you don't want extra spaces from the blocks. You can also use the pre tag to format inside a block.
And you can do this: style='text-align:center;'
For vertical see: http://www.w3schools.com/cssref/pr_pos_vertical-align.asp
Here is the best way for blocks and web page layouts, go here and learn flex the new standard which started in 2009. http://www.w3.org/TR/2014/WD-css-flexbox-1-20140325/#justify-content-property
Also w3schools has lots of flex examples.
There are pre-release (beta) versions of NCover available for free. They work fine for most cases, especially when combined with NCoverExplorer.
The regex into selected answer fail for Unicode: 0x1d (with php 7.4)
a solution:
<?php
$ct = 'différents'."\r\n test";
// fail for Unicode: 0x1d
$ct = preg_replace('/[\x00-\x1F\x7F]$/u', '',$ct);
// work for Unicode: 0x1d
$ct = preg_replace( '/[^\P{C}]+/u', "", $ct);
// work for Unicode: 0x1d and allow line break
$ct = preg_replace( '/[^\P{C}\n]+/u', "", $ct);
echo $ct;
from: UTF 8 String remove all invisible characters except newline
Use-
<span ng-bind-html="myContent"></span>
You need to tell angular to not escape it.
I was having this problem but i found out that it was a permissions problem I changed my permissions to 0744 and now it works. I don't know if this was your problem but it worked for me.
echo
adds spaces between the arguments passed to it. $text
is subject to variable expansion and word splitting, so your echo
command is equivalent to:
echo -e "this" "is" "line" "one\n" "this" "is" "line" "two\n" ...
You can see that a space will be added before "this". You can either remove the newline characters, and quote $text
to preserve the newlines:
text="this is line one
this is line two
this is line three"
echo "$text" > filename
Or you could use printf
, which is more robust and portable than echo
:
printf "%s\n" "this is line one" "this is line two" "this is line three" > filename
In bash
, which supports brace expansion, you could even do:
printf "%s\n" "this is line "{one,two,three} > filename
Google Guava Libraries collection provides such function:
Iterator<String> it = Iterators.forArray(array);
One should prefere Guava over the Apache Collection (which seems to be abandoned).
INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)
I know this question has already been answered. However, for those using spring boot, this link helped me - https://smarterco.de/java-load-file-classpath-spring-boot/
However, the resourceLoader.getResource("classpath:file.txt").getFile();
was causing this problem and sbk's comment:
That's it. A java.io.File represents a file on the file system, in a directory structure. The Jar is a java.io.File. But anything within that file is beyond the reach of java.io.File. As far as java is concerned, until it is uncompressed, a class in jar file is no different than a word in a word document.
helped me understand why to use getInputStream()
instead. It works for me now!
Thanks!
import csv
with open('file_name.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(('colum1', 'colum2', 'colum3'))
for key, value in dictionary.items():
writer.writerow([key, value[0], value[1]])
This would be the simplest way to write data to .csv file
Take a look at Google Play Location Samples
Location Updates using a Foreground Service: Get updates about a device's location using a bound and started foreground service.
Location Updates using a PendingIntent: Get updates about a device's location using a PendingIntent
. Sample shows implementation using an IntentService
as well as a BroadcastReceiver
.
If you have the product's ID you can use that to create a product object:
$_product = wc_get_product( $product_id );
Then from the object you can run any of WooCommerce's product methods.
$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();
Update
Please review the Codex article on how to write your own shortcode.
Integrating the WooCommerce product data might look something like this:
function so_30165014_price_shortcode_callback( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'bartag' );
$html = '';
if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
$_product = wc_get_product( $atts['id'] );
$html = "price = " . $_product->get_price();
}
return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );
Your shortcode would then look like [woocommerce_price id="99"]
in public static void main(String args[]) args is an array of console line argument whose data type is String. in this array, you can store various string arguments by invoking them at the command line as shown below: java myProgram Shaan Royal then Shaan and Royal will be stored in the array as arg[0]="Shaan"; arg[1]="Royal"; you can do this manually also inside the program, when you don't call them at the command line.
I like to use Optional and streams to have a net and clear solution, i use the below code to iterate over a directory. the below cases are handled by the code:
but as mentioned by others, you still have to pay attention for outOfMemory in case you have huge folders
File directoryFile = new File("put your path here");
Stream<File> files = Optional.ofNullable(directoryFile// directoryFile
.listFiles(File::isDirectory)) // filter only directories(change with null if you don't need to filter)
.stream()
.flatMap(Arrays::stream);// flatmap from Stream<File[]> to Stream<File>
Try this query (replace t.eventsDate
with e.eventsDate
):
SELECT e FROM Events e WHERE e.eventsDate BETWEEN :startDate AND :endDate
If anybody is still interest Eclipse Labs Rest Client tool is an excellent choice. I'm trying it in Windows in an EXE version and works smoothly.
I've worked also with Rest Client previously and its great too.
I've been strugglin with this problem for hours till found this post. Just like @ligi said, some people have two SDK folders (Android Studio, which is bundled and Eclipse). The problem is that it doesn't matter if you downloaded the Google Play Services library on both SDK folders, your ANDROID_HOME enviroment variable must be pointing to the SDK folder used by the Android Studio.
SDK Folder A (Used on Eclipse)
SDK Folder B (Used on AS)
ANDROID_HOME=<path to SDK Folder B>
After change the path of this variable the error was gone.
Instead of using ">" to redirect like this:
java Foo > log
use ">>" to append normal "stdout" output to a new or existing file:
java Foo >> log
However, if you also want to capture "stderr" errors (such as why the Java program couldn't be started), you should also use the "2>&1" tag which redirects "stderr" (the "2") to "stdout" (the "1"). For example:
java Foo >> log 2>&1
DML (Data Manipulation Language) commands need to be commited/rolled back. Here is a list of those commands.
Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency
On browsers that support the ECMAScript® 2016 Internationalization API Specification (ECMA-402), you can use an Intl.NumberFormat
instance:
var nf = Intl.NumberFormat();
var x = 42000000;
console.log(nf.format(x)); // 42,000,000 in many locales
// 42.000.000 in many other locales
if (typeof Intl === "undefined" || !Intl.NumberFormat) {_x000D_
console.log("This browser doesn't support Intl.NumberFormat");_x000D_
} else {_x000D_
var nf = Intl.NumberFormat();_x000D_
var x = 42000000;_x000D_
console.log(nf.format(x)); // 42,000,000 in many locales_x000D_
// 42.000.000 in many other locales_x000D_
}
_x000D_
After trying all the most upvoted answers and failing to make it work, I figured that my Android Simulator was on Airplane mode. Quite silly but posting this so it could save some time.
P.S. I had a safe reboot on my Simulator before this, which is probably the cause why my simulator booted in Airplane mode
echo "<a href='#' style = \"font-color: #ff0000;\"> Movie List for {$key} 2013 </a>";
All of these answers are so complicated, but there is a simple built-in method that accomplishes this: canScrollVertically(int)
For example:
@Override
public void onScrollChanged() {
if (!scrollView.canScrollVertically(1)) {
// bottom of scroll view
}
if (!scrollView.canScrollVertically(-1)) {
// top of scroll view
}
}
This also works with RecyclerView, ListView, and actually any other view since the method is implemented on View
.
If you have a horizontal ScrollView, the same can be achieved with canScrollHorizontally(int)
I think best approach until Angular team add this feature to cli is first create angular (ng new something) in other place and then add what you want to delete. Using git to check witch files are changed or added by angular cli. then you can revert that changes.
Be careful of untracked files from .gitignore
.
Try wrapping the spans in an anchor tag and apply the background image to that.
HTML:
<div class="header">
<a href="/">
<span class="header-title">My gray sea design</span><br />
<span class="header-title-two">A beautiful design</span>
</a>
</div>
CSS:
.header {
border-bottom:1px solid #eaeaea;
}
.header a {
display: block;
background-image: url("./images/embouchure.jpg");
background-repeat: no-repeat;
height:160px;
padding-left:280px;
padding-top:50px;
width:470px;
color: #eaeaea;
}
If you are in an interactive environment like Jupyter
or ipython
you might be interested in clearing unwanted var's if they are getting heavy.
The magic-commands reset
and reset_selective
is vailable on interactive python sessions like ipython
and Jupyter
1) reset
reset
Resets the namespace by removing all names defined by the user, if called without arguments.
in
and the out
parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist
parameter.
reset in out
Another interesting one is array
that only removes numpy Arrays:
reset array
2) reset_selective
Resets the namespace by removing names defined by the user. Input/Output history are left around in case you need them.
Clean Array Example:
In [1]: import numpy as np
In [2]: littleArray = np.array([1,2,3,4,5])
In [3]: who_ls
Out[3]: ['littleArray', 'np']
In [4]: reset_selective -f littleArray
In [5]: who_ls
Out[5]: ['np']
Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html
You may use Telnet to programmatically query your router for the WAN IP.
The Telnet part
The Telnet part can be accomplished using, for example, this Minimalistic Telnet code as an API to send a Telnet command to your router and get the router's response. The remainder of this answer assumes you are set up in one way or another to send a Telnet command and get back the response in your code.
Limitations of approach
I will say up front that one drawback of querying the router compared to other approaches is that the code you write is likely to be fairly specific to your router model. That said, it can be a useful approach that doesn't rely on external servers, and you may anyway wish to access your router from your own software for other purposes, such as configuring and controlling it, making it more worthwhile writing specific code.
Example router command and response
The example below will not be right for all routers, but illustrates the approach in principle. You will need to change the particulars to suit your router commands and responses.
For example, the way to get your router to show the WAN IP may be the following Telnet command:
connection list
The output may consist of a list of lines of text, one per connection, with the IP address at offset 39. The line for the WAN connection may be identifiable from the word "Internet" somewhere in the line:
RESP: 3947 17.110.226. 13:443 146.200.253. 16:60642 [R..A] Internet 6 tcp 128
<------------------ 39 -------------><-- WAN IP -->
The output may pad each IP address segment out to three characters with spaces, which you will need to remove. (That is, in the xample above, you would need to turn "146.200.253. 16" into "146.200.253.16".)
By experimentation or consulting reference documentation for your router, you can establish the command to use for your specific router and how to interpret the router's response.
Code to get the WAN IP
(Assumes you have a method sendRouterCommand
for the Telnet part—see above.)
Using the example router described above, the following code gets the WAN IP:
private bool getWanIp(ref string wanIP)
{
string routerResponse = sendRouterCommand("connection list");
return (getWanIpFromRouterResponse(routerResponse, out wanIP));
}
private bool getWanIpFromRouterResponse(string routerResponse, out string ipResult)
{
ipResult = null;
string[] responseLines = routerResponse.Split(new char[] { '\n' });
// RESP: 3947 17.110.226. 13:443 146.200.253. 16:60642 [R..A] Internet 6 tcp 128
//<------------------ 39 -------------><--- 15 --->
const int offset = 39, length = 15;
foreach (string line in responseLines)
{
if (line.Length > (offset + length) && line.Contains("Internet"))
{
ipResult = line.Substring(39, 15).Replace(" ", "");
return true;
}
}
return false;
}
First off, EC2 and Elastic Compute Cloud are the same thing.
Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.
EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n
number of instances.
Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.
For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.
In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.
Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/
both your conditions are the same:
if(s < f) { calc = f - s; n = s; }else if(f > s){ calc = s - f; n = f; }
so
if(s < f)
and
}else if(f > s){
are the same
change to
}else if(f < s){
Yes, there is: https://github.com/robinrowe/libunistd
Clone the repository and add path\to\libunistd\unistd
to the INCLUDE
environment variable.
Without seeing your full code, this is impossible to answer with any certainty. The error usually occurs when you are trying to unload a control rather than the form.
Make sure that you don't have the "me" in brackets.
Also if you can post the full code for the userform it would help massively.
I didn't understand why my this didn't work but I found out that this setting is now also under the programming language itself at:
'Editor' | 'Code Style' | < your language > | 'Wrapping and Braces' | 'Right margin (columns)'
Use your identifier(@"drivingDetails") as Storyboard ID.
If you have the following problem
Then you can so following to fix it
Note : You should enable USB debugging on your android device(It will be in developer option in System settings)
First off, Xvfb doesn't read configuration from xorg.conf. Xvfb is a variant of the KDrive X servers and like all members of that family gets its configuration from the command line.
It is true that XRandR and Xinerama are mutually exclusive, but in the case of Xvfb there's no Xinerama in the first place. You can enable the XRandR extension by starting Xvfb using at least the following command line options
Xvfb +extension RANDR [further options]
For this case you can also sort using LINQ:
week = week.OrderBy(w => DateTime.Parse(w.date)).ToList();
There is Task
exists, It is unnesscery using BackgroundWorker
, Task
is more simple. for example:
ProgressDialog.cs:
public partial class ProgressDialog : Form
{
public System.Windows.Forms.ProgressBar Progressbar { get { return this.progressBar1; } }
public ProgressDialog()
{
InitializeComponent();
}
public void RunAsync(Action action)
{
Task.Run(action);
}
}
Done! Then you can reuse ProgressDialog anywhere:
var progressDialog = new ProgressDialog();
progressDialog.Progressbar.Value = 0;
progressDialog.Progressbar.Maximum = 100;
progressDialog.RunAsync(() =>
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000)
this.progressDialog.Progressbar.BeginInvoke((MethodInvoker)(() => {
this.progressDialog.Progressbar.Value += 1;
}));
}
});
progressDialog.ShowDialog();
To read a specific set of columns from a dataset you, there are several other options:
1) With fread
from the data.table
-package:
You can specify the desired columns with the select
parameter from fread
from the data.table
package. You can specify the columns with a vector of column names or column numbers.
For the example dataset:
library(data.table)
dat <- fread("data.txt", select = c("Year","Jan","Feb","Mar","Apr","May","Jun"))
dat <- fread("data.txt", select = c(1:7))
Alternatively, you can use the drop
parameter to indicate which columns should not be read:
dat <- fread("data.txt", drop = c("Jul","Aug","Sep","Oct","Nov","Dec"))
dat <- fread("data.txt", drop = c(8:13))
All result in:
> data
Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27 -2 -6 -10 -32
UPDATE: When you don't want fread
to return a data.table, use the data.table = FALSE
-parameter, e.g.: fread("data.txt", select = c(1:7), data.table = FALSE)
2) With read.csv.sql
from the sqldf
-package:
Another alternative is the read.csv.sql
function from the sqldf
package:
library(sqldf)
dat <- read.csv.sql("data.txt",
sql = "select Year,Jan,Feb,Mar,Apr,May,Jun from file",
sep = "\t")
3) With the read_*
-functions from the readr
-package:
library(readr)
dat <- read_table("data.txt",
col_types = cols_only(Year = 'i', Jan = 'i', Feb = 'i', Mar = 'i',
Apr = 'i', May = 'i', Jun = 'i'))
dat <- read_table("data.txt",
col_types = list(Jul = col_skip(), Aug = col_skip(), Sep = col_skip(),
Oct = col_skip(), Nov = col_skip(), Dec = col_skip()))
dat <- read_table("data.txt", col_types = 'iiiiiii______')
From the documentation an explanation for the used characters with col_types
:
each character represents one column: c = character, i = integer, n = number, d = double, l = logical, D = date, T = date time, t = time, ? = guess, or _/- to skip the column
Comprehensions are usually faster, and this has the advantage of not editing mydict
during the iteration:
mydict = dict((k, v if v else '') for k, v in mydict.items())
You do realize this is the default behavior, right? if you add /something the results would be different.
you can do a number of things to prevent default behavior.
href="#"
:Will do nothing but anchor - not the best solution since it may jump to page top.
<a href="#">
href="javascript:void(0);"
Will do nothing at all and is perfectly legit.
<a href="javascript:void(0);"></a>
href="your-actual-intended-link"
(Best)obviously the best.
<a href="<your-actual-intended-link>"></a>
If you don't want an a
tag to go somewhere, why use an a
tag at all?