$("#datepicker").datepicker("option", "dateFormat", "yy-mm-dd ");
For the time picker, you should add timepicker to Datepicker, and it would be formatted with one equivalent command.
EDIT
Use this one that extend jQuery UI Datepicker. You can pick up both date and time.
I found that mounting a local volume over /tmp can cause permission issues when the "apt-get update" runs, which prevents the package cache from being populated. Hopefully, this isn't something most people do, but it's something else to look for if you see this issue.
max_connections
You can change max_connections
while MySQL is running via SET
:
mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 5000 |
+-----------------+-------+
1 row in set (0.00 sec)
timeout
relatedI had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.
I suggest that you increase this value to 100k or disable connection pooling Pooling=false
he has two questions.
Q1 - what happens if I disable pooling
Slow down making DB connection. connection pooling
is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool
Q2 - Can the value of pooling be increased or the maximum is 100?
you can increase but I'm sure what is MAX value, maybe max_connections
in my.cnf
My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.
If you have Stress Test tool like JMeter
you can test youself.
Try this code
if (localStorage.getItem("infiniteScrollEnabled") === null) {
} else {
}
This is described here: https://yarnpkg.com/en/docs/cli/add#toc-adding-dependencies
For example:
yarn add https://github.com/novnc/noVNC.git#0613d18
Is you want a plus (+) symbol in the body you have to encode it as 2B.
For example: Try this
find supports wildcard matches, just add a *
:
find / -type d -name "ora10*"
Take a look at this: Entity Framework don't create database
I would try giving the database a different name. Sometimes you can run into problems with SQL Express when trying to create a database with the same name a second time. There is a way to fix this using SQL Server Management Studio but it's generally easier to just use a different database name.
Edit This answer was accepted because it confirms the bug and the workaround used by OP (renaming database could help). I totally agree that renaming the database is not really an acceptable way, and does not totally solve the issue. Unfortunatly I didn't check the other ways to really solve it in SSMS.
Use MouseDown event
if(e.Button == MouseButton.Right)
SPSS can also read .dta files and export them to .csv, but that costs money. PSPP, an open source version of SPSS, which is rough, might also be able to read/export .dta files.
You should try something like this
List xx= (List) list.get(0)
String id = (String) xx.get(0)
or if you have a House value object the result of the query is of the same type, then
House myhouse = (House) list.get(0);
Quick and Easy way:
tasks
In SSMS 2017 you need to ignore step 2 - the generate scripts options is at the top level of the context menu
Thanks to Daniel for the comment to update.generate scripts
Types of data to script
- Called types of data to script
in SMSS 2014 Thanks to Ellesedil for commentingdata only
I usually in cases like this generate to a new query editor window and then just do any modifications where needed.
Simply add the class img-responsive
to your img
tag, it is applicable in bootstrap 3 onward!
I had a similar problem to this, so I altered the accepted answer to make a more generic version of the function. I thought I'd leave it here.
var filterSelectOptions = function($select, callback) {
var options = null,
dataOptions = $select.data('options');
if (typeof dataOptions === 'undefined') {
options = [];
$select.children('option').each(function() {
var $this = $(this);
options.push({value: $this.val(), text: $this.text()});
});
$select.data('options', options);
} else {
options = dataOptions;
}
$select.empty();
$.each(options, function(i) {
var option = options[i];
if(callback(option)) {
$select.append(
$('<option/>').text(option.text).val(option.value)
);
}
});
};
Another way based on amadan:
SELECT * FROM [Purchasing].[Vendor] WHERE
( (@url IS null OR @url = '' OR @url = 'ALL') and PurchasingWebServiceURL LIKE '%')
or
( @url = 'blank' and PurchasingWebServiceURL = '')
or
(@url = 'fail' and PurchasingWebServiceURL NOT LIKE '%treyresearch%')
or( (@url not in ('fail','blank','','ALL') and @url is not null and
PurchasingWebServiceUrl Like '%'+@ur+'%')
END
I've found that using ; to separate commands only works in the foreground. eg :
cmd1; cmd2; cmd3 &
- will only execute cmd3
in the background, whereas
cmd1 && cmd2 && cmd3 &
- will execute the entire chain in the background IF there are no errors.
To cater for unconditional execution, using parenthesis solves this :
(cmd1; cmd2; cmd3) &
- will execute the chain of commands in the background, even if any step fails.
You want to use:
git checkout --ours foo/bar.java
git add foo/bar.java
If you rebase a branch feature_x
against main
(i.e. running git rebase main
while on branch feature_x
), during rebasing ours
refers to main
and theirs
to feature_x
.
As pointed out in the git-rebase docs:
Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.
For further details read this thread.
It really depends on what functions you're using to plot the lines, but try see if the on you're using takes an alpha value and set it to something like 0.5. If that doesn't work, try get the line objects and set their alpha values directly.
Do not waste your time on checking integrity
or deleting data from work queue
table because these are temporary solutions and it will hit you back after a while.
Just do another checkout
and replace the existing .svn folder with the new one. Do an update
and then it should go smooth.
Use java.util.Timer
and Timer#schedule(TimerTask,delay,period)
method will help you.
public class RemindTask extends TimerTask {
public void run() {
System.out.println(" Hello World!");
}
public static void main(String[] args){
Timer timer = new Timer();
timer.schedule(new RemindTask(), 3000,3000);
}
}
An image of how to in Android Studio 1.5.1.
Within the "Android" project (see the drop-down in the topleft of my image), Right-click on the app...
Note that in Log4J 2.x, the public interface org.apache.logging.log4j.Logger
doesn't include the setAppender()
and removeAppender()
methods.
But if you're not doing anything too fancy, you should be able to cast it to the implementation class org.apache.logging.log4j.core.Logger
, which does expose those methods.
Here's an example with Mockito and AssertJ:
// Import the implementation class rather than the API interface
import org.apache.logging.log4j.core.Logger;
// Cast logger to implementation class to get access to setAppender/removeAppender
Logger log = (Logger) LogManager.getLogger(MyClassUnderTest.class);
// Set up the mock appender, stubbing some methods Log4J needs internally
Appender appender = mock(Appender.class);
when(appender.getName()).thenReturn("Mock Appender");
when(appender.isStarted()).thenReturn(true);
log.addAppender(appender);
try {
new MyClassUnderTest().doSomethingThatShouldLogAnError();
} finally {
log.removeAppender(appender);
}
// Verify that we got an error with the expected message
ArgumentCaptor<LogEvent> logEventCaptor = ArgumentCaptor.forClass(LogEvent.class);
verify(appender).append(logEventCaptor.capture());
LogEvent logEvent = logEventCaptor.getValue();
assertThat(logEvent.getLevel()).isEqualTo(Level.ERROR);
assertThat(logEvent.getMessage().getFormattedMessage()).contains(expectedErrorMessage);
document.all
works in Chrome now (not sure when since), but I've been missing it the last 20 years.... Simply a shorter method name than the clunky document.getElementById
. Not sure if it works in Firefox, those guys never had any desire to be compatible with the existing web, always creating new standards instead of embracing the existing web.
If running on Windows, you could consider using win32crypt library. It allows storage and retrieval of protected data (keys, passwords) by the user that is running the script, thus passwords are never stored in clear text or obfuscated format in your code. I am not sure if there is an equivalent implementation for other platforms, so with the strict use of win32crypt your code is not portable.
I believe the module can be obtained here: http://timgolden.me.uk/pywin32-docs/win32crypt.html
Assuming your using the Properties class, via its load method, and I guess you are using the ClassLoader getResourceAsStream to get the input stream.
How are you passing in the name, it seems it should be in this form: /com/al/common/email/templates/foo.properties
Facing similar concern, I found the following tool with a trivial Google search :
JPSoft's "Take Command" includes a batch file IDE/debugger. Their short presentation video demonstrates it nicely.
I'm using the trial version since a few hours. Here is my first humble opinion:
It deverves a try.
The code below works. Replace the text within the single quotes with your image name. If it is in the same folder, if not add ../foldername/'yourimagename' I hope that helps.
NOTE:
use of the single quotes by most of the programmers is not advised but I use it and it works. Also, if you would write a PHP you would appreciate what it can do i.e. add the background image automatically from the variable etc.
<html>
<head>
<style type="text/css">
.btn-pTool{
margin:0;
padding:0;
background-image: url('your name of the field');
height:100px;
width:200px;
display:block;
}
.btn-pToolName{
text-align: center;
width: 26px;
height: 190px;
display: block;
color: #fff;
text-decoration: none;
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 1em;
line-height: 32px;
}
</style>
</head>
<body>
<div class="pToolContainer">
<span class="btn-pTool"><a class="btn-pToolName" href="#">Test text</a></span>
<div class="pToolSlidePanel">Test text</div>
</div>
</body>
</html>
A memory heap is a location in memory where memory may be allocated at random access.
Unlike the stack where memory is allocated and released in a very defined order, individual data elements allocated on the heap are typically released in ways which is asynchronous from one another. Any such data element is freed when the program explicitly releases the corresponding pointer, and this may result in a fragmented heap. In opposition only data at the top (or the bottom, depending on the way the stack works) may be released, resulting in data element being freed in the reverse order they were allocated.
In your component -
Make sure to initialize the formControl name country with a value.
For instance: Assuming that your form group name is myForm and _fb is FormBuilder instance then,
....
this.myForm = this._fb.group({
country:[this.default]
})
and also try replacing [value] with [ngValue].
EDIT 1: If you are unable to initialize the value when declaring then set the value when you have the value like this.
this.myForm.controls.country.controls.setValue(this.country)
As morisunshine answer pointed in right direction, a little tweak in his answer solved my problem for iOS8.2 .Thanks to him.
I solved this problem by setting that:
ARCHS = armv7
VALID_ARCHS = armv6 armv7 armv7s arm64
BUILD ACTIVE ARCHITECTURE ONLY= NO
I solved the Access-Control-Allow-Origin error modifying the dataType parameter to dataType:'jsonp' and adding a crossDomain:true
$.ajax({
url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
data: myData,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});
Do you even need MSDTC? The escalation you're experiencing is often caused by creating multiple connections within a single TransactionScope.
If you do need it then you need to enable it as outlined in the error message. On XP:
You could use underscore.js and the each function:
_.each({key1: "value1", key2: "value2"}, function(value) {
console.log(value);
});
Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate
now has second parameter values
, which is being used for new record, but not for search
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'Taylor',
'lastName' => 'Otwell'
]);
For a concrete example of accessing the SMS/MMS database, take a look at gTalkSMS.
I came late but here is a little script I made for this purpose that I run in Windows PowerShell. You should be able to copy and paste it into the ISE. This will then run the arp command and save the results into a .txt file and open it in notepad.
# Declare Variables
$MyIpAddress
$MyIpAddressLast
# Declare Variable And Get User Inputs
$IpFirstThree=Read-Host 'What is the first three octects of you IP addresses please include the last period?'
$IpStart=Read-Host 'Which IP Address do you want to start with? Include NO periods.'
$IpEnd=Read-Host 'Which IP Address do you want to end with? Include NO periods.'
$SaveMyFilePath=Read-Host 'Enter the file path and name you want for the text file results.'
$PingTries=Read-Host 'Enter the number of times you want to try pinging each address.'
#Run from start ip and ping
#Run the arp -a and output the results to a text file
#Then launch notepad and open the results file
Foreach($MyIpAddressLast in $IpStart..$IpEnd)
{$MyIpAddress=$IpFirstThree+$MyIpAddressLast
Test-Connection -computername $MyIpAddress -Count $PingTries}
arp -a | Out-File $SaveMyFilePath
notepad.exe $SaveMyFilePath
I am not sure what you understand by "execute from the Command line interface", but you're probably looking after the following select statement:
select * from dba_users;
or
select username from dba_users;
The Subject, in security, is the thing being secured. In this case it could be a persons email or a website or a machine.
If we take the example of an email, say my email, then the subject key container would be the protected location containing my private key.
The certificate store usually refers to Microsoft certificate store which contains certificates form trusted roots, machines on the network, people etc. In my case the subjects certificate store would be the place, within this store, holding my certificates.
If you are working within a microsoft domain then the subject name will invariably hold the Distinguished Name, of the subject, which is how the domain references the subject and holds it in its directory. e.g. CN=Mark Sutton, OU=Developers, O=Mycompany C=UK
To look at your certificates on a microsoft machine:-
Log in as you run>mmc Select File>add/remove snap-in and select certificates then select my user account click Finish then close then ok. Look in the personal area of the store.
In the other areas of the store you will see the other trusted certificates used to validate signatures etc.
The top voted answer is deprecated in Bootstrap 3.3 and will be removed in v4. Try this instead:
JavaScript:
// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
Html (Based on the official example. Note that for Bootstrap 3.* we set data-remote="false"
to disable the deprecated Bootstrap load function):
<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
Launch Modal
</a>
<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Try it yourself: https://jsfiddle.net/ednon5d1/
use this attribute in style
font-size: 11px !important;//your font size
by !important it override your css
When a client connects to an Oracle server, it first connnects to the Oracle listener service. It often redirects the client to another port. So the client has to open another connection on a different port, which is blocked by the firewall.
So you might in fact have encountered a firewall problem due to Oracle port redirection. It should be possible to diagnose it with a network monitor on the client machine or with the firewall management software on the firewall.
--feature
and --no-feature
at the same time (last one wins)This allows users to make a shell alias with --feature
, and overriding it with --no-feature
.
parser.add_argument('--feature', default=True, action=argparse.BooleanOptionalAction)
I recommend mgilson's answer:
parser.add_argument('--feature', dest='feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)
--feature
and --no-feature
at the same timeYou can use a mutually exclusive group:
feature_parser = parser.add_mutually_exclusive_group(required=False)
feature_parser.add_argument('--feature', dest='feature', action='store_true')
feature_parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)
You can use this helper if you are going to set many of them:
def add_bool_arg(parser, name, default=False):
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('--' + name, dest=name, action='store_true')
group.add_argument('--no-' + name, dest=name, action='store_false')
parser.set_defaults(**{name:default})
add_bool_arg(parser, 'useful-feature')
add_bool_arg(parser, 'even-more-useful-feature')
If your web page has jquery in your page, then you can do it writing on chrome developers console:
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
Its jquery way of doing it!
Excerpt from the Java API for addAll(collection c) in Interface List see here
"Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation)."
You you will have as much object as you have in both lists - the number of objects in your first list plus the number of objects you have in your second list - in your case 100.
Step 1
Create a objective c file(.m file) and it's corresponding header file.
// Header file (We call it "ObjCFunc.h")
#ifndef test2_ObjCFunc_h
#define test2_ObjCFunc_h
@interface myClass :NSObject
-(void)hello:(int)num1;
@end
#endif
// Corresponding Objective C file(We call it "ObjCFunc.m")
#import <Foundation/Foundation.h>
#include "ObjCFunc.h"
@implementation myClass
//Your objective c code here....
-(void)hello:(int)num1
{
NSLog(@"Hello!!!!!!");
}
@end
Step 2
Now we will implement a c++ function to call the objective c function that we just created! So for that we will define a .mm file and its corresponding header file(".mm" file is to be used here because we will be able to use both Objective C and C++ coding in the file)
//Header file(We call it "ObjCCall.h")
#ifndef __test2__ObjCCall__
#define __test2__ObjCCall__
#include <stdio.h>
class ObjCCall
{
public:
static void objectiveC_Call(); //We define a static method to call the function directly using the class_name
};
#endif /* defined(__test2__ObjCCall__) */
//Corresponding Objective C++ file(We call it "ObjCCall.mm")
#include "ObjCCall.h"
#include "ObjCFunc.h"
void ObjCCall::objectiveC_Call()
{
//Objective C code calling.....
myClass *obj=[[myClass alloc]init]; //Allocating the new object for the objective C class we created
[obj hello:(100)]; //Calling the function we defined
}
Step 3
Calling the c++ function(which actually calls the objective c method)
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include "ObjCCall.h"
class HelloWorld : public cocos2d::Layer
{
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
void ObCCall(); //definition
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
//Final call
#include "HelloWorldScene.h"
#include "ObjCCall.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
origin.y + closeItem->getContentSize().height/2));
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
/////////////////////////////
// 3. add your codes below...
// add a label shows "Hello World"
// create and initialize a label
auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
// position the label on the center of the screen
label->setPosition(Vec2(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - label- >getContentSize().height));
// add the label as a child to this layer
this->addChild(label, 1);
// add "HelloWorld" splash screen"
auto sprite = Sprite::create("HelloWorld.png");
// position the sprite on the center of the screen
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
// add the sprite as a child to this layer
this->addChild(sprite, 0);
this->ObCCall(); //first call
return true;
}
void HelloWorld::ObCCall() //Definition
{
ObjCCall::objectiveC_Call(); //Final Call
}
void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
return;
#endif
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
Hope this works!
Set both to auto
:
height: auto;
width: auto;
Making it:
#products
{
height: auto;
width: auto;
padding:5px; margin-bottom:8px;
border: 1px solid #EFEFEF;
}
Swift 3 & 4/5
self.navigationController!.viewControllers.removeAll()
self.navigationController?.viewControllers.remove(at: "insert here a number")
Swift 2.1
remove all:
self.navigationController!.viewControllers.removeAll()
remove at index
self.navigationController?.viewControllers.removeAtIndex("insert here a number")
There a bunch of more possible actions like removeFirst,range etc.
You have to use the jquery's text() function. What it does is:
Get the combined text contents of all matched elements.
The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents. Cannot be used on input elements. For input field text use the val attribute.
For example:
Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the bold is gone).
var str = $("p:first").text(); $("p:last").html(str);
Test Paragraph.
Test Paragraph.
With your markup you have to do:
$('a#a_tbnotesverbergen').text('new text');
and it will result in
<a id="a_tbnotesverbergen" href="#nothing">new text</a>
if you are coding in jupyter notebook, and want to check which cuda version tf is using, run the follow command directly into jupyter cell:
!conda list cudatoolkit
!conda list cudnn
and to check if the gpu is visible to tf:
tf.test.is_gpu_available(
cuda_only=False, min_cuda_compute_capability=None
)
Parsing command line arguments in a primitive way as explained in the above answers is reasonable as long as the number of parameters that you need to deal with is not too much.
I strongly suggest you to use an industrial strength library for handling the command line arguments.
This will make your code more professional.
Such a library for C++ is available in the following website. I have used this library in many of my projects, hence I can confidently say that this one of the easiest yet useful library for command line argument parsing. Besides, since it is just a template library, it is easier to import into your project. http://tclap.sourceforge.net/
A similar library is available for C as well. http://argtable.sourceforge.net/
From the PHP manual:
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
I had to do 2 steps:
follow Tiep Phan
solution ... edit config.inc.php
file ...
follow Mahmoud Zalt
solution ... change password within phpmyadmin
$ ionic info Ionic:
Ionic CLI : 5.4.16
Utility:
cordova-res : not installed native-run : 0.3.0
System:
NodeJS : v12.16.1 npm : 6.13.4 OS : Linux 5.3
------------------------------------------------------------
Ionic CLI update available: 5.4.16 ? 6.2.2
The package name has changed from ionic to @ionic/cli!
To update, run: npm uninstall -g ionic
Then run: npm i -g @ionic/cli
------------------------------------------------------------
ALTER DATABASE name OWNER TO new_owner;
See the Postgresql manual's entry on this for more details.
In C, a string is actually stored as an array of characters, so the 'string pointer' is pointing to the first character. For instance,
char myString[] = "This is some text";
You can access any character as a simple char by using myString as an array, thus:
char myChar = myString[6];
printf("%c\n", myChar); // Prints s
Hope this helps! David
Here is what I use when I don't have access to the source string, e.g. for downloaded HTML:
// replace newlines with <br>
public static String replaceNewlinesWithBreaks(String source) {
return source != null ? source.replaceAll("(?:\n|\r\n)","<br>") : "";
}
For XML you should probably edit that to replace with <br/>
instead.
Example of its use in a function (additional calls removed for clarity):
// remove HTML tags but preserve supported HTML text styling (if there is any)
public static CharSequence getStyledTextFromHtml(String source) {
return android.text.Html.fromHtml(replaceNewlinesWithBreaks(source));
}
...and a further example:
textView.setText(getStyledTextFromHtml(someString));
Unfortunately there is no such class in Bootstrap as of now (27th Jan 2019).
I scanned through bootstrap code and discovered following classes that use cursor: pointer. Seems like it is not a good idea to use any of them specifically for cursor: pointer.
summary {
display: list-item;
cursor: pointer;
}
.btn:not(:disabled):not(.disabled) {
cursor: pointer;
}
.custom-range::-webkit-slider-runnable-track {
width: 100%;
height: 0.5rem;
color: transparent;
cursor: pointer;
background-color: #dee2e6;
border-color: transparent;
border-radius: 1rem;
}
.custom-range::-moz-range-track {
width: 100%;
height: 0.5rem;
color: transparent;
cursor: pointer;
background-color: #dee2e6;
border-color: transparent;
border-radius: 1rem;
}
.custom-range::-ms-track {
width: 100%;
height: 0.5rem;
color: transparent;
cursor: pointer;
background-color: transparent;
border-color: transparent;
border-width: 0.5rem;
}
.navbar-toggler:not(:disabled):not(.disabled) {
cursor: pointer;
}
.page-link:not(:disabled):not(.disabled) {
cursor: pointer;
}
.close:not(:disabled):not(.disabled) {
cursor: pointer;
}
.carousel-indicators li {
box-sizing: content-box;
-ms-flex: 0 1 auto;
flex: 0 1 auto;
width: 30px;
height: 3px;
margin-right: 3px;
margin-left: 3px;
text-indent: -999px;
cursor: pointer;
background-color: #fff;
background-clip: padding-box;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
opacity: .5;
transition: opacity 0.6s ease;
}
The only OBVIOUS SOLUTION:
What I would suggest you is just to create a class in your common css as cursor-pointer
. That is simple and elegant as of now.
.cursor-pointer{_x000D_
cursor: pointer;_x000D_
}
_x000D_
<div class="cursor-pointer">Hover on me</div>
_x000D_
I think the easiest approach is just to change the last line to
txtBlock.Text = await response.Content.ReadAsStringAsync(); //right!
This way you don't need to introduce any stream readers and you don't need any extension methods.
I've implemented this with AbsoluteLayout and a simple slide controller that moves the view to a negative offset to hide.
If anyone is interested, I can clean up the code/layout and post. I know AbsoluteLayout is deprecated, but it was a very straight forward implementation. Left View/ Right View, and when "sliding open", just move the left view out from a -X offset to the device's width - whatever you want to show of the Right View
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
If the column has the NOT NULL
constraint then it won't be possible; but otherwise this is fine:
INSERT INTO MyTable(MyIntColumn) VALUES(NULL);
I understand that this question is a bit old but I'm going to introduce another solution using redux-observable aka. Epic.
Quoting the official documentation:
What is redux-observable?
RxJS 5-based middleware for Redux. Compose and cancel async actions to create side effects and more.
An Epic is the core primitive of redux-observable.
It is a function which takes a stream of actions and returns a stream of actions. Actions in, actions out.
In more or less words, you can create a function that receives actions through a Stream and then return a new stream of actions (using common side effects such as timeouts, delays, intervals, and requests).
Let me post the code and then explain a bit more about it
store.js
import {createStore, applyMiddleware} from 'redux'
import {createEpicMiddleware} from 'redux-observable'
import {Observable} from 'rxjs'
const NEW_NOTIFICATION = 'NEW_NOTIFICATION'
const QUIT_NOTIFICATION = 'QUIT_NOTIFICATION'
const NOTIFICATION_TIMEOUT = 2000
const initialState = ''
const rootReducer = (state = initialState, action) => {
const {type, message} = action
console.log(type)
switch(type) {
case NEW_NOTIFICATION:
return message
break
case QUIT_NOTIFICATION:
return initialState
break
}
return state
}
const rootEpic = (action$) => {
const incoming = action$.ofType(NEW_NOTIFICATION)
const outgoing = incoming.switchMap((action) => {
return Observable.of(quitNotification())
.delay(NOTIFICATION_TIMEOUT)
//.takeUntil(action$.ofType(NEW_NOTIFICATION))
});
return outgoing;
}
export function newNotification(message) {
return ({type: NEW_NOTIFICATION, message})
}
export function quitNotification(message) {
return ({type: QUIT_NOTIFICATION, message});
}
export const configureStore = () => createStore(
rootReducer,
applyMiddleware(createEpicMiddleware(rootEpic))
)
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {configureStore} from './store.js'
import {Provider} from 'react-redux'
const store = configureStore()
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
App.js
import React, { Component } from 'react';
import {connect} from 'react-redux'
import {newNotification} from './store.js'
class App extends Component {
render() {
return (
<div className="App">
{this.props.notificationExistance ? (<p>{this.props.notificationMessage}</p>) : ''}
<button onClick={this.props.onNotificationRequest}>Click!</button>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
notificationExistance : state.length > 0,
notificationMessage : state
}
}
const mapDispatchToProps = (dispatch) => {
return {
onNotificationRequest: () => dispatch(newNotification(new Date().toDateString()))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
The key code to solve this problem is as easy as pie as you can see, the only thing that appears different from the other answers is the function rootEpic.
Point 1. As with sagas, you have to combine the epics in order to get a top level function that receives a stream of actions and returns a stream of actions, so you can use it with the middleware factory createEpicMiddleware. In our case we only need one so we only have our rootEpic so we don't have to combine anything but it's a good to know fact.
Point 2. Our rootEpic which takes care about the side effects logic only takes about 5 lines of code which is awesome! Including the fact that is pretty much declarative!
Point 3. Line by line rootEpic explanation (in comments)
const rootEpic = (action$) => {
// sets the incoming constant as a stream
// of actions with type NEW_NOTIFICATION
const incoming = action$.ofType(NEW_NOTIFICATION)
// Merges the "incoming" stream with the stream resulting for each call
// This functionality is similar to flatMap (or Promise.all in some way)
// It creates a new stream with the values of incoming and
// the resulting values of the stream generated by the function passed
// but it stops the merge when incoming gets a new value SO!,
// in result: no quitNotification action is set in the resulting stream
// in case there is a new alert
const outgoing = incoming.switchMap((action) => {
// creates of observable with the value passed
// (a stream with only one node)
return Observable.of(quitNotification())
// it waits before sending the nodes
// from the Observable.of(...) statement
.delay(NOTIFICATION_TIMEOUT)
});
// we return the resulting stream
return outgoing;
}
I hope it helps!
Use the input()
built-in function to get a input line from the user.
You can read the help here.
You can use the following code to get several line at once (finishing by an empty one):
while input() != '':
do_thing
For selections, you can also convert the selection using the "To spaces" function. I usually just use it via the ctrl-shift-A then find "To Spaces" from there.
I'm late to the party, but here's a small and easy solution I came up with to return an amount of words.
It's not directly related to your requirement of characters, but it serves the same outcome that I believe you were after.
function truncateWords(sentence, amount, tail) {
const words = sentence.split(' ');
if (amount >= words.length) {
return sentence;
}
const truncated = words.slice(0, amount);
return `${truncated.join(' ')}${tail}`;
}
const sentence = 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.';
console.log(truncateWords(sentence, 10, '...'));
See the working example here: https://jsfiddle.net/bx7rojgL/
You need to use a TimeSpan. Here is some sample code:
TimeSpan sincelast = TimeSpan.FromTicks(DateTime.Now.Ticks - LastUpdate.Ticks);
The portion with the HTTP://
,FTP://
, etc are called URI Schemes
You can register your own through the registry.
HKEY_CLASSES_ROOT/
your-protocol-name/
(Default) "URL:your-protocol-name Protocol"
URL Protocol ""
shell/
open/
command/
(Default) PathToExecutable
Sources: https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml, http://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx
I have also one more option why blank page issue may occur. If you are on production mode and if you cached your config files by php artisan (config:cache), try to delete cache file executing:
php artisan config:clear
or delete it manualy (bootstrap/cache/config.php)
public class Elvis {
public static final Elvis INSTANCE = new Elvis();
private Elvis () {...}
}
Source : Effective Java -> Item 2
It suggests to use it, if you are sure that class will always remain singleton.
Please correct me if I'm wrong, but when Angular 2.0 is released I do not believe$rootScope
will be around. My conjecture is based on the fact that $scope
is being removed as well. Obviously controllers, will still exist, just not in the ng-controller
fashion.Think of injecting controllers into directives instead. As the release comes imminent, it will be best to use services as global variables if you want an easier time to switch from verison 1.X to 2.0.
There is a mistake in its source. Check out its source if you may. It reads like this
<?php
class BulletProofException extends Exception{}
namespace BulletProof;
....
That is insane. Personally, I'd say the code is well documented, and elegant, but the author missed a simple point; he declared the namespace within the class. Namespace whenever used should be the first statement.
Too bad I am not in Github; could have pulled a request otherwise :(
Write your own is the best solution for now. Here is an example of a Converter that can do both way Normal and Inverted. If you have any problems with this just ask.
[ValueConversion(typeof(bool), typeof(Visibility))]
public class InvertableBooleanToVisibilityConverter : IValueConverter
{
enum Parameters
{
Normal, Inverted
}
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var boolValue = (bool)value;
var direction = (Parameters)Enum.Parse(typeof(Parameters), (string)parameter);
if(direction == Parameters.Inverted)
return !boolValue? Visibility.Visible : Visibility.Collapsed;
return boolValue? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return null;
}
}
<UserControl.Resources>
<Converters:InvertableBooleanToVisibilityConverter x:Key="_Converter"/>
</UserControl.Resources>
<Button Visibility="{Binding IsRunning, Converter={StaticResource _Converter}, ConverterParameter=Inverted}">Start</Button>
Old thread I know.......
Problem with the answer of @ryuutatsuo is that it blocks also any input or other element that has to react on 'clicks' (for example inputs), so i wrote this solution. This solution made it possible to use any existing drag and drop library that is based upon mousedown, mousemove and mouseup events on any touch device (or cumputer). This is also a cross-browser solution.
I have tested in on several devices and it works fast (in combination with the drag and drop feature of ThreeDubMedia (see also http://threedubmedia.com/code/event/drag)). It is a jQuery solution so you can use it only with jQuery libs. I have used jQuery 1.5.1 for it because some newer functions don't work properly with IE9 and above (not tested with newer versions of jQuery).
Before you add any drag or drop operation to an event you have to call this function first:
simulateTouchEvents(<object>);
You can also block all components/children for input or to speed up event handling by using the following syntax:
simulateTouchEvents(<object>, true); // ignore events on childs
Here is the code i wrote. I used some nice tricks to speed up evaluating things (see code).
function simulateTouchEvents(oo,bIgnoreChilds)
{
if( !$(oo)[0] )
{ return false; }
if( !window.__touchTypes )
{
window.__touchTypes = {touchstart:'mousedown',touchmove:'mousemove',touchend:'mouseup'};
window.__touchInputs = {INPUT:1,TEXTAREA:1,SELECT:1,OPTION:1,'input':1,'textarea':1,'select':1,'option':1};
}
$(oo).bind('touchstart touchmove touchend', function(ev)
{
var bSame = (ev.target == this);
if( bIgnoreChilds && !bSame )
{ return; }
var b = (!bSame && ev.target.__ajqmeclk), // Get if object is already tested or input type
e = ev.originalEvent;
if( b === true || !e.touches || e.touches.length > 1 || !window.__touchTypes[e.type] )
{ return; } //allow multi-touch gestures to work
var oEv = ( !bSame && typeof b != 'boolean')?$(ev.target).data('events'):false,
b = (!bSame)?(ev.target.__ajqmeclk = oEv?(oEv['click'] || oEv['mousedown'] || oEv['mouseup'] || oEv['mousemove']):false ):false;
if( b || window.__touchInputs[ev.target.tagName] )
{ return; } //allow default clicks to work (and on inputs)
// https://developer.mozilla.org/en/DOM/event.initMouseEvent for API
var touch = e.changedTouches[0], newEvent = document.createEvent("MouseEvent");
newEvent.initMouseEvent(window.__touchTypes[e.type], true, true, window, 1,
touch.screenX, touch.screenY,
touch.clientX, touch.clientY, false,
false, false, false, 0, null);
touch.target.dispatchEvent(newEvent);
e.preventDefault();
ev.stopImmediatePropagation();
ev.stopPropagation();
ev.preventDefault();
});
return true;
};
What it does: At first, it translates single touch events into mouse events. It checks if an event is caused by an element on/in the element that must be dragged around. If it is an input element like input, textarea etc, it skips the translation, or if a standard mouse event is attached to it it will also skip a translation.
Result: Every element on a draggable element is still working.
Happy coding, greetz, Erwin Haantjes
Another option for plotting inline from an array of images could be:
import IPython
def showimg(a):
IPython.display.display(PIL.Image.fromarray(a))
where a is an array
a.shape
(720, 1280, 3)
This code will help you to make a result like FEB 17 20:49 .
String myTimestamp="2014/02/17 20:49";
SimpleDateFormat form = new SimpleDateFormat("yyyy/MM/dd HH:mm");
Date date = null;
Date time = null;
try
{
date = form.parse(myTimestamp);
time = new Date(myTimestamp);
SimpleDateFormat postFormater = new SimpleDateFormat("MMM dd");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String newDateStr = postFormater.format(date).toUpperCase();
String newTimeStr = sdf.format(time);
System.out.println("Date : "+newDateStr);
System.out.println("Time : "+newTimeStr);
}
catch (Exception e)
{
e.printStackTrace();
}
Result :
Date : FEB 17
Time : 20:49
C#:
ChromeOptions options = new ChromeOptions();
options.AddArgument("C:/Users/username/Documents/Visual Studio 2012/Projects/Interaris.Test/Interaris.Tes/bin/Debug/chromedriver.exe");
ChromeDriver chrome = new ChromeDriver(options);
Worked for me.
If you don't need the entire string, you can take advantage of the delayed execution:
public static class StringExtensions
{
public static IEnumerable<char> RemoveChar(this IEnumerable<char> originalString, char removingChar)
{
return originalString.Where(@char => @char != removingChar);
}
}
You can even combine multiple characters...
string veryLongText = "abcdefghijk...";
IEnumerable<char> firstFiveCharsWithoutCsAndDs = veryLongText
.RemoveChar('c')
.RemoveChar('d')
.Take(5);
... and only the first 7 characters will be evaluated :)
EDIT: or, even better:
public static class StringExtensions
{
public static IEnumerable<char> RemoveChars(this IEnumerable<char> originalString,
params char[] removingChars)
{
return originalString.Except(removingChars);
}
}
and its usage:
var veryLongText = "abcdefghijk...";
IEnumerable<char> firstFiveCharsWithoutCsAndDs = veryLongText
.RemoveChars('c', 'd')
.Take(5)
.ToArray(); //to prevent multiple execution of "RemoveChars"
When the stored procedure returns a lot of columns and you do not want to manually "create" a temporary table to hold the result, I've found the easiest way is to go into the stored procedure and add an "into" clause on the last select statement and add 1=0 to the where clause.
Run the stored procedure once and go back and remove the SQL code you just added. Now, you'll have an empty table matching the stored procedure's result. You could either "script table as create" for a temporary table or simply insert directly into that table.
You can try this as well, it is easy to implement
TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);
Change the text to which standard time you want to change.
Use TimeZone
feature of C# to implement.
var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);
for variable:
var replaced = $("body").html().replace(new RegExp("-1o9-2202", "igm"),'The ALL new string');
$("body").html(replaced);
Simplified example (with counter):
With Me.lstbox
.ColumnCount = 2
.ColumnWidths = "60;60"
.AddItem
.List(i, 0) = Company_ID
.List(i, 1) = Company_name
i = i + 1
end with
Make sure to start the counter with 0, not 1 to fill up a listbox.
You have two ways to enable it.
First, you can set the absolute path of the php module file in your httpd.conf file like this:
LoadModule php5_module /path/to/mods-available/libphp5.so
Second, you can link the module file to the mods-enabled directory:
ln -s /path/to/mods-available/libphp5.so /path/to/mods-enabled/libphp5.so
While Hash#has_key?
gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?
.
hash.key?(some_key)
An alternative that works for me is to simply convert to a CSV.
Use the following query in sql tab:
SHOW CREATE TABLE tablename
To view full query There is this Hyperlink named +Options left above, There select Full Texts
If you want to create two table's columns into a relationship by using a query try the following:
Alter table Foreign_Key_Table_name add constraint
Foreign_Key_Table_name_Columnname_FK
Foreign Key (Column_name) references
Another_Table_name(Another_Table_Column_name)
In my case, I wanted to enable/disable the cursor when the edit is focused.
In your Activity:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (v instanceof EditText) {
EditText edit = ((EditText) v);
Rect outR = new Rect();
edit.getGlobalVisibleRect(outR);
Boolean isKeyboardOpen = !outR.contains((int)ev.getRawX(), (int)ev.getRawY());
System.out.print("Is Keyboard? " + isKeyboardOpen);
if (isKeyboardOpen) {
System.out.print("Entro al IF");
edit.clearFocus();
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
}
edit.setCursorVisible(!isKeyboardOpen);
}
}
return super.dispatchTouchEvent(ev);
}
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
Actually, above codes can be:
>>> sorted(['Some','words','sort','differently'],key=str.lower)
According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
In Angular 8 , ViewChild
takes 2 parameters:
Try like this:
@ViewChild('nameInput', { static: false }) nameInputRef: ElementRef;
Explanation:
{ static: false }
If you set static false, the child component ALWAYS gets initialized after the view initialization in time for the ngAfterViewInit/ngAfterContentInit
callback functions.
{ static: true}
If you set static true, the child component initialization will take place at the view initialization at ngOnInit
By default you can use { static: false }
. If you are creating a dynamic view and want to use the template reference variable, then you should use { static: true}
For more info, you can read this article
In the demo, we will scroll to a div using template reference variable.
@ViewChild("scrollDiv", { static: true }) scrollTo: ElementRef;
With { static: true }
, we can use this.scrollTo.nativeElement
in ngOnInit
, but with { static: false }
, this.scrollTo
will be undefined
in ngOnInit
, so we can access in only in ngAfterViewInit
A really nice function for this is adply
from plyr
, especially if you want to append the result to the original dataframe. This function and its cousin ddply
have saved me a lot of headaches and lines of code!
df_appended <- adply(df, 1, mutate, sum=x+z)
Alternatively, you can call the function you desire.
df_appended <- adply(df, 1, mutate, sum=testFunc(x,z))
In my case I was needed to have root
access.
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">
<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">
it should end up like this in the $_POST[] array (PHP format for easy visualization)
$_POST[] = array(
'firstname'=>'value',
'lastname'=>'value',
'email'=>'value',
'address'=>'value',
'tree' => array(
'tree1'=>array(
'fruit'=>'value',
'height'=>'value'
),
'tree2'=>array(
'fruit'=>'value',
'height'=>'value'
),
'tree3'=>array(
'fruit'=>'value',
'height'=>'value'
)
)
)
In Windows 10, I went to the folder where Anaconda is stored. In my case it is in \Anaconda3 folder as a shortcut to open a command prompt window, called "Anaconda Prompt". Open that and execute the command there.
Example for String Methods
Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for i in filenames:
if i.endswith(".hpp"):
x = i.replace("hpp", "h")
newfilenames.append(x)
else:
newfilenames.append(i)
print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]
Activity has six states
Activity lifecycle has seven methods
onCreate()
onStart()
onResume()
onPause()
onStop()
onRestart()
onDestroy()
Situations
When open the app
onCreate() --> onStart() --> onResume()
When back button pressed and exit the app
onPaused() -- > onStop() --> onDestory()
When home button pressed
onPaused() --> onStop()
After pressed home button when again open app from recent task list or clicked on icon
onRestart() --> onStart() --> onResume()
When open app another app from notification bar or open settings
onPaused() --> onStop()
Back button pressed from another app or settings then used can see our app
onRestart() --> onStart() --> onResume()
When any dialog open on screen
onPause()
After dismiss the dialog or back button from dialog
onResume()
Any phone is ringing and user in the app
onPause() --> onResume()
When user pressed phone's answer button
onPause()
After call end
onResume()
When phone screen off
onPaused() --> onStop()
When screen is turned back on
onRestart() --> onStart() --> onResume()
You mean
if (isset($_POST['sms_code']) == TRUE ) {
though incidentally you really mean
if (isset($_POST['sms_code'])) {
Here is a complete solution to your question using Python's built-in functions:
# Create the List
numbers = input("Enter the elements of the list. Separate each value with a comma. Do not put a comma at the end.\n").split(",")
# Convert the elements in the list (treated as strings) to integers
numberL = [int(element) for element in numbers]
# Loop through the list with a for-loop
for elements in numberL:
maxEle = max(numberL)
indexMax = numberL.index(maxEle)
print(maxEle)
print(indexMax)
for the records since this is an old post and since nobody mentioned it, check if you forgot (as I did) to set the android.permission.INTERNET flag in AndroidManifest.xml as, i.e.:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.webviewdemo">
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="@drawable/icon">
<activity android:name=".WebViewDemo" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The following should suffice:
[^ ]
If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):
[^\s]
or
\S # Note this is a CAPITAL 'S'!
The answer posted here by simon-sarris helped me.
This helped me solve my issue.
The Visual Studio installer must have added an errant line to the registry.
open up regedit and take a look at this registry key:
See that key? The Content Type key? change its value from text/plain to text/javascript.
Finally chrome can breathe easy again.
I should note that neither Content Type nor PercievedType are there by default on Windows 7, so you could probably safely delete them both, but the minimum you need to do is that edit.
Anyway I hope this fixes it for you too!
Don't forget to restart your system after the changes.
Add the Jenkinsfile where the pom.xml file has present. Provide the directory path on dir('project-dir'),
Ex:
node {
withMaven(maven:'maven') {
stage('Checkout') {
git url: 'http://xxxxxxx/gitlab/root/XXX.git', credentialsId: 'xxxxx', branch: 'xxx'
}
stage('Build') {
**dir('project-dir') {**
sh 'mvn clean install'
def pom = readMavenPom file:'pom.xml'
print pom.version
env.version = pom.version
}
}
}
}
I would like to add one further reason tests may not be found, in my case it pertained C++ unit tests that were not found.
In my case tests were not found for a particular project because its output directory was not contained within the project directory, changing this ensured the tests were found.
First, disable the currently installed version of Java. To do this, go to Control Panel > Java > Advanced > Default Java for Browsers and uncheck Microsoft Internet Explorer.
Next, enable the version of Java you want to use instead. To do this, go to (for example) C:\Program Files\Java\jre1.5.0_15\bin (where jre1.5.0_15 is the version of Java you want to use), and run javacpl.exe. Go to Advanced > Default Java for Browsers and check Microsoft Internet Explorer.
To get your old version of Java back you need to reverse these steps.
Note that in older versions of Java, Default Java for Browsers is called <APPLET> Tag Support (but the effect is the same).
The good thing about this method is that it doesn't affect other browsers, and doesn't affect the default system JRE.
WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:
using (var client = new WebClient())
{
var json = client.DownloadString("http://example.com/json");
var serializer = new JavaScriptSerializer();
SomeModel model = serializer.Deserialize<SomeModel>(json);
// TODO: do something with the model
}
There are also some REST client frameworks you may checkout such as RestSharp.
The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo
ls
show the right files?git init
? (git-init documentation)Either of those would cause your error.
Haven't tried it, but Elcomsoft released a product they claim is capable of decrypting backups, for forensics purposes. Maybe not as cool as engineering a solution yourself, but it might be faster.
There is a problem in your query..
statement =con.prepareStatement("SELECT * from employee WHERE userID = "+"''"+userID);
ResultSet rs = statement.executeQuery();
You are using Prepare Statement.. So you need to set your parameter using statement.setInt()
or statement.setString()
depending upon what is the type of your userId
Replace it with: -
statement =con.prepareStatement("SELECT * from employee WHERE userID = :userId");
statement.setString(userId, userID);
ResultSet rs = statement.executeQuery();
Or, you can use ?
in place of named value - :userId
..
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
As it's been already said, JSON spec (based on ECMAScript 3) doesn't allow trailing comma. ES >= 5 allows it, so you can actually use that notation in pure JS. It's been argued about, and some parsers did support it (http://bolinfest.com/essays/json.html, http://whereswalden.com/2010/09/08/spidermonkey-json-change-trailing-commas-no-longer-accepted/), but it's the spec fact (as shown on http://json.org/) that it shouldn't work in JSON. That thing said...
... I'm wondering why no-one pointed out that you can actually split the loop at 0th iteration and use leading comma instead of trailing one to get rid of the comparison code smell and any actual performance overhead in the loop, resulting in a code that's actually shorter, simpler and faster (due to no branching/conditionals in the loop) than other solutions proposed.
E.g. (in a C-style pseudocode similar to OP's proposed code):
s.append("[");
// MAX == 5 here. if it's constant, you can inline it below and get rid of the comparison
if ( MAX > 0 ) {
s.appendF("\"%d\"", 0); // 0-th iteration
for( int i = 1; i < MAX; ++i ) {
s.appendF(",\"%d\"", i); // i-th iteration
}
}
s.append("]");
Assuming that you have a form that is huge or simply you do not want to reset each form field one by one, you can reset all the fields of the form by iterating through the fields one by one
var self = this;
Object.keys(this.data.form).forEach(function(key,index) {
self.data.form[key] = '';
});
The above will reset all fields of the given this.data.form
object to empty string. Let's say there are one or two fields that you selectively want to set to a specific value in that case inside the above block you can easily put a condition based on field name
if(key === "country")
self.data.form[key] = 'Canada';
else
self.data.form[key] = '';
Or if you want to reset the field based on type and you have boolean and other field types in that case
if(typeof self.data.form[key] === "string")
self.data.form[key] = '';
else if (typeof self.data.form[key] === "boolean")
self.data.form[key] = false;
For more type info see here
A basic vuejs
template and script sample would look as follow
<template>
<div>
<form @submit.prevent="onSubmit">
<input type="text" class="input" placeholder="User first name" v-model="data.form.firstName">
<input type="text" class="input" placeholder="User last name" v-model="data.form.lastName">
<input type="text" class="input" placeholder="User phone" v-model="data.form.phone">
<input type="submit" class="button is-info" value="Add">
<input type="button" class="button is-warning" @click="resetForm()" value="Reset Form">
</form>
</div>
</template>
See ow the @submit.prevent="onSubmit"
is used in the form element. That would by default, prevent the form submission and call the onSubmit
function.
Let's assume we have the following for the above
<script>
export default {
data() {
return {
data: {
form: {
firstName: '',
lastName: '',
phone: ''
}
}
}
},
methods: {
onSubmit: function() {
console.log('Make API request.')
this.resetForm(); //clear form automatically after successful request
},
resetForm() {
console.log('Reseting the form')
var self = this; //you need this because *this* will refer to Object.keys below`
//Iterate through each object field, key is name of the object field`
Object.keys(this.data.form).forEach(function(key,index) {
self.data.form[key] = '';
});
}
}
}
</script>
You can call the resetForm
from anywhere and it will reset your form fields.
You can use a function like strtol()
which will convert a character array to a long.
It has a parameter which is a way to detect the first character that didn't convert properly. If this is anything other than the end of the string, then you have a problem.
See the following program for an example:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[]) {
int i;
long val;
char *next;
// Process each argument given.
for (i = 1; i < argc; i++) {
// Get value with failure detection.
val = strtol (argv[i], &next, 10);
// Check for empty string and characters left after conversion.
if ((next == argv[i]) || (*next != '\0')) {
printf ("'%s' is not valid\n", argv[i]);
} else {
printf ("'%s' gives %ld\n", argv[i], val);
}
}
return 0;
}
Running this, you can see it in operation:
pax> testprog hello "" 42 12.2 77x
'hello' is not valid
'' is not valid
'42' gives 42
'12.2' is not valid
'77x' is not valid
I faced an issue in direct download because I was logged in using multiple Google accounts.
Solution is append authUser=0
parameter. Sample request URL to download :https://drive.google.com/uc?id=FILEID&authuser=0&export=download
I think, is better to use it like this: (in RecyclerView adapter override just a one method)
override fun onViewAttachedToWindow(holder: ViewHolder) {
super.onViewAttachedToWindow(holder)
setBindAnimation(holder)
}
If You want every attach animation there in RV.
It's possible, but it requires using dynamic SQL.
I recommend reading The curse and blessings of dynamic SQL before continuing...
DECLARE @theDate varchar(60)
SET @theDate = '''2010-01-01'' AND ''2010-08-31 23:59:59'''
DECLARE @SQL VARCHAR(MAX)
SET @SQL = 'SELECT AdministratorCode,
SUM(Total) as theTotal,
SUM(WOD.Quantity) as theQty,
AVG(Total) as avgTotal,
(SELECT SUM(tblWOD.Amount)
FROM tblWOD
JOIN tblWO on tblWOD.OrderID = tblWO.ID
WHERE tblWO.Approved = ''1''
AND tblWO.AdministratorCode = tblWO.AdministratorCode
AND tblWO.OrderDate BETWEEN '+ @theDate +')'
EXEC(@SQL)
Dynamic SQL is just a SQL statement, composed as a string before being executed. So the usual string concatenation occurs. Dynamic SQL is required whenever you want to do something in SQL syntax that isn't allowed, like:
EXEC sp_executesql
allows you to use bind/preparedstatement parameters so you don't have to concern yourself with escaping single quotes/etc for SQL injection attacks.
You can use reduce() - A functional way.
words = "apple banana apple strawberry banana lemon"
reduce( lambda d, c: d.update([(c, d.get(c,0)+1)]) or d, words.split(), {})
returns:
{'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 2}
The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:
import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square')
plt.xlabel('x')
plt.ylabel('y')
plt.xticks(xi, x)
plt.title('compare')
plt.legend()
plt.show()
Google now has a feature stating that it won't allow insecure devices to send emails. When I ran my program it came up with the error in the first post. I had to go into my account and allow insecure apps to send emails, which I did by clicking on my account, going into the security tab, and allowing insecure apps to use my gmail.
$focusable:
'a[href]',
'area[href]',
'button',
'details',
'input',
'iframe',
'select',
'textarea',
// these are actually case sensitive but i'm not listing out all the possible variants
'[contentEditable=""]',
'[contentEditable="true"]',
'[contentEditable="TRUE"]',
'[tabindex]:not([tabindex^="-"])',
':not([disabled])';
I'm creating a SCSS list of all focusable elements and I thought this might help someone due to this question's Google rank.
A few things to note:
:not([tabindex="-1"])
to :not([tabindex^="-"])
because it's perfectly plausible to generate -2
somehow. Better safe than sorry right?:not([tabindex^="-"])
to all the other focusable selectors is completely pointless. When using [tabindex]:not([tabindex^="-"])
it already includes all elements that you'd be negating with :not
!:not([disabled])
because disabled elements can never be focusable. So again it's useless to add it to every single element.I would probably use regexp matches if the input has only a few valid entries. E.g. only the "start" and "stop" are valid actions.
if [[ "${ACTION,,}" =~ ^(start|stop)$ ]]; then
echo "valid action"
fi
Note that I lowercase the variable $ACTION
by using the double comma's. Also note that this won't work on too aged bash versions out there.
Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.
You have to decide if:
If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)
If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:
If you give more details about your stack, it's easier to provide examples or resources.
EDIT: For client side JS highlighting you can try higlight.js, for instance.
You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one
If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage
Ex: using localStorage and cookies library
var mode = getStoredValue('myPageMode');
function buttonClick(mode) {
mode = mode;
storeValue('myPageMode', mode);
}
function storeValue(key, value) {
if (localStorage) {
localStorage.setItem(key, value);
} else {
$.cookies.set(key, value);
}
}
function getStoredValue(key) {
if (localStorage) {
return localStorage.getItem(key);
} else {
return $.cookies.get(key);
}
}
This overloaded version of the save function works for me:
yourDF.save(outputPath, org.apache.spark.sql.SaveMode.valueOf("Overwrite"))
The example above would overwrite an existing folder. The savemode can take these parameters as well (https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/sql/SaveMode.html):
Append: Append mode means that when saving a DataFrame to a data source, if data/table already exists, contents of the DataFrame are expected to be appended to existing data.
ErrorIfExists: ErrorIfExists mode means that when saving a DataFrame to a data source, if data already exists, an exception is expected to be thrown.
Ignore: Ignore mode means that when saving a DataFrame to a data source, if data already exists, the save operation is expected to not save the contents of the DataFrame and to not change the existing data.
.gitkeep
is just a placeholder. A dummy file, so Git will not forget about the directory, since Git tracks only files.
If you want an empty directory and make sure it stays 'clean' for Git, create a .gitignore
containing the following lines within:
# .gitignore sample
###################
# Ignore all files in this dir...
*
# ... except for this one.
!.gitignore
If you desire to have only one type of files being visible to Git, here is an example how to filter everything out, except .gitignore and all .txt
files:
# .gitignore to keep just .txt files
###################################
# Filter everything...
*
# ... except the .gitignore...
!.gitignore
# ... and all text files.
!*.txt
('#' indicates comments.)
import telnetlib
user = "admin"
password = "\r"
def connect(A):
tnA = telnetlib.Telnet(A)
tnA.read_until('username: ', 3)
tnA.write(user + '\n')
tnA.read_until('password: ', 3)
tnA.write(password + '\n')
return tnA
def quit_telnet(tn)
tn.write("bye\n")
tn.write("quit\n")
I want to point out that setting a SimpleDateFormat
like described in the other answer only works for a java.util.Date
which I assume is meant in the question.
But for java.sql.Date
the formatter does not work.
In my case it was not very obvious why the formatter did not work because in the model which should be serialized the field was in fact a java.utl.Date
but the actual object ended up beeing a java.sql.Date
.
This is possible because
public class java.sql extends java.util.Date
So this is actually valid
java.util.Date date = new java.sql.Date(1542381115815L);
So if you are wondering why your Date field is not correctly formatted make sure that the object is really a java.util.Date
.
Here is also mentioned why handling java.sql.Date
will not be added.
This would then be breaking change, and I don't think that is warranted. If we were starting from scratch I would agree with the change, but as things are not so much.
From your description, what you probably want is os.Readdirnames.
func (f *File) Readdirnames(n int) (names []string, err error)
Readdirnames reads the contents of the directory associated with file and returns a slice of up to n names of files in the directory, in directory order. Subsequent calls on the same file will yield further names.
...
If n <= 0, Readdirnames returns all the names from the directory in a single slice.
Snippet:
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
names, err := file.Readdirnames(0)
if err != nil {
return err
}
fmt.Println(names)
Credit to SquattingSlavInTracksuit's comment; I'd have suggested promoting their comment to an answer if I could.
Like you say, you need to show some code. :-)
A stack overflow error usually happens when your function calls nest too deeply. See the Stack Overflow Code Golf thread for some examples of how this happens (though in the case of that question, the answers intentionally cause stack overflow).
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('host', 'port', service_name='give service name')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
c = conn.cursor()
c.execute('select count(*) from schema.table_name')
for row in c:
print row
conn.close()
Note :
In (dsn_tns) if needed, place an 'r' before any parameter in order to address any special character such as '\'.
In (conn) if needed, place an 'r' before any parameter in order to address any special character such as '\'. For example, if your user name contains '\', you'll need to place 'r' before the user name: user=r'User Name' or password=r'password'
use triple quotes if you want to spread your query across multiple lines.
Exception code 0xc0000005
is an Access Violation. An AV at fault offset 0x00000000
means that something in your service's code is accessing a nil
pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.
See: http://predef.sourceforge.net/index.php
This project provides a reasonably comprehensive listing of pre-defined #defines
for many operating systems, compilers, language and platform standards, and standard libraries.
Since C++ 17 (VS2015) you can use the standard for read-write locks:
#include <shared_mutex>
typedef std::shared_mutex Lock;
typedef std::unique_lock< Lock > WriteLock;
typedef std::shared_lock< Lock > ReadLock;
Lock myLock;
void ReadFunction()
{
ReadLock r_lock(myLock);
//Do reader stuff
}
void WriteFunction()
{
WriteLock w_lock(myLock);
//Do writer stuff
}
For older version, you can use boost with the same syntax:
#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>
typedef boost::shared_mutex Lock;
typedef boost::unique_lock< Lock > WriteLock;
typedef boost::shared_lock< Lock > ReadLock;
Does it have to be a string[] ? A List<String> would give you what you need.
List<String> testing = new List<String>();
testing.Add("One");
testing.Add("Two");
testing.Add("Three");
testing.Add("Mouse");
bool inList = testing.Contains("Mouse");
BEST Approach:
I will not recommend removing public, instead on local computer create a virtual host point to public directory
and on remote hosting change public to public_html and point your domain to this directory
. Reason, your whole laravel code will be secure because its one level down to your public directory :)
I just rename server.php
to index.php
and it works
This work well for all laravel version...
Here is my Directory Structure,
/laravel/
... app
... bootstrap
... public
... etc
Follow these easy steps
require DIR.'/../bootstrap/autoload.php';
to
require DIR.'/bootstrap/autoload.php';
and
$app = require_once DIR.'/../bootstrap/start.php';
to
$app = require_once DIR.'/bootstrap/start.php';
'public' => DIR.'/../public',
to
'public' => DIR.'/..',
and that's it, now try http:// localhost/laravel/
Google Apps Script will not open automatically web pages, but it could be used to display a message with links, buttons that the user could click on them to open the desired web pages or even to use the Window object and methods like addEventListener() to open URLs.
It's worth to note that UiApp is now deprecated. From Class UiApp - Google Apps Script - Google Developers
Deprecated. The UI service was deprecated on December 11, 2014. To create user interfaces, use the HTML service instead.
The example in the HTML Service linked page is pretty simple,
Code.gs
// Use this code for Google Docs, Forms, or new Sheets.
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Dialog')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'Dialog title');
}
A customized version of index.html to show two hyperlinks
<a href='http://stackoverflow.com' target='_blank'>Stack Overflow</a>
<br/>
<a href='http://meta.stackoverflow.com/' target='_blank'>Meta Stack Overflow</a>
I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.
ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl)
REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back
However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)
Debug -> Delete All Breakpoints ( http://darrinbishop.com/blog/2010/06/sharepoint-2010-hangs-after-visual-studio-2010-f5-debugging ) After that you can use them again, but do it once. It will remove some kind of "invalid" breakpoints too and then loading symbols will be fast again. I was chasing this issue for days :(.
Have a look at this example taken from the spring MVC showcase, this is the link to the source code:
@RunWith(SpringJUnit4ClassRunner.class)
public class FileUploadControllerTests extends AbstractContextControllerTests {
@Test
public void readString() throws Exception {
MockMultipartFile file = new MockMultipartFile("file", "orig", null, "bar".getBytes());
webAppContextSetup(this.wac).build()
.perform(fileUpload("/fileupload").file(file))
.andExpect(model().attribute("message", "File 'orig' uploaded successfully"));
}
}
This might be due to a security check. This thread might help you.
There are two suggestions: one with pushd and one with a registry change. I'd suggest to use the first one...
Truncate Pipe with optional params:
-
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 25, completeWords = false, ellipsis = '...') {
if (completeWords) {
limit = value.substr(0, limit).lastIndexOf(' ');
}
return value.length > limit ? value.substr(0, limit) + ellipsis : value;
}
}
Don't forget to add a module entry.
@NgModule({
declarations: [
TruncatePipe
]
})
export class AppModule {}
Usage
Example String:
public longStr = 'A really long string that needs to be truncated';
Markup:
<h1>{{longStr | truncate }}</h1>
<!-- Outputs: A really long string that... -->
<h1>{{longStr | truncate : 12 }}</h1>
<!-- Outputs: A really lon... -->
<h1>{{longStr | truncate : 12 : true }}</h1>
<!-- Outputs: A really... -->
<h1>{{longStr | truncate : 12 : false : '***' }}</h1>
<!-- Outputs: A really lon*** -->
my sample code
wv = (WebView) findViewById(R.id.mywebview);
wv.getLayoutParams().height = LayoutParams.MATCH_PARENT; // LayoutParams: android.view.ViewGroup.LayoutParams
// wv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
wv.requestLayout();//It is necesary to refresh the screen
Use the value attribute of the button element to pass the id, as
<button onClick={this.handleRemove} value={id}>Remove</button>
and then in handleRemove, read the value from event as:
handleRemove(event) {
...
remove(event.target.value);
...
}
This way you avoid creating a new function (when compared to using an arrow function) every time this component is re-rendered.
I had a similar problem. I was attempting to have a file written every time a user visits a website.
The problem ended up being twofold.
1: the permissions were not set correctly
2: I attempted to use
f = open(r"newfile.txt","w+")
(Wrong)
After changing the file to 777 (all users can read/write)
chmod 777 /var/www/path/to/file
and changing the path to an absolute path, my problem was solved
f = open(r"/var/www/path/to/file/newfile.txt","w+")
(Right)
In my case, same error was coming with JSP. This is how I got to the root of this issue: I went to the Network tab and clearly saw that the browser request to fetch the css was returning response header having "Content-type" : "text/html". I opened another tab and manually hit the request to fetch the css. It ended up returning a html log in form. Turns out that my web application had a url mapping for path = /
Tomcat servlet entry : (@WebServlet({ "/, /index", })
. So, any unmatching request URLs were somehow being matched to /
and the corresponding servlet was returning a Log in html form. I fixed it by removing the mapping to /
Also, the tomcat configuration wrt handling css MIME-TYPE was already present.
The best and recommended way is to use Qt Style Sheet.
To change the text color and background color of a QLabel
, here is what I would do :
QLabel* pLabel = new QLabel;
pLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");
You could also avoid using Qt Style Sheets and change the QPalette
colors of your QLabel
, but you might get different results on different platforms and/or styles.
As Qt documentation states :
Using a QPalette isn't guaranteed to work for all styles, because style authors are restricted by the different platforms' guidelines and by the native theme engine.
But you could do something like this :
QPalette palette = ui->pLabel->palette();
palette.setColor(ui->pLabel->backgroundRole(), Qt::yellow);
palette.setColor(ui->pLabel->foregroundRole(), Qt::yellow);
ui->pLabel->setPalette(palette);
But as I said, I strongly suggest not to use the palette and go for Qt Style Sheet.
To disable all rules on a specific line:
alert('foo'); // eslint-disable-line
Q1) Here are couple things to read or google more :
Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest
It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.
Q2) Here are couple of good tutorials for soap (I had them bookmarked) :
http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/
http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html
Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.
SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.
Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).
Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.
If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development
.
It's fantastic, not hard to read and not too big either (win win).
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
Its very simple though conditions in this answer are in mysql the column datatype is datetime and you want to send data from java code to mysql:
java.util.Date dt = new java.util.Date();
whatever your code object may be
.setDateTime(dt);
important thing is just pick the date and its format is already as per mysql format and send it, no further modifications required.
Create unique constraint that two numbers together CANNOT together be repeated:
ALTER TABLE someTable
ADD UNIQUE (col1, col2)
[EDIT: this was a stupid suggestion from a time I did not know Vim well enough. Please don't use tabs instead of buffers; tabs are Vim's "window layouts"]
Maybe switch to using tabs?
vim -p a/*.php
opens the same files in tabs
gt
and gT
switch tabs back and forth
:q
closes only the current tab
:qa
closes everything and exits
:tabo
closes everything but the current tab
In getUserById
you shouldn't create a new object (user1) which isn't used. Just assign it to the already (but null) initialized user
. Otherwise Hibernate.initialize(user);
is actually Hibernate.initialize(null);
Here's the new getUserById
(I haven't tested this ;)):
public User getUserById(Long user_id) {
Session session = null;
Object user = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
user = (User)session.load(User.class, user_id);
Hibernate.initialize(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return user;
}
day1= (int)ClockInfoFromSystem.DayOfWeek;
The best way is:
After that you can copy that code, and paste it in your computer.
According to this Egnyte article, Passive FTP is supported from Windows 8.1 onwards.
The Registry key:
"HKEY_CURRENT_USER\Software\Microsoft\FTP\Use PASV"
should be set with the value: yes
If you don't like poking around in the Registry, do the following:
inetcpl.cpl
and press Enter. The Internet Options dialog will open.Every time you use ftp.exe
, remember to pass the
quote pasv
command immediately after logging in to a remote host.
PS: Grant ftp.exe
access to private networks if your Firewall complains.
You don't have an element with the id u
.That's why the error occurs.
Note that the global variable document.getElementById("u").value
means you are trying to get the value of input element with name u
and its not defined in your code.
I was having this same issue, but the answer I found was different, thought someone might come across this issue, so here is my solution.
I had to whitelist 2 IPs for port 22
, 80
, 443
, and 9418
:
192.30.252.0/22
185.199.108.0/22
In case these IP's don't work, it might be because they got updated, you can find the most current ones on this page.
I'm late for the party but I hope that my response will help someone: You can do this in your Python script:
import sys, os
sys.path.append('/path/to/your/django/app')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
the rest of your stuff goes here ....
A token
is a piece of data which only Server X
could possibly have created, and which contains enough data to identify a particular user.
You might present your login information and ask Server X
for a token
; and then you might present your token
and ask Server X
to perform some user-specific action.
Token
s are created using various combinations of various techniques from the field of cryptography as well as with input from the wider field of security research. If you decide to go and create your own token
system, you had best be really smart.
cgi.escape
is fine. It escapes:
<
to <
>
to >
&
to &
That is enough for all HTML.
EDIT: If you have non-ascii chars you also want to escape, for inclusion in another encoded document that uses a different encoding, like Craig says, just use:
data.encode('ascii', 'xmlcharrefreplace')
Don't forget to decode data
to unicode
first, using whatever encoding it was encoded.
However in my experience that kind of encoding is useless if you just work with unicode
all the time from start. Just encode at the end to the encoding specified in the document header (utf-8
for maximum compatibility).
Example:
>>> cgi.escape(u'<a>bá</a>').encode('ascii', 'xmlcharrefreplace')
'<a>bá</a>
Also worth of note (thanks Greg) is the extra quote
parameter cgi.escape
takes. With it set to True
, cgi.escape
also escapes double quote chars ("
) so you can use the resulting value in a XML/HTML attribute.
EDIT: Note that cgi.escape has been deprecated in Python 3.2 in favor of html.escape
, which does the same except that quote
defaults to True.
I just wanted to add and give some more context on why we have these levels of test, what they really mean with examples
Mike Cohn in his book “Succeeding with Agile” came up with the “Testing Pyramid” as a way to approach automated tests in projects. There are various interpretations of this model. The model explains what kind of automated tests need to be created, how fast they can give feedback on the application under test and who writes these tests. There are basically 3 levels of automated testing needed for any project and they are as follows.
Unit Tests- These test the smallest component of your software application. This could literally be one function in a code which computes a value based on some inputs. This function is part of several other functions of the hardware/software codebase that makes up the application.
For example - Let’s take a web based calculator application. The smallest components of this application that needs to be unit tested could be a function that performs addition, another that performs subtraction and so on. All these small functions put together makes up the calculator application.
Historically developer writes these tests as they are usually written in the same programming language as the software application. Unit testing frameworks such as JUnit and NUnit (for java), MSTest (for C# and .NET) and Jasmine/Mocha (for JavaScript) are used for this purpose.
The biggest advantage of unit tests are, they run really fast underneath the UI and we can get quick feedback about the application. This should comprise more than 50% of your automated tests.
API/Integration Tests- These test various components of the software system together. The components could include testing databases, API’s (Application Programming Interface), 3rd party tools and services along with the application.
For example - In our calculator example above, the web application may use a database to store values, use API’s to do some server side validations and it may use a 3rd party tool/service to publish results to the cloud to make it available across different platforms.
Historically a developer or technical QA would write these tests using various tools such as Postman, SoapUI, JMeter and other tools like Testim.
These run much faster than UI tests as they still run underneath the hood but may consume a little more time than unit tests as it has to check the communication between various independent components of the system and ensure they have seamless integration. This should comprise more that 30% of the automated tests.
UI Tests- Finally, we have tests that validate the UI of the application. These tests are usually written to test end to end flows through the application.
For example - In the calculator application, an end to end flow could be, opening up the browser-> Entering the calculator application url -> Logging in with username/password -> Opening up the calculator application -> Performing some operations on the calculator -> verifying those results from the UI -> Logging out of the application. This could be one end to end flow that would be a good candidate for UI automation.
Historically, technical QA’s or manual testers write UI tests. They use open source frameworks like Selenium or UI testing platforms like Testim to author, execute and maintain the tests. These tests give more visual feedback as you can see how the tests are running, the difference between the expected and actual results through screenshots, logs, test reports.
The biggest limitation of UI tests is, they are relatively slow compared to Unit and API level tests. So, it should comprise only 10-20% of the overall automated tests.
The next two types of tests can vary based on your project but the idea is-
Smoke Tests
This can be a combination of the above 3 levels of testing. The idea is to run it during every code check in and ensure the critical functionalities of the system are still working as expected; after the new code changes are merged. They typically need to run with 5 - 10 mins to get faster feedback on failures
Regression Tests
They usually are run once a day at least and cover various functionalities of the system. They ensure the application is still working as expected. They are more details than the smoke tests and cover more scenarios of the application including the non-critical ones.
Set java version from the list of installed. For see the list of the installed version run following command:
update-java-alternatives --list
Then set your java version according to the following command:
sudo update-java-alternatives --set /usr/lib/jvm/java-1.8.0-openjdk-amd64
Go to File->Project Structure->SDK Location and check if the path for SDK and JDK location specified by you is correct. If its not then set the correct path. Then It will work.
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
I had a similar issue and solved it with a patch to ec2.py and adding some configuration parameters to ec2.ini. The patch takes the value of ec2_key_name, prefixes it with the ssh_key_path, and adds the ssh_key_suffix to the end, and writes out ansible_ssh_private_key_file as this value.
The following variables have to be added to ec2.ini in a new 'ssh' section (this is optional if the defaults match your environment):
[ssh]
# Set the path and suffix for the ssh keys
ssh_key_path = ~/.ssh
ssh_key_suffix = .pem
Here is the patch for ec2.py:
204a205,206
> 'ssh_key_path': '~/.ssh',
> 'ssh_key_suffix': '.pem',
422a425,428
> # SSH key setup
> self.ssh_key_path = os.path.expanduser(config.get('ssh', 'ssh_key_path'))
> self.ssh_key_suffix = config.get('ssh', 'ssh_key_suffix')
>
1490a1497
> instance_vars["ansible_ssh_private_key_file"] = os.path.join(self.ssh_key_path, instance_vars["ec2_key_name"] + self.ssh_key_suffix)
For the full list of snippets (little bits of prefabricated code) press Ctrl+K and then Ctrl+X. Source from MSDN. Works in Visual Studio 2013 with a C# project.
So how to make a constructor
Update: You can also right-click in your code where you want the snippet, and select Insert Snippet from the right-click menu
The answers only cover DOM / SAX and a copy paste implementation of a JAXB example.
However, one big area of when you are using XML is missing. In many projects / programs there is a need to store / retrieve some basic data structures. Your program has already a classes for your nice and shiny business objects / data structures, you just want a comfortable way to convert this data to a XML structure so you can do more magic on it (store, load, send, manipulate with XSLT).
This is where XStream shines. You simply annotate the classes holding your data, or if you do not want to change those classes, you configure a XStream instance for marshalling (objects -> xml) or unmarshalling (xml -> objects).
Internally XStream uses reflection, the readObject and readResolve methods of standard Java object serialization.
You get a good and speedy tutorial here:
To give a short overview of how it works, I also provide some sample code which marshalls and unmarshalls a data structure.
The marshalling / unmarshalling happens all in the main
method, the rest is just code to generate some test objects and populate some data to them.
It is super simple to configure the xStream
instance and marshalling / unmarshalling is done with one line of code each.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
public class XStreamIsGreat {
public static void main(String[] args) {
XStream xStream = new XStream();
xStream.alias("good", Good.class);
xStream.alias("pRoDuCeR", Producer.class);
xStream.alias("customer", Customer.class);
Producer a = new Producer("Apple");
Producer s = new Producer("Samsung");
Customer c = new Customer("Someone").add(new Good("S4", 10, new BigDecimal(600), s))
.add(new Good("S4 mini", 5, new BigDecimal(450), s)).add(new Good("I5S", 3, new BigDecimal(875), a));
String xml = xStream.toXML(c); // objects -> xml
System.out.println("Marshalled:\n" + xml);
Customer unmarshalledCustomer = (Customer)xStream.fromXML(xml); // xml -> objects
}
static class Good {
Producer producer;
String name;
int quantity;
BigDecimal price;
Good(String name, int quantity, BigDecimal price, Producer p) {
this.producer = p;
this.name = name;
this.quantity = quantity;
this.price = price;
}
}
static class Producer {
String name;
public Producer(String name) {
this.name = name;
}
}
static class Customer {
String name;
public Customer(String name) {
this.name = name;
}
List<Good> stock = new ArrayList<Good>();
Customer add(Good g) {
stock.add(g);
return this;
}
}
}
For someone who is new to IPC and Named Pipes, I found the following NuGet package to be a great help.
GitHub: Named Pipe Wrapper for .NET 4.0
To use first install the package:
PS> Install-Package NamedPipeWrapper
Then an example server (copied from the link):
var server = new NamedPipeServer<SomeClass>("MyServerPipe");
server.ClientConnected += delegate(NamedPipeConnection<SomeClass> conn)
{
Console.WriteLine("Client {0} is now connected!", conn.Id);
conn.PushMessage(new SomeClass { Text: "Welcome!" });
};
server.ClientMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
{
Console.WriteLine("Client {0} says: {1}", conn.Id, message.Text);
};
server.Start();
Example client:
var client = new NamedPipeClient<SomeClass>("MyServerPipe");
client.ServerMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
{
Console.WriteLine("Server says: {0}", message.Text);
};
client.Start();
Best thing about it for me is that unlike the accepted answer here it supports multiple clients talking to a single server.
Another, more humane way:
find /<directory> -newermt "-24 hours" -ls
or:
find /<directory> -newermt "1 day ago" -ls
or:
find /<directory> -newermt "yesterday" -ls
For IIS 7.5+ with URL Rewrite 2.0 module installed please see this SO answer
Just subtract the two dates:
select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;
The result will be the difference in days.
More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042
for PHP developer
filter_var($value, FILTER_VALIDATE_MAC)
So, if you have a statement something like the following, you're saying that you get no 'print' result?
select * from sysobjects PRINT 'Just selected * from sysobjects'
If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the timing of seeing the print statements, you may want to try using something like
raiserror ('My Print Statement', 10,1) with nowait
This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.
You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html
geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.
ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()
After making no changes to a production server we began receiving this error. After trying several different things and thinking that perhaps there were DNS issues, restarting IIS fixed the issue (restarting only the site did not fix the issue). It likely won't work for everyone but if we tried that first it would have saved a lot of time.
import sys
def func_name():
"""
:return: name of caller
"""
return sys._getframe(1).f_code.co_name
class A(object):
def __init__(self):
pass
def test_class_func_name(self):
print(func_name())
def test_func_name():
print(func_name())
Test:
a = A()
a.test_class_func_name()
test_func_name()
Output:
test_class_func_name
test_func_name
Simple solution in swift
let navigationBar = self.navigationController?.navigationBar
navigationBar?.setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
navigationBar?.shadowImage = UIImage()
Short answer: classmaps are static while PSR autoloading is dynamic.
If you don't want to use classmaps, use PSR autoloading instead.
//simple example creating a list form a string array
String[] myStrings = new String[] {"Elem1","Elem2","Elem3","Elem4","Elem5"};
List mylist = Arrays.asList(myStrings );
//getting an iterator object to browse list items
Iterator itr= mylist.iterator();
System.out.println("Displaying List Elements,");
while(itr.hasNext())
System.out.println(itr.next());
In addition to the solution that other people provided (which are good, and correct), there is a way to specify the ViewModel in XAML, yet still separate the specific ViewModel from the View. Separating them is useful for when you want to write isolated test cases.
In App.xaml:
<Application
x:Class="BuildAssistantUI.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BuildAssistantUI.ViewModels"
StartupUri="MainWindow.xaml"
>
<Application.Resources>
<local:MainViewModel x:Key="MainViewModel" />
</Application.Resources>
</Application>
In MainWindow.xaml:
<Window x:Class="BuildAssistantUI.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{StaticResource MainViewModel}"
/>
In Addition to the accepted answer: My scipt gave me an error
File "c:\Python23\lib\urllib2.py", line 580, in proxy_open
if '@' in host:
TypeError: iterable argument required
Solution was to add http:// in front of the proxy string:
proxy = urllib2.ProxyHandler({'http': 'http://proxy.xy.z:8080'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')
If you explicitly cast double
to int
, the decimal part will be truncated. For example:
int x = (int) 4.97542; //gives 4 only
int x = (int) 4.23544; //gives 4 only
Moreover, you may also use Math.floor()
method to round values in case you want double
value in return.
Here is code you can directly copy paste :
String imageName = "picture1.jpg";
String [] imageNameArray = imageName.split("\\.");
for(int i =0; i< imageNameArray.length ; i++)
{
system.out.println(imageNameArray[i]);
}
And what if mistakenly there are spaces left before or after "." in such cases? It's always best practice to consider those spaces also.
String imageName = "picture1 . jpg";
String [] imageNameArray = imageName.split("\\s*.\\s*");
for(int i =0; i< imageNameArray.length ; i++)
{
system.out.println(imageNameArray[i]);
}
Here, \\s* is there to consider the spaces and give you only required splitted strings.
vector<vector> matrix(row, vector(col, 0));
This will initialize a 2D vector of rows=row and columns = col with all initial values as 0. No need to initialize and use resize.
Since the vector is initialized with size, you can use "[]" operator as in array to modify the vector.
matrix[x][y] = 2;
One possible solution which works for me:
Bravo!
You can download the gradle you want from Gradle Service by reading the gradle-wrapper.properties.Download it ,unpack it where you like and then change your grandle configuration use local not the recommended.
To answer the original question:
HTMLDocument doc = new HTMLDocument();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
doc2.write(fileText);
// now use doc
Then to convert back to a string:
doc.documentElement.outerHTML;
Starting with Windows 10 version 1803 (and earlier, with insider build 17063), you don't install curl
anymore. Windows includes a native curl.exe
(and tar.exe
) in C:\Windows\System32\
, which you can access right from your regular CMD
.
C:\Users\vonc>C:\Windows\System32\curl.exe --version
curl 7.55.1 (Windows) libcurl/7.55.1 WinSSL
Release-Date: [unreleased]
Protocols: dict file ftp ftps http https imap imaps pop3 pop3s smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL
C:\Users\vonc>C:\Windows\System32\tar.exe --version
bsdtar 3.3.2 - libarchive 3.3.2 zlib/1.2.5.f-ipp
window.location.href = window.location.href
Unsorted vector:
if (std::find(v.begin(), v.end(),value)!=v.end())
...
Sorted vector:
if (std::binary_search(v.begin(), v.end(), value)
...
P.S. may need to include <algorithm>
header
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
You would have to configure your webserver to utilize PHP as handler for .html
files. This is typically done by modifying your with AddHandler
to include .html
along with .php
.
Note that this could have a performance impact as this would cause ALL .html files to be run through PHP handler even if there is no PHP involved. So you might strongly consider using .php
extension on these files and adding a redirect as necessary to route requests to specific .html URL's to their .php equivalents.
Here are seven steps to install spark on windows 10 and run it from python:
Step 1: download the spark 2.2.0 tar (tape Archive) gz file to any folder F from this link - https://spark.apache.org/downloads.html. Unzip it and copy the unzipped folder to the desired folder A. Rename the spark-2.2.0-bin-hadoop2.7 folder to spark.
Let path to the spark folder be C:\Users\Desktop\A\spark
Step 2: download the hardoop 2.7.3 tar gz file to the same folder F from this link - https://www.apache.org/dyn/closer.cgi/hadoop/common/hadoop-2.7.3/hadoop-2.7.3.tar.gz. Unzip it and copy the unzipped folder to the same folder A. Rename the folder name from Hadoop-2.7.3.tar to hadoop. Let path to the hadoop folder be C:\Users\Desktop\A\hadoop
Step 3: Create a new notepad text file. Save this empty notepad file as winutils.exe (with Save as type: All files). Copy this O KB winutils.exe file to your bin folder in spark - C:\Users\Desktop\A\spark\bin
Step 4: Now, we have to add these folders to the System environment.
4a: Create a system variable (not user variable as user variable will inherit all the properties of the system variable) Variable name: SPARK_HOME Variable value: C:\Users\Desktop\A\spark
Find Path system variable and click edit. You will see multiple paths. Do not delete any of the paths. Add this variable value - ;C:\Users\Desktop\A\spark\bin
4b: Create a system variable
Variable name: HADOOP_HOME Variable value: C:\Users\Desktop\A\hadoop
Find Path system variable and click edit. Add this variable value - ;C:\Users\Desktop\A\hadoop\bin
4c: Create a system variable Variable name: JAVA_HOME Search Java in windows. Right click and click open file location. You will have to again right click on any one of the java files and click on open file location. You will be using the path of this folder. OR you can search for C:\Program Files\Java. My Java version installed on the system is jre1.8.0_131. Variable value: C:\Program Files\Java\jre1.8.0_131\bin
Find Path system variable and click edit. Add this variable value - ;C:\Program Files\Java\jre1.8.0_131\bin
Step 5: Open command prompt and go to your spark bin folder (type cd C:\Users\Desktop\A\spark\bin). Type spark-shell.
C:\Users\Desktop\A\spark\bin>spark-shell
It may take time and give some warnings. Finally, it will show welcome to spark version 2.2.0
Step 6: Type exit() or restart the command prompt and go the spark bin folder again. Type pyspark:
C:\Users\Desktop\A\spark\bin>pyspark
It will show some warnings and errors but ignore. It works.
Step 7: Your download is complete. If you want to directly run spark from python shell then: go to Scripts in your python folder and type
pip install findspark
in command prompt.
In python shell
import findspark
findspark.init()
import the necessary modules
from pyspark import SparkContext
from pyspark import SparkConf
If you would like to skip the steps for importing findspark and initializing it, then please follow the procedure given in importing pyspark in python shell
Boostrap has a class for that called navbar-right
. So your code will look as follows:
<ul class="nav navbar-right">
<li class="dropdown">
<a class="dropdown-toggle" href="#" data-toggle="dropdown">Link</a>
<ul class="dropdown-menu">
<li>...</li>
</ul>
</li>
</ul>
var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;
function changeIframe() {
$('#frame')[0].src = sites[index++];
index = index >= sites.length ? 0 : index;
}
If you use a Datetime format see http://php.net/manual/en/datetime.format.php
You can do this :
$date = new \DateTime();
echo date_format($date, 'Y-m-d H:i:s');
#output: 2012-03-24 17:45:12
echo date_format($date, 'G:ia');
#output: 05:45pm
Following code shows how to upload a file to a SFTP server using our Rebex SFTP component.
// create client, connect and log in
Sftp client = new Sftp();
client.Connect(hostname);
client.Login(username, password);
// upload the 'test.zip' file to the current directory at the server
client.PutFile(@"c:\data\test.zip", "test.zip");
client.Disconnect();
You can write a complete communication log to a file using a LogWriter property as follows. Examples output (from FTP component but the SFTP output is similar) can be found here.
client.LogWriter = new Rebex.FileLogWriter(
@"c:\temp\log.txt", Rebex.LogLevel.Debug);
or intercept the communication using events as follows:
Sftp client = new Sftp();
client.CommandSent += new SftpCommandSentEventHandler(client_CommandSent);
client.ResponseRead += new SftpResponseReadEventHandler(client_ResponseRead);
client.Connect("sftp.example.org");
//...
private void client_CommandSent(object sender, SftpCommandSentEventArgs e)
{
Console.WriteLine("Command: {0}", e.Command);
}
private void client_ResponseRead(object sender, SftpResponseReadEventArgs e)
{
Console.WriteLine("Response: {0}", e.Response);
}
For more info see tutorial or download a trial and check samples.
I faced the same issue.
If you issued an api for your release version of the application. Then that api will only work for the release version not for the debug version. So make sure you are using the release version in your phone or emulator .
If you can edit all documents in aggregate :
"TimeStamp": {$toDecimal: {$toDate: "$Your Date"}}
And for the client, you set the query :
Date.parse("Your date".toISOString())
That's what makes you whole work with ISODate.