You need to add a Serializable
attribute to the class which you want to serialize.
[Serializable]
public class OrgPermission
Java has two kind of Variables
a)
Class Level (Static) :
They are one per Class.Say you have Student Class and defined name as static variable.Now no matter how many student object you create all will have same name.
Object Level :
They belong to per Object.If name is non-static ,then all student can have different name.
b)
Class Level :
This variables are initialized on Class load.So even if no student object is created you can still access and use static name variable.
Object Level:
They will get initialized when you create a new object ,say by new();
C)
Your Problem :
Your class is Just loaded in JVM and you have called its main (static) method : Legally allowed.
Now from that you want to call an Object varibale : Where is the object ??
You have to create a Object and then only you can access Object level varibales.
The latest JDBC MSSQL connectivity driver can be found on JDBC 4.0
The class file should be in the classpath. If you are using eclipse you can easily do the same by doing the following -->
Right Click Project Name --> Properties --> Java Build Path --> Libraries --> Add External Jars
Also as already been pointed out by @Cheeso the correct way to access is jdbc:sqlserver://server:port;DatabaseName=dbname
Meanwhile please find a sample class for accessing MSSQL DB (2008 in my case).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,
String db_userid,
String db_password)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from SampleTable";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://xx.xx.xx.xxxx:1433;databaseName=MyDBName", "DB_USER","DB_PASSWORD");
}
}
Hope this helps.
The answer clearly depends on the JVM implementation. Azul claim that their JVM
can scale ... to more than a 1/2 Terabyte of memory
By "can scale" they appear to mean "runs wells", as opposed to "runs at all".
@RequestBody MultiValueMap paramMap
in here Remove the @RequestBody Annotaion
@RequestMapping(value = "/signin",method = RequestMethod.POST)
public String createAccount(@RequestBody LogingData user){
logingService.save(user);
return "login";
}
@RequestMapping(value = "/signin",method = RequestMethod.POST)
public String createAccount( LogingData user){
logingService.save(user);
return "login";
}
like that
In standard SQL syntax, you would use:
WHERE mydate <= DATE '2008-11-20'
That is, the keyword DATE should precede the string. In some DBMS, however, you don't need to be that explicit; the system will convert the DATE column into a string, or the string into a DATE value, automatically. There are nominally some interesting implications if the DATE is converted into a string - if you happen to have dates in the first millennium (0001-01-01 .. 0999-12-31) and the leading zero(es) are omitted by the formatting system.
Here a solution for Swift 5.2
PlayerView.swift:
import AVFoundation
import UIKit
class PlayerView: UIView {
var player: AVPlayer? {
get {
return playerLayer.player
}
set {
playerLayer.player = newValue
}
}
var playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
// Override UIView property
override static var layerClass: AnyClass {
return AVPlayerLayer.self
}
}
VideoPlayer.swift
import AVFoundation
import Foundation
protocol VideoPlayerDelegate {
func downloadedProgress(progress:Double)
func readyToPlay()
func didUpdateProgress(progress:Double)
func didFinishPlayItem()
func didFailPlayToEnd()
}
let videoContext: UnsafeMutableRawPointer? = nil
class VideoPlayer : NSObject {
private var assetPlayer:AVPlayer?
private var playerItem:AVPlayerItem?
private var urlAsset:AVURLAsset?
private var videoOutput:AVPlayerItemVideoOutput?
private var assetDuration:Double = 0
private var playerView:PlayerView?
private var autoRepeatPlay:Bool = true
private var autoPlay:Bool = true
var delegate:VideoPlayerDelegate?
var playerRate:Float = 1 {
didSet {
if let player = assetPlayer {
player.rate = playerRate > 0 ? playerRate : 0.0
}
}
}
var volume:Float = 1.0 {
didSet {
if let player = assetPlayer {
player.volume = volume > 0 ? volume : 0.0
}
}
}
// MARK: - Init
convenience init(urlAsset:NSURL, view:PlayerView, startAutoPlay:Bool = true, repeatAfterEnd:Bool = true) {
self.init()
playerView = view
autoPlay = startAutoPlay
autoRepeatPlay = repeatAfterEnd
if let playView = playerView, let playerLayer = playView.layer as? AVPlayerLayer {
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
}
initialSetupWithURL(url: urlAsset)
prepareToPlay()
}
override init() {
super.init()
}
// MARK: - Public
func isPlaying() -> Bool {
if let player = assetPlayer {
return player.rate > 0
} else {
return false
}
}
func seekToPosition(seconds:Float64) {
if let player = assetPlayer {
pause()
if let timeScale = player.currentItem?.asset.duration.timescale {
player.seek(to: CMTimeMakeWithSeconds(seconds, preferredTimescale: timeScale), completionHandler: { (complete) in
self.play()
})
}
}
}
func pause() {
if let player = assetPlayer {
player.pause()
}
}
func play() {
if let player = assetPlayer {
if (player.currentItem?.status == .readyToPlay) {
player.play()
player.rate = playerRate
}
}
}
func cleanUp() {
if let item = playerItem {
item.removeObserver(self, forKeyPath: "status")
item.removeObserver(self, forKeyPath: "loadedTimeRanges")
}
NotificationCenter.default.removeObserver(self)
assetPlayer = nil
playerItem = nil
urlAsset = nil
}
// MARK: - Private
private func prepareToPlay() {
let keys = ["tracks"]
if let asset = urlAsset {
asset.loadValuesAsynchronously(forKeys: keys, completionHandler: {
DispatchQueue.main.async {
self.startLoading()
}
})
}
}
private func startLoading(){
var error:NSError?
guard let asset = urlAsset else {return}
let status:AVKeyValueStatus = asset.statusOfValue(forKey: "tracks", error: &error)
if status == AVKeyValueStatus.loaded {
assetDuration = CMTimeGetSeconds(asset.duration)
let videoOutputOptions = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)]
videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: videoOutputOptions)
playerItem = AVPlayerItem(asset: asset)
if let item = playerItem {
item.addObserver(self, forKeyPath: "status", options: .initial, context: videoContext)
item.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.new, .old], context: videoContext)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didFailedToPlayToEnd), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil)
if let output = videoOutput {
item.add(output)
item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.varispeed
assetPlayer = AVPlayer(playerItem: item)
if let player = assetPlayer {
player.rate = playerRate
}
addPeriodicalObserver()
if let playView = playerView, let layer = playView.layer as? AVPlayerLayer {
layer.player = assetPlayer
print("player created")
}
}
}
}
}
private func addPeriodicalObserver() {
let timeInterval = CMTimeMake(value: 1, timescale: 1)
if let player = assetPlayer {
player.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main, using: { (time) in
self.playerDidChangeTime(time: time)
})
}
}
private func playerDidChangeTime(time:CMTime) {
if let player = assetPlayer {
let timeNow = CMTimeGetSeconds(player.currentTime())
let progress = timeNow / assetDuration
delegate?.didUpdateProgress(progress: progress)
}
}
@objc private func playerItemDidReachEnd() {
delegate?.didFinishPlayItem()
if let player = assetPlayer {
player.seek(to: CMTime.zero)
if autoRepeatPlay == true {
play()
}
}
}
@objc private func didFailedToPlayToEnd() {
delegate?.didFailPlayToEnd()
}
private func playerDidChangeStatus(status:AVPlayer.Status) {
if status == .failed {
print("Failed to load video")
} else if status == .readyToPlay, let player = assetPlayer {
volume = player.volume
delegate?.readyToPlay()
if autoPlay == true && player.rate == 0.0 {
play()
}
}
}
private func moviewPlayerLoadedTimeRangeDidUpdated(ranges:Array<NSValue>) {
var maximum:TimeInterval = 0
for value in ranges {
let range:CMTimeRange = value.timeRangeValue
let currentLoadedTimeRange = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration)
if currentLoadedTimeRange > maximum {
maximum = currentLoadedTimeRange
}
}
let progress:Double = assetDuration == 0 ? 0.0 : Double(maximum) / assetDuration
delegate?.downloadedProgress(progress: progress)
}
deinit {
cleanUp()
}
private func initialSetupWithURL(url:NSURL) {
let options = [AVURLAssetPreferPreciseDurationAndTimingKey : true]
urlAsset = AVURLAsset(url: url as URL, options: options)
}
// MARK: - Observations
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == videoContext {
if let key = keyPath {
if key == "status", let player = assetPlayer {
playerDidChangeStatus(status: player.status)
} else if key == "loadedTimeRanges", let item = playerItem {
moviewPlayerLoadedTimeRangeDidUpdated(ranges: item.loadedTimeRanges)
}
}
}
}
}
Usage:
private var playerView: PlayerView = PlayerView()
private var videoPlayer:VideoPlayer?
and inside viewDidLoad()
:
view.addSubview(playerView)
preparePlayer()
// set Constraints (if you do it purely in code)
playerView.translatesAutoresizingMaskIntoConstraints = false
playerView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10.0).isActive = true
playerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10.0).isActive = true
playerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10.0).isActive = true
playerView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 10.0).isActive = true
private func preparePlayer() {
if let filePath = Bundle.main.path(forResource: "my video", ofType: "mp4") {
let fileURL = NSURL(fileURLWithPath: filePath)
videoPlayer = VideoPlayer(urlAsset: fileURL, view: playerView)
if let player = videoPlayer {
player.playerRate = 0.67
}
}
}
Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.
You could also use SwingWorker, which has built-in property change support. See addPropertyChangeListener() or the get() method for a state change listener example.
Make it lowercase first:
.m_title {text-transform: lowercase}
Then make it the first letter uppercase:
.m_title:first-letter {text-transform: uppercase}
"text-transform: capitalize" works for a word; but if you want to use for sentences this solution is perfect.
server {
index index.html index.htm;
server_name test.example.com;
location / {
root /web/test.example.com/www;
}
location /static {
root /web/test.example.com;
}
}
In my case, I just put the aar file in libs, and add
dependencies {
...
api fileTree(dir: 'libs', include: ['*.aar'])
...
}
in build.gradle and it works. I think it is similar with default generated dependency:
implementation fileTree(dir: 'libs', include: ['*.jar'])
I think you should add style="background:white;" to make looks like it is writable
<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly" style="background:white;"/>
dir /s /b /a:d>output.txt
will port it to a text file
Right, so basically it's a way to keep DLLs globally accessible without worrying about conflicts. No more DLL Hell. Each architecture and version gets it's own place to live.
It also gets it own way to browse it in Explorer, so if you go to
C:\Windows\assembly
In windows explorer it lists all the DLLs.
But if you fire up cmd
, you can see how it's really structured:
C:\Users\tritter>cd C:\Windows\assembly C:\Windows\assembly>dir Directory of C:\Windows\assembly 07/20/2009 02:18 PM <DIR> GAC 06/17/2009 04:22 PM <DIR> GAC_32 06/17/2009 04:22 PM <DIR> GAC_64 06/17/2009 04:22 PM <DIR> GAC_MSIL ...snip... 0 File(s) 0 bytes 9 Dir(s) 90,538,311,680 bytes free C:\Windows\assembly>cd GAC_64 C:\Windows\assembly\GAC_64>dir Directory of C:\Windows\assembly\GAC_64 06/17/2009 04:22 PM <DIR> . 06/17/2009 04:22 PM <DIR> .. 01/19/2008 09:54 AM <DIR> blbproxy ...snip... 01/19/2008 09:54 AM <DIR> srmlib 01/19/2008 06:11 AM <DIR> System.Data 01/19/2008 06:11 AM <DIR> System.Data.OracleClient ...snip... 0 File(s) 0 bytes 34 Dir(s) 90,538,311,680 bytes free C:\Windows\assembly\GAC_64>cd System.Data C:\Windows\assembly\GAC_64\System.Data>dir Directory of C:\Windows\assembly\GAC_64\System.Data 01/19/2008 06:11 AM <DIR> . 01/19/2008 06:11 AM <DIR> .. 04/11/2009 12:20 PM <DIR> 2.0.0.0__b77a5c561934e089 0 File(s) 0 bytes 3 Dir(s) 90,538,311,680 bytes free C:\Windows\assembly\GAC_64\System.Data>cd 2.0.0.0__b77a5c561934e089 C:\Windows\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089>dir Directory of C:\Windows\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089 04/11/2009 12:20 PM <DIR> . 04/11/2009 12:20 PM <DIR> .. 04/11/2009 12:12 PM 3,008,512 System.Data.dll 1 File(s) 3,008,512 bytes 2 Dir(s) 90,538,311,680 bytes free C:\Windows\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089>
Here you can see version 2.0.0.0__b77a5c561934e089 of System.Data.
A DLL is identified by 5 parts:
Although the first 3 are generally the big ones.
The Random
class of Java located in the java.util
package will serve your purpose better. It has some nextInt()
methods that return an integer. The one taking an int argument will generate a number between 0 and that int, the latter not inclusive.
Components control views (html). They also communicate with other components and services to bring functionality to your app.
Modules consist of one or more components. They do not control any html. Your modules declare which components can be used by components belonging to other modules, which classes will be injected by the dependency injector and which component gets bootstrapped. Modules allow you to manage your components to bring modularity to your app.
This happened to me too! But I accidentally found out that execute the 'mysqld' command can solve your problem.
My SQL version is 5.7. Hope this works for you.
If you are asking about actual command line makefiles then you can export a makefile, or you can call MSBuild on a solution file from the command line. What exactly do you want to do with the makefile?
You can do a search on SO for MSBuild for more details.
Beyond how UTF is a superset of ASCII, another good difference to know between ASCII and UTF is in terms of disk file encoding and data representation and storage in random memory. Programs know that given data should be understood as an ASCII or UTF string either by detecting special byte order mark codes at the start of the data, or by assuming from programmer intent that the data is text and then checking it for patterns that indicate it is in one text encoding or another.
Using the conventional prefix notation of 0x
for hexadecimal data, basic good reference is that ASCII text starts with byte values 0x00
to 0x7F
representing one of the possible ASCII character values. UTF text is normally indicated by starting with the bytes 0xEF 0xBB 0xBF
for UTF8. For UTF16, start bytes 0xFE 0xFF
, or 0xFF 0xFE
are used, with the endian-ness order of the text bytes indicated by the order of the start bytes. The simple presence of byte values that are not in the ASCII range of possible byte values also indicates that data is probably UTF.
There are other byte order marks that use different codes to indicate data should be interpreted as text encoded in a certain encoding standard.
In create-react-app
relative paths for images don't seem to work. Instead, you can import an image:
import logo from './logo.png' // relative path to image
class Nav extends Component {
render() {
return (
<img src={logo} alt={"logo"}/>
)
}
}
There is a difference.
When the ^
character appears outside of []
matches the beginning of the line (or string). When the ^
character appears inside the []
, it matches any character not appearing inside the []
.
I think the lightsail as the name suggest is light weight and meant for initial development. For production sites and apps with high volume it simply becomes unavailable and hangs....It is just a sandbox to play with things. Further lack of support reduces its reliability. There should be an option to migrate to EC2, when u fully develop your apps or sites..So that with same minimum configuration you can migrate to scalable EC2..
It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.
What you need is properly a service:
.factory('DataLayer', ['$http',
function($http) {
var factory = {};
var locations;
factory.getLocations = function(success) {
if(locations){
success(locations);
return;
}
$http.get('locations/locations.json').success(function(data) {
locations = data;
success(locations);
});
};
return factory;
}
]);
The locations
would be cached in the service which worked as singleton model. This is the right way to fetch data.
Use this service DataLayer
in your controller and directive is ok as following:
appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
DataLayer.getLocations(function(data){
$scope.locations = data;
});
});
.directive('map', function(DataLayer) {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
link: function(scope, element, attrs) {
DataLayer.getLocations(function(data) {
angular.forEach(data, function(location, key){
//do something
});
});
}
};
});
See the documentation for sys.path:
http://docs.python.org/library/sys.html#sys.path
To quote:
If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first.
So, there's no need to monkey with sys.path if you're starting the python interpreter from the directory containing your module.
Also, to import your package, just do:
import mypackage
Since the directory containing the package is already in sys.path, it should work fine.
The reason for this warning is that const in c doesn't mean constant. It means "read only". So the value is stored at a memory address and could potentially be changed by machine code.
There is both window.onbeforeunload
and window.onunload
, which are used differently depending on the browser. You can assign them either by setting the window properties to functions, or using the .addEventListener
:
window.onbeforeunload = function(){
// Do something
}
// OR
window.addEventListener("beforeunload", function(e){
// Do something
}, false);
Usually, onbeforeunload
is used if you need to stop the user from leaving the page (ex. the user is working on some unsaved data, so he/she should save before leaving). onunload
isn't supported by Opera, as far as I know, but you could always set both.
If you're trying this with GitHub, you can do this with your SSH entered:
git clone https://[email protected]/username/repository
Yes, you can write virtual "functions" in Java.
Have you considered doing this from the layout.xml
? You could set for your ImageView
the ScaleType to android:scaleType="centerCrop"
and set the dimensions of the image in the ImageView
inside the layout.xml
.
With a wider view of what you're actually trying to do and the context in which you're doing it, I'm sure we could give you a better answer than the literal answer to your question.
But here's a literal answer:
If you're assigning these functions to some property somewhere, you can wrap the original function and put your replacement on the property instead:
// Original code in main.js
var theProperty = init;
function init(){
doSomething();
}
// Extending it by replacing and wrapping, in extended.js
theProperty = (function(old) {
function extendsInit() {
old();
doSomething();
}
return extendsInit;
})(theProperty);
If your functions aren't already on an object, you'd probably want to put them there to facilitate the above. For instance:
// In main.js
var MyLibrary = {
init: function init() {
}
};
// In extended.js
(function() {
var oldInit = MyLibrary.init;
MyLibrary.init = extendedInit;
function extendedInit() {
oldInit.call(MyLibrary); // Use #call in case `init` uses `this`
doSomething();
}
})();
But there are better ways to do that. Like for instance, providing a means of registering init
functions.
// In main.js
var MyLibrary = (function() {
var initFunctions = [];
return {
init: function init() {
var fns = initFunctions;
initFunctions = undefined;
for (var index = 0; index < fns.length; ++index) {
try { fns[index](); } catch (e) { }
}
},
addInitFunction: function addInitFunction(fn) {
if (initFunctions) {
// Init hasn't run yet, remember it
initFunctions.push(fn);
} else {
// `init` has already run, call it almost immediately
// but *asynchronously* (so the caller never sees the
// call synchronously)
setTimeout(fn, 0);
}
}
};
})();
Here in 2020 (or really any time after ~2016), that can be written a bit more compactly:
// In main.js
const MyLibrary = (() => {
let initFunctions = [];
return {
init() {
const fns = initFunctions;
initFunctions = undefined;
for (const fn of fns) {
try { fn(); } catch (e) { }
}
},
addInitFunction(fn) {
if (initFunctions) {
// Init hasn't run yet, remember it
initFunctions.push(fn);
} else {
// `init` has already run, call it almost immediately
// but *asynchronously* (so the caller never sees the
// call synchronously)
setTimeout(fn, 0);
// Or: `Promise.resolve().then(() => fn());`
// (Not `.then(fn)` just to avoid passing it an argument)
}
}
};
})();
Classes are not meant to be just collections of methods. A class is supposed to represent an abstract concept, with both state (fields) and behaviour (methods) which changes the state. Using inheritance just to get some desired behaviour sounds like bad OO design, and exactly the reason why many languages disallow multiple inheritance: in order to prevent "spaghetti inheritance", i.e. extending 3 classes because each has a method you need, and ending up with a class that inherits 100 method and 20 fields, yet only ever uses 5 of them.
app.run(use_reloader=True)
we can use this, use_reloader so every time we reload the page our code changes will be updated.
To replace a string in a single file (currently opened): CTRL + H
For replacing at workspace level use: CTRL + SHIFT + H
One way could be to detect if the iterator has next
. If there is no next attached to the iterator it means you are in the last loop.
foreach ($some_array as $element) {
if(!next($some_array)) {
// This is the last $element
}
}
Also, you can do it with css selectors:
form#myform input[type='submit']
space beween elements in css elector means searching input[type='submit'] that elements at any depth of parent form#myform element
Each TCP connection requires an initial handshake before data is transmitted. Also, the TCP header contains a lot of overhead intended for different signals and message delivery detection. For a message exchange, UDP will probably suffice if a small chance of failure is acceptable. If receipt must be verified, TCP is your best option.
The first thing comes to my mind is: this is a good place to use Binary search (inspired by this great tutorials.)
To find the square root of vaule
,we are searching the number
in (1..value)
where the predictor
is true for the first time. The predictor we are choosing is number * number - value > 0.00001
.
double square_root_of(double value)
{
assert(value >= 1);
double lo = 1.0;
double hi = value;
while( hi - lo > 0.00001)
{
double mid = lo + (hi - lo) / 2 ;
std::cout << lo << "," << hi << "," << mid << std::endl;
if( mid * mid - value > 0.00001) //this is the predictors we are using
{
hi = mid;
} else {
lo = mid;
}
}
return lo;
}
Hi to pass values from one js file to another js file we can use Local storage concept
<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
Two.js file
function myFunction() {
var test =localStorage.name;
alert(test);
}
Three.js File
localStorage.name = 1;
vector <int> numbers {10,20,30,40};
vector <int> *ptr {nullptr};
ptr = &numbers;
for(auto num: *ptr){
cout << num << endl;
}
cout << (*ptr).at(2) << endl; // 20
cout << "-------" << endl;
cout << ptr -> at(2) << endl; // 20
The important part is this:
Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml];
due to:
nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl
According to this log, Spring could not find your MemberPointSummaryDAOImpl
class.
You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.
Usually, you can login as the postgres user:
Open a Terminal and do sudo su postgres
.
Now, after entering your admin password, you are able to launch psql
and do
CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';
This creates a new admin user. If you want to list the existing users, you could also do
\du
to list all users and then
ALTER USER yourusername WITH PASSWORD 'yournewpass';
Using the standard CustomCreationConverter
, I was struggling to work how to generate the correct type (Person
or Employee
), because in order to determine this you need to analyse the JSON and there is no built in way to do this using the Create
method.
I found a discussion thread pertaining to type conversion and it turned out to provide the answer. Here is a link: Type converting.
What's required is to subclass JsonConverter
, overriding the ReadJson
method and creating a new abstract Create
method which accepts a JObject
.
The JObject class provides a means to load a JSON object and provides access to the data within this object.
The overridden ReadJson
method creates a JObject
and invokes the Create
method (implemented by our derived converter class), passing in the JObject
instance.
This JObject
instance can then be analysed to determine the correct type by checking existence of certain fields.
Example
string json = "[{
\"Department\": \"Department1\",
\"JobTitle\": \"JobTitle1\",
\"FirstName\": \"FirstName1\",
\"LastName\": \"LastName1\"
},{
\"Department\": \"Department2\",
\"JobTitle\": \"JobTitle2\",
\"FirstName\": \"FirstName2\",
\"LastName\": \"LastName2\"
},
{\"Skill\": \"Painter\",
\"FirstName\": \"FirstName3\",
\"LastName\": \"LastName3\"
}]";
List<Person> persons =
JsonConvert.DeserializeObject<List<Person>>(json, new PersonConverter());
...
public class PersonConverter : JsonCreationConverter<Person>
{
protected override Person Create(Type objectType, JObject jObject)
{
if (FieldExists("Skill", jObject))
{
return new Artist();
}
else if (FieldExists("Department", jObject))
{
return new Employee();
}
else
{
return new Person();
}
}
private bool FieldExists(string fieldName, JObject jObject)
{
return jObject[fieldName] != null;
}
}
public abstract class JsonCreationConverter<T> : JsonConverter
{
/// <summary>
/// Create an instance of objectType, based properties in the JSON object
/// </summary>
/// <param name="objectType">type of object expected</param>
/// <param name="jObject">
/// contents of JSON object that will be deserialized
/// </param>
/// <returns></returns>
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override bool CanWrite
{
get { return false; }
}
public override object ReadJson(JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
// Populate the object properties
serializer.Populate(jObject.CreateReader(), target);
return target;
}
}
Adding to the first answer, I think .service() is for people who have written their code in more object oriented style(C#/Java) (using this keyword and instantiating object via prototype/Constructor function).
Factory is for developers who write code which is more natural to javascript/functional style of coding.
Take a look at the source code of .service and .factory method inside angular.js - internally they all call provider method:
function provider(name, provider_) {
if (isFunction(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw Error('Provider ' + name + ' must define $get factory method.');
}
return providerCache[name + providerSuffix] = provider_;
}
function factory(name, factoryFn) { \
return provider(name, { $get: factoryFn });
}
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
Create extension as below & call hideKeyboardWhenTappedAround()
in your Base view controller.
//
// UIViewController+Extension.swift
// Project Name
//
// Created by ABC on 2/3/18.
// Copyright © 2018 ABC. All rights reserved.
//
import UIKit
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tapGesture = UITapGestureRecognizer(target: self,
action: #selector(hideKeyboard))
view.addGestureRecognizer(tapGesture)
}
@objc func hideKeyboard() {
view.endEditing(true)
}
}
Most important thing to call in your Base View Controller so that no need to call all time in all view controllers.
Historically, from UNIX v7, the process system has detected orphanity of processes by checking a process' parent id. As I say, historically, the init(8)
system process is a special process by only one reason: It cannot die. It cannot die because the kernel algorithm to deal with assigning a new parent process id, depends on this fact. when a process executes its exit(2)
call (by means of a process system call or by external task as sending it a signal or the like) the kernel reassigns all children of this process the id of the init process as their parent process id. This leads to the most easy test, and most portable way of knowing if a process has got orphan. Just check the result of the getppid(2)
system call and if it is the process id of the init(2)
process then the process got orphan before the system call.
Two issues emerge from this approach that can lead to issues:
init
process to any user process, so How can we assure that the init process will always be parent of all orphan processes? Well, in the exit
system call code there's a explicit check to see if the process executing the call is the init process (the process with pid equal to 1) and if that's the case, the kernel panics (It should not be able anymore to maintain the process hierarchy) so it is not permitted for the init process to do an exit(2)
call.1
, but that's not warranted by the POSIX approach, that states (as exposed in other response) that only a system's process id is reserved for that purpose. Almost no posix implementation does this, and you can assume in original unix derived systems that having 1
as response of getppid(2)
system call is enough to assume the process is orphan. Another way to check is to make a getppid(2)
just after the fork and compare that value with the result of a new call. This simply doesn't work in all cases, as both call are not atomic together, and the parent process can die after the fork(2)
and before the first getppid(2)
system call. The processparent id only changes once, when its parent does an
exit(2)call, so this should be enough to check if the
getppid(2)result changed between calls to see that parent process has exit. This test is not valid for the actual children of the init process, because they are always children of
init(8)`, but you can assume safely these processes as having no parent either (except when you substitute in a system the init process)Two tricks. Basically inverting the HTML order of your desired elements in HTML and using
~
Next siblings operator:
float-right
+ inverse the order of HTML elementsdiv{ /* Do with the parent whatever you know just to make the_x000D_
inner float-right elements appear where desired */_x000D_
display:inline-block;_x000D_
}_x000D_
span{_x000D_
float:right; /* float-right the elements! */_x000D_
}_x000D_
span:hover ~ span{ /* On hover target it's "previous";) elements */_x000D_
background:red;_x000D_
}
_x000D_
<div>_x000D_
<!-- Reverse the order of inner elements -->_x000D_
<span>5</span>_x000D_
<span>4</span>_x000D_
<span>3</span>_x000D_
<span>2</span>_x000D_
<span>1</span>_x000D_
</div>
_x000D_
direction: rtl;
+ inverse the order of inner elements.inverse{_x000D_
direction: rtl;_x000D_
display: inline-block; /* inline-block to keep parent at the left of window */_x000D_
}_x000D_
span:hover ~ span{ /* On hover target it's "previous";) elements */_x000D_
background:gold;_x000D_
}
_x000D_
Hover one span and see the previous elements being targeted!<br>_x000D_
_x000D_
<div class="inverse">_x000D_
<!-- Reverse the order of inner elements -->_x000D_
<span>5</span>_x000D_
<span>4</span>_x000D_
<span>3</span>_x000D_
<span>2</span>_x000D_
<span>1</span>_x000D_
</div>
_x000D_
i wanna put my 5 cents to accepted answer: i've been researching topic for 2 days and finally found a solution that i will be using always from now on
go up to item 4 in accepted answer and forget about adding attributes of frames and contentsizes and so on
to make everything automatic just use solution from this link
everything is clear, easy, elegant and works like a charm on ios 7. i'm pretty glad with all that lol
You can add this to onCreate
and it will hide the keyboard every time the Activity
starts.
You can also programmatically change the focus to another item.
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
There are 3 access specifiers
for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:
Public - The members declared as Public are accessible from outside the Class through an object of the class.
Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
public:
int a;
protected:
int b;
private:
int c;
};
int main()
{
MyClass obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, gives compiler error
obj.c = 30; //Not Allowed, gives compiler error
}
Inheritance in C++ can be one of the following types:
Private
Inheritance Public
Inheritance Protected
inheritance Here are the member access rules with respect to each of these:
First and most important rule
Private
members of a class are never accessible from anywhere except the members of the same class.
All
Public
members of the Base Class becomePublic
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.
Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:public Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomePrivate
Members of the Derived class &
AllProtected
members of the Base Class becomePrivate
Members of the Derived Class.
An code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:private Base //Not mentioning private is OK because for classes it defaults to private
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Not Allowed, Compiler Error, a is private member of Derived now
b = 20; //Not Allowed, Compiler Error, b is private member of Derived now
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomeProtected
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
A Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:protected Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
b = 20; //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
Remember the same access rules apply to the classes and members down the inheritance hierarchy.
- Access Specification is per-Class not per-Object
Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.
- A Derived class can only access members of its own Base class
Consider the following code example:
class Myclass
{
protected:
int x;
};
class derived : public Myclass
{
public:
void f( Myclass& obj )
{
obj.x = 5;
}
};
int main()
{
return 0;
}
It gives an compilation error:
prog.cpp:4: error: ‘int Myclass::x’ is protected
Because the derived class can only access members of its own Base Class. Note that the object obj
being passed here is no way related to the derived
class function in which it is being accessed, it is an altogether different object and hence derived
member function cannot access its members.
friend
? How does friend
affect access specification rules?You can declare a function or class as friend
of another class. When you do so the access specification rules do not apply to the friend
ed class/function. The class or function can access all the members of that particular class.
So do
friend
s break Encapsulation?
No they don't, On the contrary they enhance Encapsulation!
friend
ship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private
or protected
members but You do not want everyone to have access by using the public
access specifier then you should use friend
ship.
Use of Hive, Hbase and Pig w.r.t. my real time experience in different projects.
Hive is used mostly for:
Analytics purpose where you need to do analysis on history data
Generating business reports based on certain columns
Efficiently managing the data together with metadata information
Joining tables on certain columns which are frequently used by using bucketing concept
Efficient Storing and querying using partitioning concept
Not useful for transaction/row level operations like update, delete, etc.
Pig is mostly used for:
Frequent data analysis on huge data
Generating aggregated values/counts on huge data
Generating enterprise level key performance indicators very frequently
Hbase is mostly used:
For real time processing of data
For efficiently managing Complex and nested schema
For real time querying and faster result
For easy Scalability with columns
Useful for transaction/row level operations like update, delete, etc.
While the IS operator is normally the best way, there is an alternative that you can use in some cirumstances. You can use the as operator and test for null.
MyClass mc = foo as MyClass;
if ( mc == null ) { }
else {}
If the plugin you want to install is not listed in the Plugins Admin, you may still install it manually. The plugin (in the DLL form) should be placed in the plugins subfolder of the Notepad++ Install Folder, under the subfolder with the same name of plugin binary name without file extension.
For example, if the plugin you want to install named myAwesomePlugin.dll, you should install it with the following path:
%PROGRAMFILES(x86)%\Notepad++\plugins\myAwesomePlugin\myAwesomePlugin.dll
or
%PROGRAMFILES%\Notepad++\plugins\myAwesomePlugin\myAwesomePlugin.dll
Once you installed the plugin, you can use (and you may configure) it via the menu “Plugins”.
Restart the Notepad++ after putting the plugin
If you use Guava in your project you can use Iterables::toArray
.
Foo[] foos = Iterables.toArray(x, Foo.class);
Arrays are pretty flexible in JS, you can do:
var myArray = new Array();
myArray.push("string 1");
myArray.push("string 2");
How about the following, where y is the name of your matrix and you are looking for the maximum in the entire matrix:
row(y)[y==max(y)]
if you want to extract the row:
y[row(y)[y==max(y)],] # this returns unsorted rows.
To return sorted rows use:
y[sort(row(y)[y==max(y)]),]
The advantage of this approach is that you can change the conditional inside to anything you need. Also, using col(y)
and location of the hanging comma you can also extract columns.
y[,col(y)[y==max(y)]]
To find just the row for the max in a particular column, say column 2 you could use:
seq(along=y[,2])[y[,2]==max(y[,2])]
again the conditional is flexible to look for different requirements.
See Phil Spector's excellent "An introduction to S and S-Plus" Chapter 5 for additional ideas.
What you see for OPTIONS request is fine. Authorisation headers are not exposed in it.
But in order for basic auth to work you need to add: withCredentials = true;
to your var config
.
From the AngularJS $http documentation:
withCredentials -
{boolean}
- whether to to set thewithCredentials
flag on the XHR object. See requests with credentials for more information.
When I had this error, it went away after I my computer crashed and restarted. Try closing and reopening your IDE, if that doesn't work, try restarting your computer. I had just installed the libraries at that point without restarting pycharm when I got this error.
Never closed PyCharm first to test because my blasted computer keeps crashing randomly... working on that one, but it at least solved this problem.. little victories.. :).
Push down the whole button. I suggest this it is looking nice in button.
#button:active {
position: relative;
top: 1px;
}
if you only want to push text increase top-padding and decrease bottom padding. You can also use line-height.
The simplest thing you can do is cherry picking a range. It does the same as the rebase --onto
but is easier for the eyes :)
git cherry-pick quickfix1..quickfix2
This works for me: close the project then re-open it, this will force eclipse to see it as a fresh project and detects a correct build path.
You are accessing your list twice to replace one element. I think simple for
loop should be enough:
var key = valueFieldValue.ToString();
for (int i = 0; i < listofelements.Count; i++)
{
if (listofelements[i] == key)
{
listofelements[i] = value.ToString();
break;
}
}
I had the same problem. which as resolved using these steps:
1.) Click File
2.) Select "save as"
3.) Click on drop down (Save as type)
4.) Select Excel 97-2003 Workbook
5.) Click on Save button
Once you have started the SSH agent with:
eval $(ssh-agent)
Do either:
To add your private key to it:
ssh-add
This will ask you your passphrase just once, and then you should be allowed to push, provided that you uploaded the public key to Github.
To add and save your key permanently on macOS:
ssh-add -K
This will persist it after you close and re-open it by storing it in user's keychain.
To add and save your key permanently on Ubuntu (or equivalent):
ssh-add ~/.ssh/id_rsa
"<pre>"
is an HTML tag. If you insert this line of code in your program
echo "<pre>";
then you will enable the viewing of multiple spaces and line endings. Without this, all \n
, \r
and other end line characters wouldn't have any effect in the browser and wherever you had more than 1 space in the code, the output would be shortened to only 1 space. That's the default HTML. In that case only with <br>
you would be able to break the line and go to the next one.
For example,
the code below would be displayed on multiple lines, due to \n
line ending specifier.
<?php
echo "<pre>";
printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
printf("Goodbye");
?>
However the following code, would be displayed in one line only (line endings are disregarded).
<?php
printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
printf("Goodbye");
?>
You used %H
(24 hour format) instead of %I
(12 hour format).
This error also comes if 2 versions of hamcrest-library or hamcrest-core is present in the classpath.
In the pom file, you can exclude the extra version and it works.
another simple way of navigating to another activity is
Intent(this, CodeActivity::class.java).apply {
startActivity(this)
}
Long
is the Object
form of long
, and Integer
is the object form of int
.
The long
uses 64 bits. The int
uses 32 bits, and so can only hold numbers up to ±2 billion (-231 to +231-1).
You should use long
and int
, except where you need to make use of methods inherited from Object
, such as hashcode
. Java.util.collections
methods usually use the boxed (Object
-wrapped) versions, because they need to work for any Object
, and a primitive type, like int
or long
, is not an Object
.
Another difference is that long
and int
are pass-by-value, whereas Long
and Integer
are pass-by-reference value, like all non-primitive Java types. So if it were possible to modify a Long
or Integer
(it's not, they're immutable without using JNI code), there would be another reason to use one over the other.
A final difference is that a Long
or Integer
could be null
.
Basically the scope of workspace(s) is divided in two points.
First point (and primary) is the eclipse it self and is related with the settings and metadata configurations (plugin ctr). Each time you create a project, eclipse collects all the configurations and stores them on that workspace and if somehow in the same workspace a conflicting project is present you might loose some functionality or even stability of eclipse it self.
And second (secondary) the point of development strategy one can adopt. Once the primary scope is met (and mastered) and there's need for further adjustments regarding project relations (as libraries, perspectives ctr) then initiate separate workspace(s) could be appropriate based on development habits or possible language/frameworks "behaviors". DLTK for examples is a beast that should be contained in a separate cage. Lots of complains at forums for it stopped working (properly or not at all) and suggested solution was to clean the settings of the equivalent plugin from the current workspace.
Personally, I found myself lean more to language distinction when it comes to separate workspaces which is relevant to known issues that comes with the current state of the plugins are used. Preferably I keep them in the minimum numbers as this is leads to less frustration when the projects are become... plenty and version control is not the only version you keep your projects. Finally, loading speed and performance is an issue that might come up if lots of (unnecessary) plugins are loaded due to presents of irrelevant projects. Bottom line; there is no one solution to every one, no master blue print that solves the issue. It's something that grows with experience, Less is more though!
$result = mysql_query($query) or die("Data not found.");
$rows=array();
while($r=mysql_fetch_assoc($result))
{
$rows[]=$r;
}
header("Content-type:application/json");
echo json_encode($rows);
An alternative method to BenAlabaster answer
First of all, you can rewrite the query like this:
var matches = from Users in people
where Users.User_Rights == "Admin" ||
Users.User_Rights == "Users" ||
Users.User_Rights == "Limited"
select Users;
Certainly this is more 'wordy' and a pain to write but it works all the same.
So if we had some utility method that made it easy to create these kind of LINQ expressions we'd be in business.
with a utility method in place you can write something like this:
var matches = ctx.People.Where(
BuildOrExpression<People, string>(
p => p.User_Rights, names
)
);
This builds an expression that has the same effect as:
var matches = from p in ctx.People
where names.Contains(p.User_Rights)
select p;
But which more importantly actually works against .NET 3.5 SP1.
Here is the plumbing function that makes this possible:
public static Expression<Func<TElement, bool>> BuildOrExpression<TElement, TValue>(
Expression<Func<TElement, TValue>> valueSelector,
IEnumerable<TValue> values
)
{
if (null == valueSelector)
throw new ArgumentNullException("valueSelector");
if (null == values)
throw new ArgumentNullException("values");
ParameterExpression p = valueSelector.Parameters.Single();
if (!values.Any())
return e => false;
var equals = values.Select(value =>
(Expression)Expression.Equal(
valueSelector.Body,
Expression.Constant(
value,
typeof(TValue)
)
)
);
var body = equals.Aggregate<Expression>(
(accumulate, equal) => Expression.Or(accumulate, equal)
);
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
I'm not going to try to explain this method, other than to say it essentially builds a predicate expression for all the values using the valueSelector (i.e. p => p.User_Rights) and ORs those predicates together to create an expression for the complete predicate
You can use configuration extension method : getConnectionString ("DefaultConnection")
you can find the locked tables in oralce by querying with following query
select
c.owner,
c.object_name,
c.object_type,
b.sid,
b.serial#,
b.status,
b.osuser,
b.machine
from
v$locked_object a ,
v$session b,
dba_objects c
where
b.sid = a.session_id
and
a.object_id = c.object_id;
addAccordian(type, data) { console.log(type, data);
let form = this.form;
if (!form.controls[type]) {
let ownerAccordian = new FormArray([]);
const group = new FormGroup({});
ownerAccordian.push(
this.applicationService.createControlWithGroup(data, group)
);
form.controls[type] = ownerAccordian;
} else {
const group = new FormGroup({});
(<FormArray>form.get(type)).push(
this.applicationService.createControlWithGroup(data, group)
);
}
console.log(this.form);
}
For someone using Android Studio 4.0 or above on MacOS 10.15.1 or above. Using command line blow:
# Deletes the Android Studio application
# Note that this may be different depending on what you named the application as, or whether you downloaded the preview version
rm -Rf /Applications/Android\ Studio.app
# Delete All Android Studio related preferences
# The asterisk here should target all folders/files beginning with the string before it
rm -Rf ~/Library/Preferences/Google/AndroidStudio*
# Deletes the Android Studio's plist file
rm -Rf ~/Library/Preferences/com.google.android.*
# Deletes the Android Emulator's plist file
rm -Rf ~/Library/Preferences/com.android.*
# Deletes mainly plugins (or at least according to what mine (Edric) contains)
rm -Rf ~/Library/Application\ Support/Google/AndroidStudio*
# Deletes all logs that Android Studio outputs
rm -Rf ~/Library/Logs/Google/AndroidStudio*
# Deletes Android Studio's caches
rm -Rf ~/Library/Caches/Google/AndroidStudio*
# Deletes older versions of Android Studio
rm -Rf ~/.AndroidStudio*
Difference
Library/Preferences/Google/AndroidStudio*
Library/Logs/Google/AndroidStudio*
Library/Caches/Google/AndroidStudio*
I would consider using roboguice's logging facility instead of the built-in android.util.Log
Their facility automatically disables debug and verbose logs for release builds. Plus, you get some nifty features for free (e.g. customizable logging behavior, additional data for every log and more)
Using proguard could be quite a hassle and I wouldn't go through the trouble of configuring and making it work with your application unless you have a good reason for that (disabling logs isn't a good one)
In .NET 4 you can now write:
flags.HasFlag(FlagsEnum.Bit4)
I faced the same error with my Visual Studio Team Services account (formerly Visual Studio Online, Team Foundation Service).
I simply entered the credentials using the VS 2013 "Connect to Team Foundation Server" Window, and then connected it to the Visual Studio Team Services Team Project. It worked this way.
I achieved it using some extension methods
private const string endFieldPattern = "^(.*?)>";
public static MvcHtmlString IsDisabled(this MvcHtmlString htmlString, bool disabled)
{
string rawString = htmlString.ToString();
if (disabled)
{
rawString = Regex.Replace(rawString, endFieldPattern, "$1 disabled=\"disabled\">");
}
return new MvcHtmlString(rawString);
}
public static MvcHtmlString IsReadonly(this MvcHtmlString htmlString, bool @readonly)
{
string rawString = htmlString.ToString();
if (@readonly)
{
rawString = Regex.Replace(rawString, endFieldPattern, "$1 readonly=\"readonly\">");
}
return new MvcHtmlString(rawString);
}
and then....
@Html.TextBoxFor(model => model.Name, new { @class= "someclass"}).IsDisabled(Model.ExpireDate == null)
Similar setup here and looks like it was just a bug in my code. At the start of my app I looked for the offending URL and this worked: echo '<html>test</html>'; exit();
In my case, turns out the problem was an uninitialized variable that only failed under peculiar circumstances.
To diagnose better, you can capture the standard output and standard error streams of the external program, in order to see what output was generated and why it might not be running as expected.
Look up:
If you set each of those to true, then you can later call process.StandardOutput.ReadToEnd()
and process.StandardError.ReadToEnd()
to get the output into string variables, which you can easily inspect under the debugger, or output to trace or your log file.
Alternatively, if you are not concerned with the possible exception raised, you could change TryParse for Parse:
DateTime? d = DateTime.Parse("some valid text");
Although there won't be a boolean indicating success either, it could be practical in some situations where you know that the input text will always be valid.
The way your radios are set up in the fiddle - sharing the same model - will cause only the last group to show a checked radio if you decide to quote all of the truthy values. A more solid approach will involve giving the individual groups their own model, and set the value as a unique attribute of the radios, such as the id:
$scope.radioMod = 1;
$scope.radioMod2 = 2;
Here is a representation of the new html:
<label data-ng-repeat="choice2 in question2.choices">
<input type="radio" name="response2" data-ng-model="radioMod2" value="{{choice2.id}}"/>
{{choice2.text}}
</label>
From the Heroku Web
Dashboard => Your App Name => Resources => Pencil icon=> Flip the switch => Confirm
if you want to open all your .cpp
files with one command, and have the window split in as many tiles as opened files, you can use:
vim -o $(find name ".cpp")
if you want to include a template in the place you are, you can use:
:r ~/myHeaderTemplate
will import the file "myHeaderTemplate in the place the cursor was before starting the command.
you can conversely select visually some code and save it to a file
when you select visualy, after type ":" in order to enter a command, you'll see "'<,'>" appear after the ":"
'<,'>w ~/myfile $
^ if you add "~/myfile" to the command, the selected part of the file will be saved to myfile.
if you're editing a file an want to copy it :
:saveas newFileWithNewName
It's best to use whatever one reads better - there's in all practical effect 0 difference between performance.
In this case I think the last statement reads better than the first if statement, but careful not to overuse the ternary operator - sometimes it can really make things a lot less clear.
You must have either disabled
, froze
or uninstalled
FaceProvider in settings>applications>all
This will only happen if it's frozen
, either uninstall
it, or enable
it.
The code of JS20'07'11 is really incredible simple and direct. One suggestion that I would like to give is to put a exclamation mark in the conditions:
InStr(1, objName.RefersTo, sWsName+"!", vbTextCompare)
Because this will prevent adding a NamedRange in an incorrect Sheet. Eg: If the NamedRange refers to a Sheet named Plan11 and you have another Sheet named Plan1 the code can do some mess when add the ranges if you don't use the exclamation mark.
UPDATE
A correction: It's best to use a regular expression evaluate the name of the Sheet. A simple function that you can use is the following (adapted by http://blog.malcolmp.com/2010/regular-expressions-excel-add-in, enable Microsoft VBScript Regular Expressions 5.5):
Function xMatch(pattern As String, searchText As String, Optional matchIndex As Integer = 1, Optional ignoreCase As Boolean = True) As String
On Error Resume Next
Dim RegEx As New RegExp
RegEx.Global = True
RegEx.MultiLine = True
RegEx.pattern = pattern
RegEx.ignoreCase = ignoreCase
Dim matches As MatchCollection
Set matches = RegEx.Execute(searchText)
Dim i As Integer
i = 1
For Each Match In matches
If i = matchIndex Then
xMatch = Match.Value
End If
i = i + 1
Next
End Function
So, You can use something like that:
xMatch("'?" +sWsName + "'?" + "!", objName.RefersTo, 1) <> ""
instead of
InStr(1, objName.RefersTo, sWsName+"!", vbTextCompare)
This will cover Plan1 and 'Plan1' (when the range refers to more than one cell) variations
TIP: Avoid Sheet names with single quotes ('), :) .
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
If you're using angularJS or some variant of the Q promise library, then you have a .all()
method that solves this exact problem.
var savePromises = [];
angular.forEach(models, function(model){
savePromises.push(
model.saveToServer()
)
});
$q.all(savePromises).then(
function success(results){...},
function failed(results){...}
);
see the full API:
https://github.com/kriskowal/q/wiki/API-Reference#promiseall
Use:
npm run test -- test-name
This will only work if your test specification name is unique.
The code above would reference a file with this name: test-name.component.spec.ts
One of my first projects as a programmer was a gem called stagecoach that (among other things) allowed the automatic adding of a github issue number to every commit message on a branch, which is a part of the question that hasn't really been answered.
Essentially when creating a branch you'd use a custom command (something like stagecoach -b <branch_name> -g <issue_number>
), and the issue number would then be assigned to that branch in a yml file. There was then a commit hook that appended the issue number to the commit message automatically.
I wouldn't recommend it for production use as at the time I'd only been programming for a few months and I no longer maintain it, but it may be of interest to somebody.
Copy-pasted from here: Incrementing a date in JavaScript
Three options for you:
Using just JavaScript's Date object (no libraries):
var today = new Date(); var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
Or if you don't mind changing the date in place (rather than creating a new date):
var dt = new Date(); dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));
Edit: See also Jigar's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
Using MomentJS:
var today = moment(); var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)
Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today() var tomorrow = today.add(1).day();
I think the answer is here (possibly duplicate):
How to test if a file is a directory in a batch script?
IF EXIST %VAR%\NUL ECHO It's a directory
Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.
As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)
if exist "c:\folder\" echo folder exists
should be enough for modern windows.
The Way I solved this problem is , Install TCPview go to TCP view and check what ports is Tomcat utilizing there will be few other ports other than 8005,8009,8080 now go to Servers tab in eclipse double click on Tomcatv9.0 server and change port numbers there. This will solve the problem.
n % x == 0
Means that n can be divided by x. So... for instance, in your case:
boolean isDivisibleBy20 = number % 20 == 0;
Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:
boolean even = (number & 1) == 0;
boolean odd = (number & 1) != 0;
Use the -printcert
command like this:
keytool -printcert -file certificate.pem
I used back.png image in the project menifest.xml file. it is fine working in project.
<activity
android:name=".YourActivity"
android:icon="@drawable/back"
android:label="@string/app_name" >
</activity>
Solution posted by Denys S. in the question post:
I quite messed it up with c to c++ conversion (basically env
variable stuff), but I got it working with the following code for C++:
#include <string.h>
#include <stdio.h>
#include <jni.h>
jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){
jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);
const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
printf("%s\n", str);
return (*env)->NewStringUTF(env, str);
}
And next code for java methods:
public class MainActivity extends Activity {
private static String LIB_NAME = "thelib";
static {
System.loadLibrary(LIB_NAME);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textview);
tv.setText(this.getJniString());
}
// please, let me live even though I used this dark programming technique
public String messageMe(String text) {
System.out.println(text);
return text;
}
public native String getJniString();
}
Yes, PHP supports arrays as session variables. See this page for an example.
As for your second question: once you set the session variable, it will remain the same until you either change it or unset
it. So if the 3rd page doesn't change the session variable, it will stay the same until the 2nd page changes it again.
dictionary["C1"]=map(lambda x:x+10,dictionary["C1"])
Should do it...
Jdk 9 and 10 solution
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<debug>true</debug>
</configuration>
<dependencies>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>6.2</version>
</dependency>
</dependencies>
</plugin>
and make sure your maven is pointing to JDK 10 or 9. mvn -v
Apache Maven 3.5.3 (3383c37e1f9e9b3bc3df5050c29c8aff9f295297; 2018-02-24T14:49:05-05:00)
Maven home: C:\devplay\apache-maven-3.5.3\bin\..
Java version: 10.0.1, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk-10.0.1
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
With
void DoWork(int n);
n
is a copy of the value of the actual parameter, and it is legal to change the value of n
within the function. With
void DoWork(const int &n);
n
is a reference to the actual parameter, and it is not legal to change its value.
For setting up virtualenv on a clean Ubuntu installation, I found this zookeeper tutorial to be the best - you can ignore the parts about zookeper itself. The virtualenvwrapper documentation offers similar content, but it's a bit scarce on telling you what exactly to put into your .bashrc
file.
PPK ? OpenSSH RSA with PuttyGen & Docker.
Private key:
docker run --rm -v $(pwd):/app zinuzoid/puttygen private.ppk -O private-openssh -o my-openssh-key
Public key:
docker run --rm -v $(pwd):/app zinuzoid/puttygen private.ppk -L -o my-openssh-key.pub
You can also use the v-bind directly to the template like ...
<a :href="'/path-to-route/' + IdVariable">
the :
is the abbreviation of v-bind
.
As the statement executed is not actually DML (eg UPDATE
, INSERT
or EXECUTE
), but a piece of T-SQL which contains DML, I suspect it is not treated as an update-query.
Section 13.1.2.3 of the JDBC 4.1 specification states something (rather hard to interpret btw):
When the method
execute
returns true, the methodgetResultSet
is called to retrieve the ResultSet object. Whenexecute
returns false, the methodgetUpdateCount
returns an int. If this number is greater than or equal to zero, it indicates the update count returned by the statement. If it is -1, it indicates that there are no more results.
Given this information, I guess that executeUpdate()
internally does an execute()
, and then - as execute()
will return false
- it will return the value of getUpdateCount()
, which in this case - in accordance with the JDBC spec - will return -1
.
This is further corroborated by the fact 1) that the Javadoc for Statement.executeUpdate()
says:
Returns: either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
And 2) that the Javadoc for Statement.getUpdateCount() specifies:
the current result as an update count; -1 if the current result is a ResultSet object or there are no more results
Just to clarify: given the Javadoc for executeUpdate()
the behavior is probably wrong, but it can be explained.
Also as I commented elsewhere, the -1 might just indicate: maybe something was changed, but we simply don't know, or we can't give an accurate number of changes (eg because in this example it is a piece of T-SQL that is executed).
If you want to run the #'.py' file just write in print() in your code to actually see it get printed. Unlike python IDLE, you need to specify what you want to print using print() command. For eg.
import os
os.getcwd()
a=[1,2,3,4,5]
name= 'Python'
# Use print() function
print(a)
print(name)
OUTPUT [1, 2, 3, 4, 5] Python
SELECT * from `user` ORDER BY `user_id`;
SET @count = 0;
UPDATE `user` SET `user_id` = @count:= @count + 1;
ALTER TABLE `user_id` AUTO_INCREMENT = 1;
if you want to order by
You should enable the unicode strings feature, and this is the default if you use v5.14;
You should not really use unicode identifiers esp. for foreign code via utf8 as they are insecure in perl5, only cperl got that right. See e.g. http://perl11.org/blog/unicode-identifiers.html
Regarding utf8 for your filehandles/streams: You need decide by yourself the encoding of your external data. A library cannot know that, and since not even libc supports utf8, proper utf8 data is rare. There's more wtf8, the windows aberration of utf8 around.
BTW: Moose is not really "Modern Perl", they just hijacked the name. Moose is perfect Larry Wall-style postmodern perl mixed with Bjarne Stroustrup-style everything goes, with an eclectic aberration of proper perl6 syntax, e.g. using strings for variable names, horrible fields syntax, and a very immature naive implementation which is 10x slower than a proper implementation. cperl and perl6 are the true modern perls, where form follows function, and the implementation is reduced and optimized.
In C# Predicates are simply delegates that return booleans. They're useful (in my experience) when you're searching through a collection of objects and want something specific.
I've recently run into them in using 3rd party web controls (like treeviews) so when I need to find a node within a tree, I use the .Find() method and pass a predicate that will return the specific node I'm looking for. In your example, if 'a' mod 2 is 0, the delegate will return true. Granted, when I'm looking for a node in a treeview, I compare it's name, text and value properties for a match. When the delegate finds a match, it returns the specific node I was looking for.
As already mentioned, a device may support both mouse and touch input. Very often, the question is not "what is supported" but "what is currently used".
For this case, you can simply register mouse events (including the hover listener) and touch events alike.
element.addEventListener('touchstart',onTouchStartCallback,false);
element.addEventListener('onmousedown',onMouseDownCallback,false);
...
JavaScript should automatically call the correct listener based on user input. So, in case of a touch event, onTouchStartCallback
will be fired, emulating your hover code.
Note that a touch may fire both kinds of listeners, touch and mouse. However, the touch listener goes first and can prevent subsequent mouse listeners from firing by calling event.preventDefault()
.
function onTouchStartCallback(ev) {
// Call preventDefault() to prevent any further handling
ev.preventDefault();
your code...
}
Further reading here.
If you want to filter the models by applicationname
and the remaining models by surname
:
List<Model> newList = list.Where(m => m.application == "applicationname")
.Select(m => new Model {
application = m.application,
users = m.users.Where(u => u.surname == "surname").ToList()
}).ToList();
As you can see, it needs to create new models and user-lists, hence it is not the most efficient way.
If you instead don't want to filter the list of users but filter the models by users with at least one user with a given username, use Any
:
List<Model> newList = list
.Where(m => m.application == "applicationname"
&& m.users.Any(u => u.surname == "surname"))
.ToList();
Why setContentView() in Android Had Been So Popular Till Now?
setContentView(int layoutid) - method of activity class. It shows layout on screen.
R.layout.main - is an integer number implemented in nested layout class of R.java class file.
At the run time device will pick up their layout based on the id given in setcontentview() method.
Sample Instruction
Given an integer, n
, performing the following conditional actions:
import math
n = int(input())
if n % 2 ==1:
print("Weird")
elif n % 2==0 and n in range(2,6):
print("Not Weird")
elif n % 2 == 0 and n in range(6,21):
print("Weird")
elif n % 2==0 and n>20:
print("Not Weird")
If the repository is on GitHub, you can use the open source Android app Octodroid which displays the size of the repository by default.
For example, with the mptcp repository:
Disclaimer: I didn't create Octodroid.
You can also generate source code from schema using jaxb2-maven-plugin plugin:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<sources>
<source>src/main/resources/your_schema.xsd</source>
</sources>
<xjbSources>
<xjbSource>src/main/resources/bindings.xjb</xjbSource>
</xjbSources>
<packageName>some_package</packageName>
<outputDirectory>src/main/java</outputDirectory>
<clearOutputDir>false</clearOutputDir>
<generateEpisode>false</generateEpisode>
<noGeneratedHeaderComments>true</noGeneratedHeaderComments>
</configuration>
</plugin>
In JSF I used:
<h:head>
<f:facet name="first">
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
</f:facet>
<!-- ... other meta tags ... -->
</h:head>
to get distance between two points try this code..
public static float GetDistanceFromCurrentPosition(double lat1,double lng1, double lat2, double lng2)
{
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
* Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;
int meterConversion = 1609;
return new Float(dist * meterConversion).floatValue();
}
You can also just use the pipeline with the AddScript Method:
string cmdArg = ".\script.ps1 -foo bar"
Collection<PSObject> psresults;
using (Pipeline pipeline = _runspace.CreatePipeline())
{
pipeline.Commands.AddScript(cmdArg);
pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
psresults = pipeline.Invoke();
}
return psresults;
It will take a string, and whatever parameters you pass it.
I believe if you combine the delete by query with a match all it should do what you are looking for, something like this (using your example):
curl -XDELETE 'http://localhost:9200/twitter/tweet/_query' -d '{
"query" : {
"match_all" : {}
}
}'
Or you could just delete the type:
curl -XDELETE http://localhost:9200/twitter/tweet
Try this :)
var mystring = "How do I get a long text string";
mystring = mystring.substring(0,10);
alert(mystring);
I use ? (0x25B8) for the right arrow, often to show a collapsed list; and I pair it with ? (0x25BE) to show the list opened up. Both are unobtrusive.
var a1 = [1,2,3,6];
var a2 = [1,2,3,5];
function check(a, b) {
return (a.length != b.length) ? false :
a.every(function(row, index) {
return a[index] == b[index];
});
}
check(a1, a2);
////// OR ///////
var a1 = [1,2,3,6];
var a2 = [1,2,3,6];
function check(a, b) {
return (a.length != b.length) ? false :
!(a.some(function(row, index) {
return a[index] != b[index];
}));
}
check(a1, a2)
Try the below Code:
$("#textbox").on('change keypress paste', function() {
console.log("Handler for .keypress() called.");
});
Font myFont = new Font ("Courier New", 1, 17);
The 17 represents the font size. Once you have that, you can put:
g.setFont (myFont);
g.drawString ("Hello World", 10, 10);
Check this thread out: read and write image file.
Also, have a look at this other question at Stackoverflow.
Since you are selecting multiple tables, The table to delete from is no longer unambiguous. You need to select:
DELETE posts FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id
In this case, table_name1
and table_name2
are the same table, so this will work:
DELETE projects FROM posts INNER JOIN [...]
You can even delete from both tables if you wanted to:
DELETE posts, projects FROM posts INNER JOIN [...]
Note that order by
and limit
don't work for multi-table deletes.
Also be aware that if you declare an alias for a table, you must use the alias when referring to the table:
DELETE p FROM posts as p INNER JOIN [...]
Total control version:
in your terminal, navigate to home directory
cd
create file .bash_profile
touch .bash_profile
open file with TextEdit
open -e .bash_profile
insert line into TextEdit
export PATH=$PATH:/Users/username/Library/Android/sdk/platform-tools/
save file and reload file
source ~/.bash_profile
check if adb was set into path
adb version
One liner version
Echo your export command and redirect the output to be appended to .bash_profile file and restart terminal. (have not verified this but should work)
echo "export PATH=$PATH:/Users/username/Library/Android/sdk/platform-tools/ sdk/platform-tools/" >> ~/.bash_profile
to add parameter to post urls (to perma-links), i use this:
add_filter( 'post_type_link', 'append_query_string', 10, 2 );
function append_query_string( $url, $post )
{
return add_query_arg('my_pid',$post->ID, $url);
}
output:
http://yoursite.com/pagename?my_pid=12345678
I'm new to git but it seems that if I do git checkout for each directory then it works. Also, the sparse-checkout file needs to have a trailing slash after every directory as indicated. Someone more experience please confirm that this will work.
Interestingly, if you checkout a directory not in the sparse-checkout file it seems to make no difference. They don't show up in git status and git read-tree -m -u HEAD doesn't cause it to be removed. git reset --hard doesn't cause the directory to be removed either. Anyone more experienced care to comment on what git thinks of directories that are checked out but which are not in the sparse checkout file?
Your stored procedure expects 5 parameters as input
@userID int,
@userName varchar(50),
@password nvarchar(50),
@emailAddress nvarchar(50),
@preferenceName varchar(20)
So you should add all 5 parameters to this SP call:
cmd.CommandText = "SHOWuser";
cmd.Parameters.AddWithValue("@userID",userID);
cmd.Parameters.AddWithValue("@userName", userName);
cmd.Parameters.AddWithValue("@password", password);
cmd.Parameters.AddWithValue("@emailAddress", emailAddress);
cmd.Parameters.AddWithValue("@preferenceName", preferences);
dbcon.Open();
PS: It's not clear what these parameter are for. You don't use these parameters in your SP body so your SP should looks like:
ALTER PROCEDURE [dbo].[SHOWuser] AS BEGIN ..... END
You should use <h:panelGroup ...>
tag with attribute rendered
. If you set true
to rendered, the content of <h:panelGroup ...>
won't be shown. Your XHTML file should have something like this:
<h:panelGroup rendered="#{userBean.showPassword}">
<h:outputText id="password" value="#{userBean.password}"/>
</h:panelGroup>
UserBean.java:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class UserBean implements Serializable{
private boolean showPassword = false;
private String password = "";
public boolean isShowPassword(){
return showPassword;
}
public void setPassword(password){
this.password = password;
}
public String getPassword(){
return this.password;
}
}
It's not necessarily important; it depends on the size of your collections and your performance requirements and whether your class will be used in a library where you may not know the performance requirements. I frequently know my collection sizes are not very large and my time is more valuable than a few microseconds of performance gained by creating a perfect hash code; so (to get rid of the annoying warning by the compiler) I simply use:
public override int GetHashCode()
{
return base.GetHashCode();
}
(Of course I could use a #pragma to turn off the warning as well but I prefer this way.)
When you are in the position that you do need the performance than all of the issues mentioned by others here apply, of course. Most important - otherwise you will get wrong results when retrieving items from a hash set or dictionary: the hash code must not vary with the life time of an object (more accurately, during the time whenever the hash code is needed, such as while being a key in a dictionary): for example, the following is wrong as Value is public and so can be changed externally to the class during the life time of the instance, so you must not use it as the basis for the hash code:
class A
{
public int Value;
public override int GetHashCode()
{
return Value.GetHashCode(); //WRONG! Value is not constant during the instance's life time
}
}
On the other hand, if Value can't be changed it's ok to use:
class A
{
public readonly int Value;
public override int GetHashCode()
{
return Value.GetHashCode(); //OK Value is read-only and can't be changed during the instance's life time
}
}
redirect with query string
$('#results').on('click', '.item', function () {
var NestId = $(this).data('id');
// var url = '@Url.Action("Details", "Artists",new { NestId = '+NestId+' })';
var url = '@ Url.Content("~/Artists/Details?NestId =' + NestId + '")'
window.location.href = url;
})
I wouldn't go with MSTest. Although it's probably the most future proof of the frameworks with Microsoft behind it's not the most flexible solution. It won't run stand alone without some hacks. So running it on a build server other than TFS without installing Visual Studio is hard. The visual studio test-runner is actually slower than Testdriven.Net + any of the other frameworks. And because the releases of this framework are tied to releases of Visual Studio there are less updates and if you have to work with an older VS you're tied to an older MSTest.
I don't think it matters a lot which of the other frameworks you use. It's really easy to switch from one to another.
I personally use XUnit.Net or NUnit depending on the preference of my coworkers. NUnit is the most standard. XUnit.Net is the leanest framework.
Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li>
elements with class="dropdown-menu"
. It automatically displays the proper caret indicator as well.
<head>
...
<script src=".../jquery.smartmenus.min.js"></script>
<script src=".../jquery.smartmenus.bootstrap.min.js"></script>
...
<link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
...
</head>
Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html
keep it simple
<div align="center">
<div style="display: inline-block"> <img src="img1.png"> </div>
<div style="display: inline-block"> <img src="img2.png"> </div>
</div>
From http://www.gnu.org/s/bash/manual/bash.html#Special-Parameters
?
Expands to the exit status of the most recently executed foreground pipeline.
people.OrderBy(person => person.lastname).ToList();
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username
and password
:
data: 'username='+username+'&password='+password,
In the FILE2.php example, you would retrieve those values like this:
$uname = $_POST['username'];
$pword = $_POST['password'];
Then do your MySQL lookup and return the values thus:
echo 'You are logged in';
This would deliver the message You are logged in
to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data);
line in the success function would alert that message. Of course, you can echo
anything that you like, even large amounts of HTML, such as entire table structures.
Here is another good example to review.
The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.
The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).
The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script>
tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?>
at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.
In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.
list.set(5,"newString");
A quick way to explain this is to visualize it.
if both i and j are from 0 to N, it's easy to see O(N^2)
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
in this case, it's:
O
O O
O O O
O O O O
O O O O O
O O O O O O
O O O O O O O
O O O O O O O O
This comes out to be 1/2 of N^2, which is still O(N^2)
You want $_SERVER['REQUEST_URI']
. From the docs:
'REQUEST_URI'
The URI which was given in order to access this page; for instance,
'/index.html'
.
Yes, this is a classpath issue. You need to tell the compiler and runtime that the directory where your .class files live is part of the CLASSPATH. The directory that you need to add is the parent of the "com" directory at the start of your package structure.
You do this using the -classpath argument for both javac.exe and java.exe.
Should also ask how the 3rd party classes you're using are packaged. If they're in a JAR, and I'd recommend that you have them in one, you add the .jar file to the classpath:
java -classpath .;company.jar foo.bar.baz.YourClass
Google for "Java classpath". It'll find links like this.
One more thing: "import" isn't loading classes. All it does it save you typing. When you include an import statement, you don't have to use the fully-resolved class name in your code - you can type "Foo" instead of "com.company.thing.Foo". That's all it's doing.
Sometimes i see this error in my project. I solve that by
1 - Right click on EDMX file
2 - Select Run Custom Tool
option
3 - Rebuild project
I have some hacky answers that are likely to be terrible... but I have very little experience at this point.
a way:
class myClass():
myInstances = []
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
self.__class__.myInstances.append(self)
myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar", "Baz")
for thisObj in myClass.myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
A hack way to get this done:
import sys
class myClass():
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar", "Baz")
myInstances = []
myLocals = str(locals()).split("'")
thisStep = 0
for thisLocalsLine in myLocals:
thisStep += 1
if "myClass object at" in thisLocalsLine:
print(thisLocalsLine)
print(myLocals[(thisStep - 2)])
#myInstances.append(myLocals[(thisStep - 2)])
print(myInstances)
myInstances.append(getattr(sys.modules[__name__], myLocals[(thisStep - 2)]))
for thisObj in myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
Another more 'clever' hack:
import sys
class myClass():
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
myInstances = []
myClasses = {
"myObj01": ["Foo", "Bar"],
"myObj02": ["FooBar", "Baz"]
}
for thisClass in myClasses.keys():
exec("%s = myClass('%s', '%s')" % (thisClass, myClasses[thisClass][0], myClasses[thisClass][1]))
myInstances.append(getattr(sys.modules[__name__], thisClass))
for thisObj in myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
If you're using jQuery 1.5, then statusCode
will work.
If you're using jQuery 1.4, try this:
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
You should see the status code from the first alert.
I've faced this error, when there was no enough free space to create backup.
Actually, I figured it out myself that I could do this:
while (rdr.read())
{
string str = rdr.GetValue().ToString().Trim();
}
If you're using Ubuntu then use the following:
sudo chown -R ubuntu /var/www/html
sudo chmod -R 755 /var/www/html
Answering your first question, a set is a data structure optimized for set operations. Like a mathematical set, it does not enforce or maintain any particular order of the elements. The abstract concept of a set does not enforce order, so the implementation is not required to. When you create a set from a list, Python has the liberty to change the order of the elements for the needs of the internal implementation it uses for a set, which is able to perform set operations efficiently.
Xcode 8 bug…
Try this first if your Storyboard UITableView style is set to Plain.
Set the table's style to Grouped and then back to Plain. This removed the space in my app at the head of my UITableView.
Thread.interrupt()
sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait()
may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException
)
Interruption in Java is not pre-emptive. Put another way both threads have to cooperate in order to process the interrupt properly. If the target thread does not poll the interrupted status the interrupt is effectively ignored.
Polling occurs via the Thread.interrupted()
method which returns the current thread's interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.
EDIT (from Thilo comments): Some API methods have built in interrupt handling. Of the top of my head this includes.
Object.wait()
, Thread.sleep()
, and Thread.join()
java.util.concurrent
structuresInterruptedException
, instead using ClosedByInterruptException
.EDIT (from @thomas-pornin's answer to exactly same question for completeness)
Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit cleanly, as opposed to Thread.stop()
that is more like shooting the thread with an assault rifle.
I prefer:
$qb->andWhere($qb->expr()->in('t.user_role_id', [
User::USER_ROLE_ID_ADVERTISER,
User::USER_ROLE_ID_MANAGER,
]));
You can simply get HQ youtube thumbnails..
Actually you get promise
on $http.get
.
Try to use followed flow:
<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
<span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
<span>{{document.Name}}</span>
</li>
Where documents
is your array.
$scope.documents = [];
$http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
result.data.forEach(function(val, i) {
$scope.documents.push(/* put data here*/);
});
}, function(error) {
alert(error.message);
});
This is a little late to the party, but I have been struggling with this for a couple of days. It is possible and none of the answers I found here have worked. It's deceptively simple. Here's the .ajax call:
<!DOCTYPE HTML>_x000D_
<html>_x000D_
<head>_x000D_
<body>_x000D_
<title>Javascript Test</title>_x000D_
<script src="http://code.jquery.com/jquery-latest.min.js"></script>_x000D_
<script type="text/javascript">_x000D_
$(document).domain = 'XXX.com';_x000D_
$(document).ready(function () {_x000D_
$.ajax({_x000D_
xhrFields: {cors: false},_x000D_
type: "GET",_x000D_
url: "http://XXXX.com/test.php?email='[email protected]'",_x000D_
success: function (data) {_x000D_
alert(data);_x000D_
},_x000D_
error: function (x, y, z) {_x000D_
alert(x.responseText + " :EEE: " + x.status);_x000D_
}_x000D_
});_x000D_
});_x000D_
</script> _x000D_
</body>_x000D_
</html>
_x000D_
Here's the php on the server side:
<html>_x000D_
<head>_x000D_
<title>PHP Test</title>_x000D_
</head>_x000D_
<body>_x000D_
<?php_x000D_
header('Origin: xxx.com');_x000D_
header('Access-Control-Allow-Origin:*');_x000D_
$servername = "sqlxxx";_x000D_
$username = "xxxx";_x000D_
$password = "sss";_x000D_
$conn = new mysqli($servername, $username, $password);_x000D_
if ($conn->connect_error) {_x000D_
die( "Connection failed: " . $conn->connect_error);_x000D_
}_x000D_
$sql = "SELECT email, status, userdata FROM msi.usersLive";_x000D_
$result = $conn->query($sql);_x000D_
if ($result->num_rows > 0) {_x000D_
while($row = $result->fetch_assoc()) {_x000D_
echo $row["email"] . ":" . $row["status"] . ":" . $row["userdata"] . "<br>";_x000D_
}_x000D_
} else {_x000D_
echo "{ }";_x000D_
}_x000D_
$conn->close();_x000D_
?>_x000D_
</body>
_x000D_
Calling .parents(".box .something1")
will return all parent elements that match the selector .box .something
. In other words, it will return parent elements that are .something1
and are inside of .box
.
You need to get the children of the closest parent, like this:
$(this).closest('.box').children('.something1')
This code calls .closest
to get the innermost parent matching a selector, then calls .children
on that parent element to find the uncle you're looking for.
If you use Kotlin, it supports these nullability annotations in its compiler and will prevent you from passing a null to a java method that requires a non-null argument. Event though this question was originally targeted at Java, I mention this Kotlin feature because it is specifically targeted at these Java annotation and the question was "Is there a way to make these annotations more strictly enforced and/or propagate further?" and this feature does make these annotation more strictly enforced.
Java class using @NotNull
annotation
public class MyJavaClazz {
public void foo(@NotNull String myString) {
// will result in an NPE if myString is null
myString.hashCode();
}
}
Kotlin class calling Java class and passing null for the argument annotated with @NotNull
class MyKotlinClazz {
fun foo() {
MyJavaClazz().foo(null)
}
}
Kotlin compiler error enforcing the @NotNull
annotation.
Error:(5, 27) Kotlin: Null can not be a value of a non-null type String
see: http://kotlinlang.org/docs/reference/java-interop.html#nullability-annotations
When you want to zoom out a web page to fit it into the iframe size:
Here is an example:
<div id="wrap">
<IFRAME ID="frame" name="Main" src ="http://www.google.com" />
</div>
<style type="text/css">
#wrap { width: 130px; height: 130px; padding: 0; overflow: hidden; }
#frame { width: 900px; height: 600px; border: 1px solid black; }
#frame { zoom:0.15; -moz-transform:scale(0.15);-moz-transform-origin: 0 0; }
</style>
Pandas 0.24.0+ solution
In Pandas 0.24.0 a new feature was introduced specifically designed for fast writes to Postgres. You can learn more about it here: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method
import csv
from io import StringIO
from sqlalchemy import create_engine
def psql_insert_copy(table, conn, keys, data_iter):
# gets a DBAPI connection that can provide a cursor
dbapi_conn = conn.connection
with dbapi_conn.cursor() as cur:
s_buf = StringIO()
writer = csv.writer(s_buf)
writer.writerows(data_iter)
s_buf.seek(0)
columns = ', '.join('"{}"'.format(k) for k in keys)
if table.schema:
table_name = '{}.{}'.format(table.schema, table.name)
else:
table_name = table.name
sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(
table_name, columns)
cur.copy_expert(sql=sql, file=s_buf)
engine = create_engine('postgresql://myusername:mypassword@myhost:5432/mydatabase')
df.to_sql('table_name', engine, method=psql_insert_copy)
Note that if the user may be in multiple zones used in the query, you may probably want to add .distinct()
. Otherwise you get one user multiple times:
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3]).distinct()
Add these lines after newWin.document.write(divToPrint.innerHTML)
newWin.document.close();
newWin.focus();
newWin.print();
newWin.close();
Then print function will work in all browser...
What about extensions on Double and CGFloat types:
extension Double {
func formatted(_ decimalPlaces: Int?) -> String {
let theDecimalPlaces : Int
if decimalPlaces != nil {
theDecimalPlaces = decimalPlaces!
}
else {
theDecimalPlaces = 2
}
let theNumberFormatter = NumberFormatter()
theNumberFormatter.formatterBehavior = .behavior10_4
theNumberFormatter.minimumIntegerDigits = 1
theNumberFormatter.minimumFractionDigits = 1
theNumberFormatter.maximumFractionDigits = theDecimalPlaces
theNumberFormatter.usesGroupingSeparator = true
theNumberFormatter.groupingSeparator = " "
theNumberFormatter.groupingSize = 3
if let theResult = theNumberFormatter.string(from: NSNumber(value:self)) {
return theResult
}
else {
return "\(self)"
}
}
}
Usage:
let aNumber: Double = 112465848348508.458758344
Swift.print("The number: \(aNumber.formatted(2))")
prints: 112 465 848 348 508.46
This will work for ENUM type as default value
ALTER TABLE engagete_st.holidays add column `STATUS` ENUM('A', 'D') default 'A' AFTER `H_TYPE`;
If I understand your question correctly:
for elem in doc.findall('timeSeries/values/value'):
print elem.get('dateTime'), elem.text
or if you prefer (and if there is only one occurrence of timeSeries/values
:
values = doc.find('timeSeries/values')
for value in values:
print value.get('dateTime'), elem.text
The findall()
method returns a list of all matching elements, whereas find()
returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values
element, in this case leading to the same result.
I don't see where the problem with not finding timeSeries
comes from however. Maybe you just forgot the getroot()
call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values
or //timeSeries/values
)
Create your assets directory the same as lib level
like this
projectName
-android
-ios
-lib
-assets
-pubspec.yaml
then your pubspec.yaml like
flutter:
assets:
- assets/images/
now you can use Image.asset("/assets/images/")
Wildcards can only be used in the ServerAlias
rather than the ServerName
. Something which had me stumped.
For your use case, the following should suffice
<VirtualHost *:80>
ServerAlias *.example.com
VirtualDocumentRoot /var/www/%1/
</VirtualHost>
For iPhone Devices : Now we need only one size iPhone 6 Plus (5.5 Inch) • 1242 x 2208 Then we have check box there, in all other sizes to : Use 5.5-Inch Display
One more reason I found (vague as it may sound). The below did not work.
LinearLayout vertical
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
EndLinearLayout
What did work was
RelativeLayout
LinearLayout vertical
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
EndLinearLayout
EndRelativeLayout
It sounds vague by a root layout with Linear and weights under it did not work. And when I say "did not work", I mean, that after I viewed the graphical layout between various resolutions the screen consistency broke big time.
Sorry, Im a newbie myself and I had this issue:
./hello.py: line 1: syntax error near unexpected token "Hello World"'
./hello.py: line 1:
print("Hello World")'
I added the file header for the python 'deal' as #!/usr/bin/python
Then simple executed the program with './hello.py'
You could use the System.Net.Mail.MailMessage class of the .NET framework.
You can find the MSDN documentation here.
Here is a simple example (code snippet):
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
...
try
{
SmtpClient mySmtpClient = new SmtpClient("my.smtp.exampleserver.net");
// set smtp-client with basicAuthentication
mySmtpClient.UseDefaultCredentials = false;
System.Net.NetworkCredential basicAuthenticationInfo = new
System.Net.NetworkCredential("username", "password");
mySmtpClient.Credentials = basicAuthenticationInfo;
// add from,to mailaddresses
MailAddress from = new MailAddress("[email protected]", "TestFromName");
MailAddress to = new MailAddress("[email protected]", "TestToName");
MailMessage myMail = new System.Net.Mail.MailMessage(from, to);
// add ReplyTo
MailAddress replyTo = new MailAddress("[email protected]");
myMail.ReplyToList.Add(replyTo);
// set subject and encoding
myMail.Subject = "Test message";
myMail.SubjectEncoding = System.Text.Encoding.UTF8;
// set body-message and encoding
myMail.Body = "<b>Test Mail</b><br>using <b>HTML</b>.";
myMail.BodyEncoding = System.Text.Encoding.UTF8;
// text or html
myMail.IsBodyHtml = true;
mySmtpClient.Send(myMail);
}
catch (SmtpException ex)
{
throw new ApplicationException
("SmtpException has occured: " + ex.Message);
}
catch (Exception ex)
{
throw ex;
}
A constructor should no have a return type . remove void before each constructor .
Some very basic characteristic of a constructor :
a. Same name as class b. no return type. c. will be called every time an object is made with the class. for eg- in your program if u made two objects of Flow, Flow flow1=new Flow(); Flow flow2=new Flow(); then Flow constructor will be called for 2 times.
d. If you want to call the constructor just for once then declare that as static (static constructor) and dont forget to remove any access modifier from static constructor ..
Assuming I understand what you mean:
If your UserControl
is in a library you can add this to you Toolbox using
Toolbox -> right click -> Choose Items -> Browse
Select your assembly with the UserControl
.
If the UserControl
is part of your project you only need to build the entire solution. After that, your UserControl
should appear in the toolbox.
In general, it is not possible to add a Control from Solution Explorer, only from the Toolbox.
Anaconda does not use the PYTHONPATH
. One should however note that if the PYTHONPATH
is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a
unset PYTHONPATH
For instance this PYTHONPATH points to an incorrect pandas lib:
export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
unsetting the PYTHONPATH
prevents the wrong pandas lib from being loaded:
unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>
You can convert yourInt
to bytes by using a ByteBuffer
like this:
return ByteBuffer.allocate(4).putInt(yourInt).array();
Beware that you might have to think about the byte order when doing so.
try this
input[type='text']
{
background:red !important;
}
os.Mkdir
is used to create a single directory. To create a folder path, instead try using:
os.MkdirAll(folderPath, os.ModePerm)
func MkdirAll(path string, perm FileMode) error
MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.
Edit:
Updated to correctly use os.ModePerm
instead.
For concatenation of file paths, use package path/filepath
as described in @Chris' answer.
return false
in your listener should work in all browsers.
$('orderNowForm').addEvent('submit', function () {
// your code
return false;
}
TakeScreenShot screenshot=new TakeScreenShot();
screenshot.screenShot("screenshots//TestScreenshot//password.png");
it will work , please try.
<div class="row" data-toggle="popover" data-trigger="hover"
data-content="My popover content.My popover content.My popover content.My popover content.">
<div class="col-md-6">
<label for="name">Name:</label>
<input id="name" class="form-control" type="text" />
</div>
</div>
Basically i put the popover code in the row div, instead of the input div. Solved the problem.
Try this it will work, it's better create a procedure, if procedure is not possible you can use this script.
with param AS(
SELECT 1234 empid
FROM dual)
SELECT *
FROM Employees, param
WHERE EmployeeID = param.empid;
END;
This one works for me:
Another, and a bit better workaround which apparently works:
Eclipse
.Eclipse
, wait for workspace to load (it should).Eclipse
again.Source: Eclipse hangs while opening workspace after upgrading to GWT 2.0/Google app engine 1.2.8
From answer that was removed due to being written in Spanish:
All of the above fixes may not work in android studio. If you are using ANDROID STUDIO please use the following fix.
Use
xmlns: compat = "http://schemas.android.com/tools"
on the menu label instead of
xmlns: compat = "http://schemas.android.com/apk/res-auto"
I had a similar case, what worked for me was:
name.firstChild.childNodes[0].data
XML is supposed to be simple and it really is and I don't know why python's minidom did it so complicated... but it's how it's made
There are 10 events in ASP.NET page life cycle, and the sequence is:
Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.
Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010
@Html.LabelFor(model => model.SomekingStatus, "foo bar")
Once you write a generic FuncEqualityComparer you can use it everywhere.
peopleList2.Except(peopleList1, new FuncEqualityComparer<Person>((p, q) => p.ID == q.ID));
public class FuncEqualityComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> comparer;
private readonly Func<T, int> hash;
public FuncEqualityComparer(Func<T, T, bool> comparer)
{
this.comparer = comparer;
if (typeof(T).GetMethod(nameof(object.GetHashCode)).DeclaringType == typeof(object))
hash = (_) => 0;
else
hash = t => t.GetHashCode();
}
public bool Equals(T x, T y) => comparer(x, y);
public int GetHashCode(T obj) => hash(obj);
}
AFAIK there is no "double break" or similar construct in C++. The closest would be a goto
- which, while it has a bad connotation to its name, exists in the language for a reason - as long as it's used carefully and sparingly, it's a viable option.
In SQL without SELECT
you cannot result anything. Instead of IF-ELSE
block I prefer to use CASE
statement for this
SELECT CASE
WHEN EXISTS (SELECT 1
FROM tblGLUserAccess
WHERE GLUserName = 'xxxxxxxx') THEN 1
ELSE 2
END
I had this problem in InteliJ. I went to: Edit -> Configuration -> Deployment -> EditArtifact:
Then there where yellow problems, I just clicked on fix two times and it works. I hope this will help someone.
If a parameter is expected to have a specific property, you can document that property by providing an additional @param tag. For example, if an employee parameter is expected to have name and department properties, you can document it as follows:
/**
* Assign the project to a list of employees.
* @param {Object[]} employees - The employees who are responsible for the project.
* @param {string} employees[].name - The name of an employee.
* @param {string} employees[].department - The employee's department.
*/
function(employees) {
// ...
}
If a parameter is destructured without an explicit name, you can give the object an appropriate one and document its properties.
/**
* Assign the project to an employee.
* @param {Object} employee - The employee who is responsible for the project.
* @param {string} employee.name - The name of the employee.
* @param {string} employee.department - The employee's department.
*/
Project.prototype.assign = function({ name, department }) {
// ...
};
Source: JSDoc
Calling Exception.ToString()
gives you more information than just using the Exception.Message
property. However, even this still leaves out lots of information, including:
Data
collection property found on all exceptions.There are times when you want to capture this extra information. The code below handles the above scenarios. It also writes out the properties of the exceptions in a nice order. It's using C# 7 but should be very easy for you to convert to older versions if necessary. See also this related answer.
public static class ExceptionExtensions
{
public static string ToDetailedString(this Exception exception) =>
ToDetailedString(exception, ExceptionOptions.Default);
public static string ToDetailedString(this Exception exception, ExceptionOptions options)
{
if (exception == null)
{
throw new ArgumentNullException(nameof(exception));
}
var stringBuilder = new StringBuilder();
AppendValue(stringBuilder, "Type", exception.GetType().FullName, options);
foreach (PropertyInfo property in exception
.GetType()
.GetProperties()
.OrderByDescending(x => string.Equals(x.Name, nameof(exception.Message), StringComparison.Ordinal))
.ThenByDescending(x => string.Equals(x.Name, nameof(exception.Source), StringComparison.Ordinal))
.ThenBy(x => string.Equals(x.Name, nameof(exception.InnerException), StringComparison.Ordinal))
.ThenBy(x => string.Equals(x.Name, nameof(AggregateException.InnerExceptions), StringComparison.Ordinal)))
{
var value = property.GetValue(exception, null);
if (value == null && options.OmitNullProperties)
{
if (options.OmitNullProperties)
{
continue;
}
else
{
value = string.Empty;
}
}
AppendValue(stringBuilder, property.Name, value, options);
}
return stringBuilder.ToString().TrimEnd('\r', '\n');
}
private static void AppendCollection(
StringBuilder stringBuilder,
string propertyName,
IEnumerable collection,
ExceptionOptions options)
{
stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
var innerOptions = new ExceptionOptions(options, options.CurrentIndentLevel + 1);
var i = 0;
foreach (var item in collection)
{
var innerPropertyName = $"[{i}]";
if (item is Exception)
{
var innerException = (Exception)item;
AppendException(
stringBuilder,
innerPropertyName,
innerException,
innerOptions);
}
else
{
AppendValue(
stringBuilder,
innerPropertyName,
item,
innerOptions);
}
++i;
}
}
private static void AppendException(
StringBuilder stringBuilder,
string propertyName,
Exception exception,
ExceptionOptions options)
{
var innerExceptionString = ToDetailedString(
exception,
new ExceptionOptions(options, options.CurrentIndentLevel + 1));
stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
stringBuilder.AppendLine(innerExceptionString);
}
private static string IndentString(string value, ExceptionOptions options)
{
return value.Replace(Environment.NewLine, Environment.NewLine + options.Indent);
}
private static void AppendValue(
StringBuilder stringBuilder,
string propertyName,
object value,
ExceptionOptions options)
{
if (value is DictionaryEntry)
{
DictionaryEntry dictionaryEntry = (DictionaryEntry)value;
stringBuilder.AppendLine($"{options.Indent}{propertyName} = {dictionaryEntry.Key} : {dictionaryEntry.Value}");
}
else if (value is Exception)
{
var innerException = (Exception)value;
AppendException(
stringBuilder,
propertyName,
innerException,
options);
}
else if (value is IEnumerable && !(value is string))
{
var collection = (IEnumerable)value;
if (collection.GetEnumerator().MoveNext())
{
AppendCollection(
stringBuilder,
propertyName,
collection,
options);
}
}
else
{
stringBuilder.AppendLine($"{options.Indent}{propertyName} = {value}");
}
}
}
public struct ExceptionOptions
{
public static readonly ExceptionOptions Default = new ExceptionOptions()
{
CurrentIndentLevel = 0,
IndentSpaces = 4,
OmitNullProperties = true
};
internal ExceptionOptions(ExceptionOptions options, int currentIndent)
{
this.CurrentIndentLevel = currentIndent;
this.IndentSpaces = options.IndentSpaces;
this.OmitNullProperties = options.OmitNullProperties;
}
internal string Indent { get { return new string(' ', this.IndentSpaces * this.CurrentIndentLevel); } }
internal int CurrentIndentLevel { get; set; }
public int IndentSpaces { get; set; }
public bool OmitNullProperties { get; set; }
}
Most people will be using this code for logging. Consider using Serilog with my Serilog.Exceptions NuGet package which also logs all properties of an exception but does it faster and without reflection in the majority of cases. Serilog is a very advanced logging framework which is all the rage at the time of writing.
You can use the Ben.Demystifier NuGet package to get human readable stack traces for your exceptions or the serilog-enrichers-demystify NuGet package if you are using Serilog.
In addition to the accepted answer, I would like to add one info, that NuGet packages in Visual Studio 2017 are located in the project file itself. I.e., right click on the project -> edit, to find all package reference entries.
To get the currently logged in user:
System.getProperty("user.name");
To get the host name of the machine:
InetAddress.getLocalHost().getHostName();
To answer the last part of your question, the Java API says that getHostName() will return
the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.
I've written the tests that compare using regular expressions (as per other answers) against not using regular expressions. Tests done on a quad core OSX10.8 machine running Java 1.6
Interestingly using regular expressions turns out to be about 5-10 times slower than manually iterating over a string. Furthermore the isAlphanumeric2()
function is marginally faster than isAlphanumeric()
. One supports the case where extended Unicode numbers are allowed, and the other is for when only standard ASCII numbers are allowed.
public class QuickTest extends TestCase {
private final int reps = 1000000;
public void testRegexp() {
for(int i = 0; i < reps; i++)
("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
}
public void testIsAlphanumeric() {
for(int i = 0; i < reps; i++)
isAlphanumeric("ab4r3rgf"+i);
}
public void testIsAlphanumeric2() {
for(int i = 0; i < reps; i++)
isAlphanumeric2("ab4r3rgf"+i);
}
public boolean isAlphanumeric(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (!Character.isLetterOrDigit(c))
return false;
}
return true;
}
public boolean isAlphanumeric2(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
return false;
}
return true;
}
}
Concept:
To be very simple Type Safe like the meanings, it makes sure that type of the variable should be safe like
so it is all about the safety of the types of your storage in terms of variables.
Iterate through a copy of the list:
>>> a = ["a", "b", "c", "d", "e"]
>>> for item in a[:]:
print item
if item == "b":
a.remove(item)
a
b
c
d
e
>>> print a
['a', 'c', 'd', 'e']