You could do it like this:
String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));
which produces:
[123, 456, 789, 0]
The regex (?<=\G...)
matches an empty string that has the last match (\G
) followed by three characters (...
) before it ((?<= )
)
NOT SUPPORTED BY IE
More info here: Can I Use?
.container {_x000D_
overflow: hidden;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
.container img {_x000D_
object-fit: cover;_x000D_
width: 100%;_x000D_
min-height: 100%;_x000D_
}
_x000D_
<div class='container'>_x000D_
<img src='http://i.imgur.com/H9lpVkZ.jpg' />_x000D_
</div>
_x000D_
While both reducebykey and groupbykey will produce the same answer, the reduceByKey example works much better on a large dataset. That's because Spark knows it can combine output with a common key on each partition before shuffling the data.
On the other hand, when calling groupByKey - all the key-value pairs are shuffled around. This is a lot of unnessary data to being transferred over the network.
for more detailed check this below link
Integrated application pool mode
When an application pool is in Integrated mode, you can take advantage of the integrated request-processing architecture of IIS and ASP.NET. When a worker process in an application pool receives a request, the request passes through an ordered list of events. Each event calls the necessary native and managed modules to process portions of the request and to generate the response.
There are several benefits to running application pools in Integrated mode. First the request-processing models of IIS and ASP.NET are integrated into a unified process model. This model eliminates steps that were previously duplicated in IIS and ASP.NET, such as authentication. Additionally, Integrated mode enables the availability of managed features to all content types.
Classic application pool mode
When an application pool is in Classic mode, IIS 7.0 handles requests as in IIS 6.0 worker process isolation mode. ASP.NET requests first go through native processing steps in IIS and are then routed to Aspnet_isapi.dll for processing of managed code in the managed runtime. Finally, the request is routed back through IIS to send the response.
This separation of the IIS and ASP.NET request-processing models results in duplication of some processing steps, such as authentication and authorization. Additionally, managed code features, such as forms authentication, are only available to ASP.NET applications or applications for which you have script mapped all requests to be handled by aspnet_isapi.dll.
Be sure to test your existing applications for compatibility in Integrated mode before upgrading a production environment to IIS 7.0 and assigning applications to application pools in Integrated mode. You should only add an application to an application pool in Classic mode if the application fails to work in Integrated mode. For example, your application might rely on an authentication token passed from IIS to the managed runtime, and, due to the new architecture in IIS 7.0, the process breaks your application.
Taken from: What is the difference between DefaultAppPool and Classic .NET AppPool in IIS7?
Original source: Introduction to IIS Architecture
Terminal type:
Last login: Thu Dec 20 08:28:43 on console
~ ? sudo spctl --master-disable
Password:
~ ? spctl --status
assessments disabled
~ ?
System Preferences->Security & Privacy
You could also pass points to the function: Small example:
def test(points):
addpoint = raw_input ("type ""add"" to add a point")
if addpoint == "add":
points = points + 1
else:
print "asd"
return points;
if __name__ == '__main__':
points = 0
for i in range(10):
points = test(points)
print points
Try:
CREATE TABLE foo SELECT * FROM bar LIMIT 0
Or:
CREATE TABLE foo SELECT * FROM bar WHERE 1=0
Check out the MSDN Documentation for the Application.DoEvents
method.
Here is worked for me:
Subject: SomeSubject
From:Company B (me)
Reply-to:Company A
To:Company A's customers
if you do it from unix command (apart from PGAdmin) dont forget to pass the DB as a parameter. otherwise this extension will not be enabled when executing requests on this DB
psql -d -c "create EXTENSION pgcrypto;"
You can put title attribute to tag.I hope it will work.
<img src="smiley.gif" title="Smiley face" width="42" height="42">
That depends on our requirement. For windows users
We use strncpy whenever we don't want to copy entire string or we want to copy only n number of characters. But strcpy copies the entire string including terminating null character.
These links will help you more to know about strcpy and strncpy and where we can use.
I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.
Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.
In general, there should be one class per file. If you organise things that way, then when you search for a class, you know you only need to search for the file with that name.
The exception is when a class is best implemented using one or more small helper classes. Usually, the code is easiest to follow when those classes are present in the same file. For instance, you might need a small 'tuple' wrapper class to pass some data between method calls. Another example are 'task' classes implementing Runnable or Callable. They may be so small that they are best combined with the parent class creating and calling them.
if you want to run an update, delete, or insert statement, you should use the ExecuteNonQuery. ExecuteNonQuery returns the number of rows affected by the statement.
An alternative solution is to introduce a method to the file instance that would do the explicit conversion.
import types
def _write_str(self, ascii_str):
self.write(ascii_str.encode('ascii'))
source_file = open("myfile.bin", "wb")
source_file.write_str = types.MethodType(_write_str, source_file)
And then you can use it as source_file.write_str("Hello World")
.
You can also use react helmet
import React from "react";
import {Helmet} from "react-helmet";
class Application extends React.Component {
render () {
return (
<div className="application">
<Helmet>
<meta charSet="utf-8" />
<title>My Title</title>
<link rel="canonical" href="http://example.com/example" />
<script src="/path/to/resource.js" type="text/javascript" />
</Helmet>
...
</div>
);
}
};
Helmet takes plain HTML tags and outputs plain HTML tags. It's dead simple, and React beginner friendly.
First check if your vim installation has clipboard support.
vim --version
If clipboard support is installed you will see:
+clipboard
+X11
+xterm_clipboard
If clipboard support is not installed you will see:
-clipboard
-X11
-xterm_clipboard
To install clipboard support:
apt-get install vim-gnome
Once you have verified that clipboard support is installed do the following:
Above steps might get tedious if you have to repeatedly copy from vim to system clipboard and vice versa. You can create vim shortcuts so that when you press Ctrlc selected text will be copied to system clipboard. And when you press Ctrlp system clipboard text is copied to vim. To create shortcuts :
Open .vimrc file and add following text at the end of file:
nnoremap <C-c> "+y
vnoremap <C-c> "+y
nnoremap <C-p> "+p
vnoremap <C-p> "+p
Save and reload your .vimrc to apply the new changes.
Position your cursor to the first line you want to copy.
Press Shiftv to enter visual mode.
Press ? to select multiple lines
Press Ctrlc to copy the selected text to system clipboard.
Now you can copy the selected text to browser, text editor etc.
Press Ctrlp if you want to copy system clipboard text to vim.
Note: This is for ubuntu systems.
Here is a very handy and helpful information about Git Push: Git Push: Just the Tip
The most common use of git push is to push your local changes to your public upstream repository. Assuming that the upstream is a remote named "origin" (the default remote name if your repository is a clone) and the branch to be updated to/from is named "master" (the default branch name), this is done with: git push origin master
git push origin
will push changes from all local branches to matching branches the origin remote.
git push origin master
will push changes from the local master branch to the remote master branch.
git push origin master:staging
will push changes from the local master branch to the remote staging branch if it exists.
I disagree that you should be calling a method on your controller. You should be using a service for any actual functionality, and you should be defining directives for any functionality for scalability and modularity, as well as assigning a click event which contains a call to the service which you inject into your directive.
So, for instance, on your HTML...
<a class="btn" ng-remove-birthday="$index">Delete</a>
Then, create a directive...
angular.module('myApp').directive('ngRemoveBirthday', ['myService', function(myService){
return function(scope, element, attrs){
angular.element(element.bind('click', function(){
myService.removeBirthday(scope.$eval(attrs.ngRemoveBirthday), scope);
};
};
}])
Then in your service...
angular.module('myApp').factory('myService', [function(){
return {
removeBirthday: function(birthdayIndex, scope){
scope.bdays.splice(birthdayIndex);
scope.$apply();
}
};
}]);
When you write your code properly like this, you will make it very easy to write future changes without having to restructure your code. It's organized properly, and you're handling custom click events correctly by binding using custom directives.
For instance, if your client says, "hey, now let's make it call the server and make bread, and then popup a modal." You will be able to easily just go to the service itself without having to add or change any of the HTML, and/or controller method code. If you had just the one line on the controller, you'd eventually need to use a service, for extending the functionality to the heavier lifting the client is asking for.
Also, if you need another 'Delete' button elsewhere, you now have a directive attribute ('ng-remove-birthday') you can easily assign to any element on the page. This now makes it modular and reusable. This will come in handy when dealing with the HEAVY web components paradigm of Angular 2.0. There IS no controller in 2.0. :)
Happy Developing!!!
The two valid mains are int main()
and int main(int, char*[])
. Any thing else may or may not compile. If main
doesn't explicitly return a value, 0 is implicitly returned.
// max size constraint
CGSize maximumLabelSize = CGSizeMake(184, FLT_MAX)
// font
UIFont *font = [UIFont fontWithName:TRADE_GOTHIC_REGULAR size:20.0f];
// set paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
// dictionary of attributes
NSDictionary *attributes = @{NSFontAttributeName:font,
NSParagraphStyleAttributeName: paragraphStyle.copy};
CGRect textRect = [string boundingRectWithSize: maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGSize expectedLabelSize = CGSizeMake(ceil(textRect.size.width), ceil(textRect.size.height));
Rather than setting a flag, it could be more elegant to use JavaScript's Array.prototype.find
to find the matching item in the array. The loop will end as soon as a truthy value is returned from the callback, and the array value during that iteration will be the .find
call's return value:
function findXX(word) {
return someArray.find((item, i) => {
$('body').append('-> '+i+'<br />');
return item === word;
});
}
const someArray = new Array();
someArray[0] = 't5';
someArray[1] = 'z12';
someArray[2] = 'b88';
someArray[3] = 's55';
someArray[4] = 'e51';
someArray[5] = 'o322';
someArray[6] = 'i22';
someArray[7] = 'k954';
var test = findXX('o322');
console.log('found word:', test);
function findXX(word) {
return someArray.find((item, i) => {
$('body').append('-> ' + i + '<br />');
return item === word;
});
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY.
An example of this solution can be found at this answer: https://stackoverflow.com/a/62485644/1178478
I installed mysql use brew install mysql
mysqld --verbose --help | less
And it shows:
Look at the following:
echo "ls -l" | at 07:00
This code line executes "ls -l" at a specific time. This is an example of executing something (a command in my example) at a specific time. "at" is the command you were really looking for. You can read the specifications here:
http://manpages.ubuntu.com/manpages/precise/en/man1/at.1posix.html http://manpages.ubuntu.com/manpages/xenial/man1/at.1posix.html
Hope it helps!
If someone is looking to sub out more than a comma I'm a fan of:
"1,200".chars.grep(/\d/).join.to_i
dunno about performance but, it is more flexible than a gsub
, ie:
"1-200".chars.grep(/\d/).join.to_i
If you're willing to transmit some data and that you don't need to be secured (any public infos) you can use a CORS proxy, it's very easy, you'll not have to change anything in your code or in server side (especially of it's not your server like the Yahoo API or OpenWeather). I've used it to fetch JSON files with an XMLHttpRequest and it worked fine.
I'll add a bit to this old thread.
Usually you would use
$ echo "$FOO"
However, I've had problems even with this syntax. Consider the following script.
#!/bin/bash
curl_opts="-s --noproxy * -O"
curl $curl_opts "$1"
The *
needs to be passed verbatim to curl
, but the same problems will arise. The above example won't work (it will expand to filenames in the current directory) and neither will \*
. You also can't quote $curl_opts
because it will be recognized as a single (invalid) option to curl
.
curl: option -s --noproxy * -O: is unknown
curl: try 'curl --help' or 'curl --manual' for more information
Therefore I would recommend the use of the bash
variable $GLOBIGNORE
to prevent filename expansion altogether if applied to the global pattern, or use the set -f
built-in flag.
#!/bin/bash
GLOBIGNORE="*"
curl_opts="-s --noproxy * -O"
curl $curl_opts "$1" ## no filename expansion
Applying to your original example:
me$ FOO="BAR * BAR"
me$ echo $FOO
BAR file1 file2 file3 file4 BAR
me$ set -f
me$ echo $FOO
BAR * BAR
me$ set +f
me$ GLOBIGNORE=*
me$ echo $FOO
BAR * BAR
really interesting problem, haven't seen it yet. this code works fine for me. tested it in chrome and IE9
<html>
<head>
<style>
body{
background-image: url('img.jpg');
background-color: #6DB3F2;
}
</style>
</head>
<body>
</body>
</html>
It is privacy concern. It is recommended to disallow users to backup an app if it contains sensitive data. Having access to backup files (i.e. when android:allowBackup="true"
), it is possible to modify/read the content of an app even on a non-rooted device.
Solution - use android:allowBackup="false"
in the manifest file.
You can read this post to have more information: Hacking Android Apps Using Backup Techniques
All the answers here seem to forget about landscape possibilities. If you would like this to work when the device is rotated to a landscape view, then you will face problems.
The trick here is that although the view is aware of the orientation, the keyboard is not. This means in Landscape, the keyboards width is actually its height and visa versa.
To modify Apples recommended way of changing the content insets and get it support landscape orientation, I would recommend using the following:
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
CGSize keyboardSize = [[[notif userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
if (orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight ) {
CGSize origKeySize = keyboardSize;
keyboardSize.height = origKeySize.width;
keyboardSize.width = origKeySize.height;
}
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0);
scroller.contentInset = contentInsets;
scroller.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
CGRect rect = scroller.frame;
rect.size.height -= keyboardSize.height;
NSLog(@"Rect Size Height: %f", rect.size.height);
if (!CGRectContainsPoint(rect, activeField.frame.origin)) {
CGPoint point = CGPointMake(0, activeField.frame.origin.y - keyboardSize.height);
NSLog(@"Point Height: %f", point.y);
[scroller setContentOffset:point animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
The part to pay attention to here is the following:
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
CGSize keyboardSize = [[[notif userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
if (orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight ) {
CGSize origKeySize = keyboardSize;
keyboardSize.height = origKeySize.width;
keyboardSize.width = origKeySize.height;
}
What is does, is detects what orientation the device is in. If it is landscape, it will 'swap' the width and height values of the keyboardSize variable to ensure that the correct values are being used in each orientation.
Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.
Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;
This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79
.
I was using AngularJS and AngularStrap 2.3.7 and trying to catch the 'change'
event by listening to a <form>
element (not the input itself) and none of the answers here worked for me. I tried to do:
$(form).on('change change.dp dp.change changeDate' function () {...})
And nothing would fire. I ended up listening to the focus
and blur
events and setting a custom property before/after on the element itself:
// special hack to make bs-datepickers fire change events
// use timeout to make sure they all exist first
$timeout(function () {
$('input[bs-datepicker]').on('focus', function (e){
e.currentTarget.focusValue = e.currentTarget.value;
});
$('input[bs-datepicker]').on('blur', function (e){
if (e.currentTarget.focusValue !== e.currentTarget.value) {
var event = new Event('change', { bubbles: true });
e.currentTarget.dispatchEvent(event);
}
});
})
This basically manually checks the value before and after the focus
and blur
and dispatches a new 'change'
event. The { bubbles: true }
bit is what got the form to detect the change. If you have any datepicker elements inside of an ng-if
you'll need to wrap the listeners in a $timeout
to make sure the digest happens first so all of your datepicker elements exist.
Hope this helps someone!
It is very simple, just add a property:
public string Value {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
Finally in SQLalchemy1.2 version, this new implementation is added to use psycopg2.extras.execute_batch() instead of executemany when you initialize your engine with use_batch_mode=True like:
engine = create_engine(
"postgresql+psycopg2://scott:tiger@host/dbname",
use_batch_mode=True)
http://docs.sqlalchemy.org/en/latest/changelog/migration_12.html#change-4109
Then someone would have to use SQLalchmey won't bother to try different combinations of sqla and psycopg2 and direct SQL together..
Setting a min-width on child elements will also create a breakpoint. For example breaking every 3 elements,
flex-grow: 1;
min-width: 33%;
If there are 4 elements, this will have the 4th element wrap taking the full 100%. If there are 5 elements, the 4th and 5th elements will wrap and take each 50%.
Make sure to have parent element with,
flex-wrap: wrap
As per String literals:
String literals can be enclosed within single quotes (i.e.
'...'
) or double quotes (i.e."..."
). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings).The backslash character (i.e.
\
) is used to escape characters which otherwise will have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letterr
orR
. Such strings are called raw strings and use different rules for backslash escape sequences.In triple-quoted strings, unescaped newlines and quotes are allowed, except that the three unescaped quotes in a row terminate the string.
Unless an
r
orR
prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C.
So ideally you need to replace the line:
data = open("C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")
To any one of the following characters:
Using raw prefix and single quotes (i.e. '...'
):
data = open(r'C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener')
Using double quotes (i.e. "..."
) and escaping backslash character (i.e. \
):
data = open("C:\\Users\\miche\\Documents\\school\\jaar2\\MIK\\2.6\\vektis_agb_zorgverlener")
Using double quotes (i.e. "..."
) and forwardslash character (i.e. /
):
data = open("C:/Users/miche/Documents/school/jaar2/MIK/2.6/vektis_agb_zorgverlener")
Try to use flexbox model. It is easy and short to write.
Live Jsfiddle
CSS:
#wrapper {
display: flex;
border: 1px solid black;
}
#first {
border: 1px solid red;
}
#second {
border: 1px solid green;
}
default direction is row. So, it aligns next to each other inside the #wrapper. But it is not supported IE9 or less than that versions
If you want to do it with only 1 element, you can use the ::before and ::after pseudo elements for the same div instead of a wrapper.
See http://css-tricks.com/pseudo-element-roundup/
"Core Java" is Sun's term, used to refer to Java SE, the standard edition and a set of related technologies, like the Java VM, CORBA, et cetera. This is mostly to differentiate from, say, Java ME or Java EE.
Also note that they're talking about a set of libraries rather than the programming language. That is, the underlying way you write Java doesn't change, regardless of the libraries you're using.
First create table without auto_increment,
CREATE TABLE `members`(
`id` int(11) NOT NULL,
`memberid` VARCHAR( 30 ) NOT NULL ,
`Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`firstname` VARCHAR( 50 ) NULL ,
`lastname` VARCHAR( 50 ) NULL
PRIMARY KEY (memberid)
) ENGINE = MYISAM;
after set id as index,
ALTER TABLE `members` ADD INDEX(`id`);
after set id as auto_increment,
ALTER TABLE `members` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;
Or
CREATE TABLE IF NOT EXISTS `members` (
`id` int(11) NOT NULL,
`memberid` VARCHAR( 30 ) NOT NULL ,
`Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`firstname` VARCHAR( 50 ) NULL ,
`lastname` VARCHAR( 50 ) NULL,
PRIMARY KEY (`memberid`),
KEY `id` (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
I can recommend make pre-init of future index value, this is very usefull in a lot of case like multi work, some export e.t.c.
just create additional User_Seq
table:
with two fields: id Uniq index
and SeqVal nvarchar(1)
and create next SP, and generated ID value from this SP and put to new User row!
CREATE procedure [dbo].[User_NextValue]
as
begin
set NOCOUNT ON
declare @existingId int = (select isnull(max(UserId)+1, 0) from dbo.User)
insert into User_Seq (SeqVal) values ('a')
declare @NewSeqValue int = scope_identity()
if @existingId > @NewSeqValue
begin
set identity_insert User_Seq on
insert into User_Seq (SeqID) values (@existingId)
set @NewSeqValue = scope_identity()
end
delete from User_Seq WITH (READPAST)
return @NewSeqValue
end
I have a similar answer for asynchronous preloading images via JS. Loading them dynamically is the same as loading them normally. they will cache.
as for caching, you can't control the browser but you can set it via server. if you need to load a really fresh resource on demand, you can use the cache buster technique to force load a fresh resource.
Open Oracle SQLDeveloper
Right click on connection tab and select new connection
Enter HR_ORCL in connection name and HR for the username and password.
Specify localhost for your Hostname and enter ORCL for the SID.
Click Test.
The status of the connection Test Successfully.
The connection was not saved however click on Save button to save the connection. And then click on Connect button to connect your database.
The connection is saved and you see the connection list.
Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/
In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.
If you are using PHP Apache server, then you will need to add following in your .htaccess
file:
Header set Access-Control-Allow-Origin "*"
Answering my own question.
curl -X GET --basic --user username:password \
https://www.example.com/mobile/resource
curl -X DELETE --basic --user username:password \
https://www.example.com/mobile/resource
curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \
-d 'param2_name=param2_value' https://www.example.com/mobile/resource
POSTing a file and additional parameter
curl -X POST -F 'param_name=@/filepath/filename' \
-F 'extra_param_name=extra_param_value' --basic --user username:password \
https://www.example.com/mobile/resource
Update: 5/5/2015 For your MVC 5 project you need to set the Version to 5.0.0.0 in your /views/web.config
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</system.web.webPages.razor>
I have made a node module to read large file asynchronously text or JSON. Tested on large files.
var fs = require('fs')
, util = require('util')
, stream = require('stream')
, es = require('event-stream');
module.exports = FileReader;
function FileReader(){
}
FileReader.prototype.read = function(pathToFile, callback){
var returnTxt = '';
var s = fs.createReadStream(pathToFile)
.pipe(es.split())
.pipe(es.mapSync(function(line){
// pause the readstream
s.pause();
//console.log('reading line: '+line);
returnTxt += line;
// resume the readstream, possibly from a callback
s.resume();
})
.on('error', function(){
console.log('Error while reading file.');
})
.on('end', function(){
console.log('Read entire file.');
callback(returnTxt);
})
);
};
FileReader.prototype.readJSON = function(pathToFile, callback){
try{
this.read(pathToFile, function(txt){callback(JSON.parse(txt));});
}
catch(err){
throw new Error('json file is not valid! '+err.stack);
}
};
Just save the file as file-reader.js, and use it like this:
var FileReader = require('./file-reader');
var fileReader = new FileReader();
fileReader.readJSON(__dirname + '/largeFile.json', function(jsonObj){/*callback logic here*/});
To stop the pipeline of which ForEach-Object
is part just use the statement continue
inside the script block under ForEach-Object
. continue
behaves differently when you use it in foreach(...) {...}
and in ForEach-Object {...}
and this is why it's possible. If you want to carry on producing objects in the pipeline discarding some of the original objects, then the best way to do it is to filter out using Where-Object
.
Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.
Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.
Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.
On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)
The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.
Jake
So your myscript
output 3 lines, could look like:
myscript() { echo $'abc\ndef\nghi'; }
or
myscript() { local i; for i in abc def ghi ;do echo $i; done ;}
Ok this is a function, not a script (no need of path ./
), but output is same
myscript
abc
def
ghi
To check for result code, test function will become:
myscript() { local i;for i in abc def ghi ;do echo $i;done;return $((RANDOM%128));}
Your operation is correct:
RESULT=$(myscript)
About result code, you could add:
RCODE=$?
even in same line:
RESULT=$(myscript) RCODE=$?
Then
echo $RESULT
abc def ghi
echo "$RESULT"
abc
def
ghi
echo ${RESULT@Q}
$'abc\ndef\nghi'
printf "%q\n" "$RESULT"
$'abc\ndef\nghi'
but for showing variable definition, use declare -p
:
declare -p RESULT
declare -- RESULT="abc
def
ghi"
mapfile
Storing answer into myvar
variable:
mapfile -t myvar < <(myscript)
echo ${myvar[2]}
ghi
Showing $myvar
:
declare -p myvar
declare -a myvar=([0]="abc" [1]="def" [2]="ghi")
In case you have to check for result code, you could:
RESULT=$(myscript) RCODE=$?
mapfile -t myvar <<<"$RESULT"
read
in command group{ read firstline; read secondline; read thirdline;} < <(myscript)
echo $secondline
def
Showing variables:
declare -p firstline secondline thirdline
declare -- firstline="abc"
declare -- secondline="def"
declare -- thirdline="ghi"
I often use:
{ read foo;read foo total use free foo ;} < <(df -k /)
Then
declare -p use free total
declare -- use="843476"
declare -- free="582128"
declare -- total="1515376"
Same prepended step:
RESULT=$(myscript) RCODE=$?
{ read firstline; read secondline; read thirdline;} <<<"$RESULT"
declare -p firstline secondline thirdline RCODE
declare -- firstline="abc"
declare -- secondline="def"
declare -- thirdline="ghi"
declare -- RCODE="50"
please set dataType config property in your ajax call and give it another try!
another point is you are using ajax call setup configuration properties as string and it is wrong as reference site
$.ajax({
url : 'http://voicebunny.comeze.com/index.php',
type : 'GET',
data : {
'numberOfWords' : 10
},
dataType:'json',
success : function(data) {
alert('Data: '+data);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
I hope be helpful!
You need to do this via an extension as of the version 1.8.1.
Go to View ? Extensions. This will open Extensions Panel.
Type bookmark
to list all related extensions.
Install
I personally like "Numbered Bookmarks" - it is pretty simple and powerful.
Go to the line you need to create a bookmark.
Click Ctrl + Shift + [some number]
Ex: Ctrl + Shift + 2
Now you can jump to this line from anywhere by pressing Ctrl + number
Ex: Ctrl + 2
If you want to check if current date exist in between two dates in db: =>here the query will get the application list if employe's application from and to date is exist in todays date.
$list= (new LeaveApplication())
->whereDate('from','<=', $today)
->whereDate('to','>=', $today)
->get();
You can use Boost's lexical_cast
, which wraps this in a more generic interface.
lexical_cast<Target>(Source)
throws bad_lexical_cast
on failure.
You've started right - now you just need to fill the each student
structure in the array:
struct student
{
public int s_id;
public String s_name, c_name, dob;
}
class Program
{
static void Main(string[] args)
{
student[] arr = new student[4];
for(int i = 0; i < 4; i++)
{
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
arr[i].s_id = Int32.Parse(Console.ReadLine());
arr[i].s_name = Console.ReadLine();
arr[i].c_name = Console.ReadLine();
arr[i].s_dob = Console.ReadLine();
}
}
}
Now, just iterate once again and write these information to the console. I will let you do that, and I will let you try to make program to take any number of students, and not just 4.
If you're using node:
values.js
:export let someValues = {
value1: 0
}
Then just import it as needed at the top of each file it's used in (e.g., file.js
):
import { someValues } from './values'
console.log(someValues);
you cannot set this in javascript, you have to do this with html/css:
<style type="text/css" media="print">
@page { size: landscape; }
</style>
EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?
Do keep in mind that you don't need a stable sort if you compare all members. The 2.0 solution, as requested, can look like this:
public void SortList() {
MyList.Sort(delegate(MyClass a, MyClass b)
{
int xdiff = a.x.CompareTo(b.x);
if (xdiff != 0) return xdiff;
else return a.y.CompareTo(b.y);
});
}
Do note that this 2.0 solution is still preferable over the popular 3.5 Linq solution, it performs an in-place sort and does not have the O(n) storage requirement of the Linq approach. Unless you prefer the original List object to be untouched of course.
I have had great experiences with Idiorm and Paris. Idiorm is a small, simple ORM library. Paris is an equally simple Active Record implementation built on Idiorm. It's for PHP 5.2+ with PDO. It's perfect if you want something simple that you can just drop into an existing application.
You need to use one of the procedural languages such as PL/pgSQL not the SQL proc language. In PL/pgSQL you can use vars right in SQL statements. For single quotes you can use the quote literal function.
You can try with this:
function doParseCSVFile($filesArray)
{
if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) {
$strFilePath = $filesArray['frmUpload']['tmp_name'];
$strFileHandle = fopen($strFilePath,"r");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
do {
if ($line_of_text[0]) {
$strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
ExecuteQry($strInsertSql);
}
} while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);
} else {
return FALSE;
}
}
Provided you use the Angular-CLI to generate new projects, there's another way to make bootstrap accessible in Angular 2/4.
$ npm install --save bootstrap
. The --save
option will make bootstrap appear in the dependencies."styles"
array. The reference has to be the relative path to the bootstrap file downloaded with npm. In my case it's: "../node_modules/bootstrap/dist/css/bootstrap.min.css",
My example .angular-cli.json:
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "bootstrap-test"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css"
],
"scripts": [],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"lint": [
{
"project": "src/tsconfig.app.json"
},
{
"project": "src/tsconfig.spec.json"
},
{
"project": "e2e/tsconfig.e2e.json"
}
],
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}
Now bootstrap should be part of your default settings.
Material please go through this Link And also try this
ArrayList<Class> myArray= new ArrayList<Class>();
What Tyler Rinker says is correct:
AQ2 <- airquality
AQ2[is.na(AQ2)] <- 0
will do just this.
What you are originally doing is that you are taking from airquality
all those rows (cases) that are complete. So, all the cases that do not have any NA's in them, and keep only those.
the problem is you're trying to use regex features not supported by grep. namely, your \d
won't work. use this instead:
REGEX_DATE="^[[:digit:]]{2}[-/][[:digit:]]{2}[-/][[:digit:]]{4}$"
echo "$1" | grep -qE "${REGEX_DATE}"
echo $?
you need the -E
flag to get ERE in order to use {#}
style.
I also got same error, compiling with -D flag fixed it, Try this:
g++ -Dstd=c++11
In my multi-module project, the problem was that version of "com.android.support:appcompat-v7" in module A was "22.0.0", but in B - "22.2.0".
Solution: make sure
1. version of common libraries is same among modules.
2. each of modules compiles without any errors (try to build each of them from CLI).
You can change it directly in styles.xml file \app\src\main\res\values\styles.xml
This work on older versions, I was changing it in KitKat and come here.
If you are using the variables later, you'll find that stuff like path
actually will let accented characters through, but it won't actually match the browser path. For that you need to URIEncode them. So i.e. like this:
const encodedPath = encodeURI(myPath);
document.cookie = `use_pwa=true; domain=${location.host}; path=${encodedPath};`
So the "allowed" chars, might be more than what's in the spec. But you should stay within the spec, and use URI-encoded strings to be safe.
This is to make the variable of Optional type. Otherwise declared variables shows "undefined" if this variable is not used.
export interface ISearchResult {
title: string;
listTitle:string;
entityName?: string,
lookupName?:string,
lookupId?:string
}
Two other ways are strcpy(str, "");
and string[0] = 0
To really delete the Variable contents (in case you have dirty code which is not working properly with the snippets above :P ) use a loop like in the example below.
#include <string.h>
...
int i=0;
for(i=0;i<strlen(string);i++)
{
string[i] = 0;
}
In case you want to clear a dynamic allocated array of chars from the beginning, you may either use a combination of malloc() and memset() or - and this is way faster - calloc() which does the same thing as malloc but initializing the whole array with Null.
At last i want you to have your runtime in mind. All the way more, if you're handling huge arrays (6 digits and above) you should try to set the first value to Null instead of running memset() through the whole String.
It may look dirtier at first, but is way faster. You just need to pay more attention on your code ;)
I hope this was useful for anybody ;)
It's worth noting that in Firefox 3 and Safari, resizing an image by just changing the height and width doesn't look too bad. In other browsers it can look very noisy because it's using nearest-neighbor resampling. Of course, you're paying to serve a larger image, but that might not matter.
Your DemoApplication
class is in the com.ag.digital.demo.boot
package and your LoginBean
class is in the com.ag.digital.demo.bean
package. By default components (classes annotated with @Component
) are found if they are in the same package or a sub-package of your main application class DemoApplication
. This means that LoginBean
isn't being found so dependency injection fails.
There are a couple of ways to solve your problem:
LoginBean
into com.ag.digital.demo.boot
or a sub-package.scanBasePackages
attribute of @SpringBootApplication
that should be on DemoApplication
.A few of other things that aren't causing a problem, but are not quite right with the code you've posted:
@Service
is a specialisation of @Component
so you don't need both on LoginBean
@RestController
is a specialisation of @Component
so you don't need both on DemoRestController
DemoRestController
is an unusual place for @EnableAutoConfiguration
. That annotation is typically found on your main application class (DemoApplication
) either directly or via @SpringBootApplication
which is a combination of @ComponentScan
, @Configuration
, and @EnableAutoConfiguration
.I can't find any other built-in way of doing case-insensitive comparison: The python cook-book recipe uses lower().
However you have to be careful when using lower for comparisons because of the Turkish I problem. Unfortunately Python's handling for Turkish Is is not good. i is converted to I, but I is not converted to i. I is converted to i, but i is not converted to I.
If you have problems with accessing to the path, maybe you need to put this:
$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/cv/";
// Open the folder
$dir_handle = @opendir($root . $path) or die("Unable to open $path");
The proper way to do this is like this:
LIBS += -L/path/to -lpsapi
This way it will work on all platforms supported by Qt. The idea is that you have to separate the directory from the library name (without the extension and without any 'lib' prefix). Of course, if you are including a Windows specific lib, this really doesn't matter.
In case you want to store your lib files in the project directory, you can reference them with the $$_PRO_FILE_PWD_
variable, e.g.:
LIBS += -L"$$_PRO_FILE_PWD_/3rdparty/libs/" -lpsapi
<fieldset>_x000D_
<legend> YOUR TITLE </legend>_x000D_
_x000D_
_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, est et illum reformidans, at lorem propriae mei. Qui legere commodo mediocritatem no. Diam consetetur._x000D_
</p>_x000D_
</fieldset>
_x000D_
You can open a new popup window by following code:
var myWindow = window.open("", "newWindow", "width=500,height=700");
//window.open('url','name','specs');
Afterwards, you can add HTML using both myWindow.document.write();
or myWindow.document.body.innerHTML = "HTML";
What I will recommend is that first you create a new html file with any name. In this example I am using
newFile.html
And make sure to add all content in that file such as bootstrap cdn or jquery, means all the links and scripts. Then make a div with some id or use your body and give that a id
. in this example I have given id="mainBody"
to my newFile.html <body>
tag
<body id="mainBody">
Then open this file using
<script>
var myWindow = window.open("newFile.html", "newWindow", "width=500,height=700");
</script>
And add whatever you want to add in your body tag. using following code
<script>
var myWindow = window.open("newFile.html","newWindow","width=500,height=700");
myWindow.onload = function(){
let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
myWindow.document.getElementById('mainBody').innerHTML = content;
}
myWindow.window.close();
</script>
it is as simple as that.
You may have come here for advice on when to use persist and when to use merge. I think that it depends the situation: how likely is it that you need to create a new record and how hard is it to retrieve persisted data.
Let's presume you can use a natural key/identifier.
Data needs to be persisted, but once in a while a record exists and an update is called for. In this case you could try a persist and if it throws an EntityExistsException, you look it up and combine the data:
try { entityManager.persist(entity) }
catch(EntityExistsException exception) { /* retrieve and merge */ }
Persisted data needs to be updated, but once in a while there is no record for the data yet. In this case you look it up, and do a persist if the entity is missing:
entity = entityManager.find(key);
if (entity == null) { entityManager.persist(entity); }
else { /* merge */ }
If you don't have natural key/identifier, you'll have a harder time to figure out whether the entity exist or not, or how to look it up.
The merges can be dealt with in two ways, too:
I faced the similar problem, and solved by django admin site.
# models
class Document(models.Model):
docfile = models.FileField(upload_to='documents/Temp/%Y/%m/%d')
def doc_name(self):
return self.docfile.name.split('/')[-1] # only the name, not full path
# admin
from myapp.models import Document
class DocumentAdmin(admin.ModelAdmin):
list_display = ('doc_name',)
admin.site.register(Document, DocumentAdmin)
Take a look at antlr4. It will get you much farther along in creating a tree structure than regular expressions alone.
https://github.com/antlr/grammars-v4/tree/master/calculator (calculator.g4 contains the grammar you need)
In a nutshell, you define the grammar to parse an expression, use antlr to generate java code, and add callbacks to handle evaluation when the tree is being built.
Solution as proposed by Aziz would be:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children:children,
)
It would not be in the exact center because of padding:
padding: new EdgeInsets.all(25.0),
To make exactly center Column - at least in this case - you would need to remove padding.
I have an excellent answer.
#! /bin/bash
output=$(git diff origin/master..origin/develop | \
python -c '
# DO YOUR HACKING
variable1_to_be_exported="Yo Yo"
variable2_to_be_exported="Honey Singh"
… so on
magic=""
magic+="export onShell-var1=\""+str(variable1_to_be_exported)+"\"\n"
magic+="export onShell-var2=\""+str(variable2_to_be_exported)+"\""
print magic
'
)
eval "$output"
echo "$onShell-var1" // Output will be Yo Yo
echo "$onShell-var2" // Output will be Honey Singh
Mr Alex Tingle is correct about those processes and sub-process stuffs
How it can be achieved is like the above I have mentioned. Key Concept is :
printed
from python will be stored in the variable in the catching variable in bash
[output
]eval
print
output from python in a meaningful bash
commandseval
to execute it in bashAnd you can see your results
NOTE
Always execute the eval
using double quotes
or else bash
will mess up your \n
s and outputs will be strange
PS: I don't like bash but your have to use it
When making join(t)
function for both non-daemon thread and daemon thread, the main thread (or main process) should wait t
seconds, then can go further to work on its own process. During the t
seconds waiting time, both of the children threads should do what they can do, such as printing out some text. After the t
seconds, if non-daemon thread still didn't finish its job, and it still can finish it after the main process finishes its job, but for daemon thread, it just missed its opportunity window. However, it will eventually die after the python program exits. Please correct me if there is something wrong.
Or maybe you can use the setInterval function, to call a particular function, after the specified number of milliseconds. Just do a google for the setInterval prototype.I don't quite recollect it.
As you can see in the below source code, BeanUtils.copyProperties internally uses reflection and there's additional internal cache lookup steps as well which is going to add cost wrt performance
private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
@Nullable String... ignoreProperties) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
"] not assignable to Editable class [" + editable.getName() + "]");
}
actualEditable = editable;
}
**PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);**
List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
for (PropertyDescriptor targetPd : targetPds) {
Method writeMethod = targetPd.getWriteMethod();
if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null) {
Method readMethod = sourcePd.getReadMethod();
if (readMethod != null &&
ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
try {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
}
}
}
}
}
}
So it's better to use plain setters given the cost reflection
I have used Unlocker for years and really like it. It not only will identify programs and offer to unlock the folder\file, it will allow you to kill the processing that has the lock as well.
Additionally, it offers actions to do to the locked file in question such as deleting it.
Unlocker helps delete locked files with error messages including "cannot delete file," and "access is denied." Video tutorial available.
Some errors you might get that Unlocker can help with include:
- Cannot delete file: Access is denied.
- There has been a sharing violation.
- The source or destination file may be in use.
- The file is in use by another program or user.
- Make sure the disk is not full or write-protected and that the file is not currently in use.
You may be confusing Javascript arrays with PHP arrays. In PHP, arrays are very flexible. They can either be numerically indexed or associative, or even mixed.
array('Item 1', 'Item 2', 'Items 3') // numerically indexed array
array('first' => 'Item 1', 'second' => 'Item 2') // associative array
array('first' => 'Item 1', 'Item 2', 'third' => 'Item 3')
Other languages consider these two to be different things, Javascript being among them. An array in Javascript is always numerically indexed:
['Item 1', 'Item 2', 'Item 3'] // array (numerically indexed)
An "associative array", also called Hash or Map, technically an Object in Javascript*, works like this:
{ first : 'Item 1', second : 'Item 2' } // object (a.k.a. "associative array")
They're not interchangeable. If you need "array keys", you need to use an object. If you don't, you make an array.
*
Technically everything is an Object in Javascript, please put that aside for this argument. ;)
Open file
D:\wamp\www\yiistore2\common\config\params-local.php
Paste below code before return
Yii::setAlias('@anyname', realpath(dirname(__FILE__).'/../../'));
After inserting above code in params-local.php file your file should look like this.
Yii::setAlias('@anyname', realpath(dirname(__FILE__).'/../../'));
return [
];
Now to get path of your root (in my case its D:\wamp\www\yiistore2
) directory you can use below code in any php file.
echo Yii::getAlias('@anyname');
It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.
In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue"
to then end of the URL you are opening. :
http://www.somesite.com/send.php?variableName=someValue
or
http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue
This way, from PHP you can access this value as:
$phpVariableName = $_POST["variableName"];
for forms using POST method or:
$phpVariableName = $_GET["variableName"];
for forms using GET method or the append to url method I've mentioned above (querystring).
for tensorflow 2.1.0, following code works fine.
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
Late, but can be done by using Object.keys like,
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
function random_number($size = 5)
{
$random_number='';
$count=0;
while ($count < $size )
{
$random_digit = mt_rand(0, 9);
$random_number .= $random_digit;
$count++;
}
return $random_number;
}
Deleting and Recreating a project with same name is tricky. If you try to follow above suggested steps and try to create a project with same name as the one you just deleted, you will run into error like
'C:/xxxxxx/pom.xml' already exists in VFS
Here is what I found would work.
The relevant use cases for null pointers are
Dynamic casts. Casting a base-class pointer to a particular derived-class one (something you should again try to avoid, but may at times find necessary) always succeeds, but results in a null pointer if the derived class doesn't match. One way to check this is
Derived* derived_ptr = dynamic_cast<Derived*>(base_ptr);
if(derived_ptr != nullptr) { ... }
(or, preferrably, auto derived_ptr = ...
). Now, this is bad, because it leaves the (possibly invalid, i.e. null) derived pointer outside of the safety-guarding if
block's scope. This isn't necessary, as C++ allows you to introduce boolean-convertable variables inside an if
-condition:
if(auto derived_ptr = dynamic_cast<Derived*>(base_ptr)) { ... }
which is not only shorter and scope-safe, it's also much more clear in its intend: when you check for null in a separate if-condition, the reader wonders "ok, so derived_ptr
must not be null here... well, why would it be null?" Whereas the one-line version says very plainly "if you can safely cast base_ptr
to Derived*
, then use it for...".
The same works just as well for any other possible-failure operation that returns a pointer, though IMO you should generally avoid this: it's better to use something like boost::optional
as the "container" for results of possibly failing operations, rather than pointers.
So, if the main use case for null pointers should always be written in a variation of the implicit-cast-style, I'd say it's good for consistency reasons to always use this style, i.e. I'd advocate for if(ptr)
over if(ptr!=nullptr)
.
I'm afraid I have to end with an advert: the if(auto bla = ...)
syntax is actually just a slightly cumbersome approximation to the real solution to such problems: pattern matching. Why would you first force some action (like casting a pointer) and then consider that there might be a failure... I mean, it's ridiculous, isn't it? It's like, you have some foodstuff and want to make soup. You hand it to your assistant with the task to extract the juice, if it happens to be a soft vegetable. You don't first look it at it. When you have a potato, you still give it to your assistant but they slap it back in your face with a failure note. Ah, imperative programming!
Much better: consider right away all the cases you might encounter. Then act accordingly. Haskell:
makeSoupOf :: Foodstuff -> Liquid
makeSoupOf p@(Potato{..}) = mash (boil p) <> water
makeSoupOf vegetable
| isSoft vegetable = squeeze vegetable <> salt
makeSoupOf stuff = boil (throwIn (water<>salt) stuff)
Haskell also has special tools for when there is really a serious possibility of failure (as well as for a whole bunch of other stuff): monads. But this isn't the place for explaining those.
⟨/advert⟩
Well if you want to return your array from a function you must make sure that the values are not stored on the stack as they will be gone when you leave the function.
So either make your array static or allocate the memory (or pass it in but your initial attempt is with a void parameter). For your method I would define it like this:
int *gnabber(){
static int foo[] = {1,2,3}
return foo;
}
This is a fast and straightforward solution -
function chunkString (str, len) {_x000D_
const size = Math.ceil(str.length/len)_x000D_
const r = Array(size)_x000D_
let offset = 0_x000D_
_x000D_
for (let i = 0; i < size; i++) {_x000D_
r[i] = str.substr(offset, len)_x000D_
offset += len_x000D_
}_x000D_
_x000D_
return r_x000D_
}_x000D_
_x000D_
console.log(chunkString("helloworld", 3))_x000D_
// => [ "hel", "low", "orl", "d" ]_x000D_
_x000D_
// 10,000 char string_x000D_
const bigString = "helloworld".repeat(1000)_x000D_
console.time("perf")_x000D_
const result = chunkString(bigString, 3)_x000D_
console.timeEnd("perf")_x000D_
console.log(result)_x000D_
// => perf: 0.385 ms_x000D_
// => [ "hel", "low", "orl", "dhe", "llo", "wor", ... ]
_x000D_
Also, consider GForge.
When you run the official entrypoint (A.K.A. when you launch the container), it runs initdb
in $PGDATA
(/var/lib/postgresql/data
by default), and then it stores in that directory these 2 files:
postgresql.conf
with default manual settings.postgresql.auto.conf
with settings overriden automatically with ALTER SYSTEM
commands.The entrypoint also executes any /docker-entrypoint-initdb.d/*.{sh,sql}
files.
All this means you can supply a shell/SQL script in that folder that configures the server for the next boot (which will be immediately after the DB initialization, or the next times you boot the container).
Example:
conf.sql
file:
ALTER SYSTEM SET max_connections = 6;
ALTER SYSTEM RESET shared_buffers;
Dockerfile
file:
FROM posgres:9.6-alpine
COPY *.sql /docker-entrypoint-initdb.d/
RUN chmod a+r /docker-entrypoint-initdb.d/*
And then you will have to execute conf.sql
manually in already-existing databases. Since configuration is stored in the volume, it will survive rebuilds.
Another alternative is to pass -c
flag as many times as you wish:
docker container run -d postgres -c max_connections=6 -c log_lock_waits=on
This way you don't need to build a new image, and you don't need to care about already-existing or not databases; all will be affected.
Maybe what you want is just plain old predefined variables.
Consider trying
$_SERVER['REQUEST_URI'']
Or read more here.
The image needs to be in the same folder that your html page is in, then create a href to that folder with the picture name at the end. Example:
<img src="C:\users\home\pictures\picture.png"/>
If you're trying to query an Oracle database, you might want to use
select owner, table_name
from all_tab_columns
where column_name = 'ColName';
If you want to change query params without change the route. see below
example might help you:
current route is : /search
& Target route is(without reload page) : /search?query=love
submit(value: string) {
this.router.navigate( ['.'], { queryParams: { query: value } })
.then(_ => this.search(q));
}
search(keyword:any) {
//do some activity using }
please note : you can use this.router.navigate( ['search']
instead of this.router.navigate( ['.']
Print the PDF header (using header() function) like:
header("Content-type: application/pdf");
and then just echo the content of the PDF file you created (instead of writing it to disk).
Answer for "pre-Java-9" is below. As of Java 9, properties files are saved and loaded in UTF-8 by default, but falling back to ISO-8859-1 if an invalid UTF-8 byte sequence is detected. See the Java 9 release notes for details.
Properties files are ISO-8859-1 by definition - see the docs for the Properties class.
Spring has a replacement which can load with a specified encoding, using PropertiesFactoryBean
.
EDIT: As Laurence noted in the comments, Java 1.6 introduced overloads for load
and store
which take a Reader
/Writer
. This means you can create a reader for the file with whatever encoding you want, and pass it to load
. Unfortunately FileReader
still doesn't let you specify the encoding in the constructor (aargh) so you'll be stuck with chaining FileInputStream
and InputStreamReader
together. However, it'll work.
For example, to read a file using UTF-8:
Properties properties = new Properties();
InputStream inputStream = new FileInputStream("path/to/file");
try {
Reader reader = new InputStreamReader(inputStream, "UTF-8");
try {
properties.load(reader);
} finally {
reader.close();
}
} finally {
inputStream.close();
}
There may be a valid reason why you want to do this, but generating this kind of XML is generally best avoided. Why? Because it means that the XML elements of your map are dependent on the runtime contents of your map. And since XML is usually used as an external interface or interface layer this is not desirable. Let me explain.
The Xml Schema (xsd) defines the interface contract of your XML documents. In addition to being able to generate code from the XSD, JAXB can also generate the XML schema for you from the code. This allows you to restrict the data exchanged over the interface to the pre-agreed structures defined in the XSD.
In the default case for a Map<String, String>
, the generated XSD will restrict the map element to contain multiple entry elements each of which must contain one xs:string
key and one xs:string
value. That's a pretty clear interface contract.
What you describe is that you want the xml map to contain elements whose name will be determined by the content of the map at runtime. Then the generated XSD can only specify that the map must contain a list of elements whose type is unknown at compile time. This is something that you should generally avoid when defining an interface contract.
To achieve a strict contract in this case, you should use an enumerated type as the key of the map instead of a String. E.g.
public enum KeyType {
KEY, KEY2;
}
@XmlJavaTypeAdapter(MapAdapter.class)
Map<KeyType , String> mapProperty;
That way the keys which you want to become elements in XML are known at compile time so JAXB should be able to generate a schema that would restrict the elements of map to elements using one of the predefined keys KEY or KEY2.
On the other hand, if you wish to simplify the default generated structure
<map>
<entry>
<key>KEY</key>
<value>VALUE</value>
</entry>
<entry>
<key>KEY2</key>
<value>VALUE2</value>
</entry>
</map>
To something simpler like this
<map>
<item key="KEY" value="VALUE"/>
<item key="KEY2" value="VALUE2"/>
</map>
You can use a MapAdapter that converts the Map to an array of MapElements as follows:
class MapElements {
@XmlAttribute
public String key;
@XmlAttribute
public String value;
private MapElements() {
} //Required by JAXB
public MapElements(String key, String value) {
this.key = key;
this.value = value;
}
}
public class MapAdapter extends XmlAdapter<MapElements[], Map<String, String>> {
public MapAdapter() {
}
public MapElements[] marshal(Map<String, String> arg0) throws Exception {
MapElements[] mapElements = new MapElements[arg0.size()];
int i = 0;
for (Map.Entry<String, String> entry : arg0.entrySet())
mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());
return mapElements;
}
public Map<String, String> unmarshal(MapElements[] arg0) throws Exception {
Map<String, String> r = new TreeMap<String, String>();
for (MapElements mapelement : arg0)
r.put(mapelement.key, mapelement.value);
return r;
}
}
If that is a copy/paste from your script, you've permuted this line:
#!/usr/env/bin bash
There's no #!/usr/env/bin
, you meant #!/usr/bin/env
.
Probably the best way to check for errors in runtime API code is to define an assert style handler function and wrapper macro like this:
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) exit(code);
}
}
You can then wrap each API call with the gpuErrchk
macro, which will process the return status of the API call it wraps, for example:
gpuErrchk( cudaMalloc(&a_d, size*sizeof(int)) );
If there is an error in a call, a textual message describing the error and the file and line in your code where the error occurred will be emitted to stderr
and the application will exit. You could conceivably modify gpuAssert
to raise an exception rather than call exit()
in a more sophisticated application if it were required.
A second related question is how to check for errors in kernel launches, which can't be directly wrapped in a macro call like standard runtime API calls. For kernels, something like this:
kernel<<<1,1>>>(a);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaDeviceSynchronize() );
will firstly check for invalid launch argument, then force the host to wait until the kernel stops and checks for an execution error. The synchronisation can be eliminated if you have a subsequent blocking API call like this:
kernel<<<1,1>>>(a_d);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaMemcpy(a_h, a_d, size * sizeof(int), cudaMemcpyDeviceToHost) );
in which case the cudaMemcpy
call can return either errors which occurred during the kernel execution or those from the memory copy itself. This can be confusing for the beginner, and I would recommend using explicit synchronisation after a kernel launch during debugging to make it easier to understand where problems might be arising.
Note that when using CUDA Dynamic Parallelism, a very similar methodology can and should be applied to any usage of the CUDA runtime API in device kernels, as well as after any device kernel launches:
#include <assert.h>
#define cdpErrchk(ans) { cdpAssert((ans), __FILE__, __LINE__); }
__device__ void cdpAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
printf("GPU kernel assert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) assert(0);
}
}
In Dart 2 int.tryParse is available.
It returns null for invalid inputs instead of throwing. You can use it like this:
int val = int.tryParse(text) ?? defaultValue;
I usually use set_time_limit(30) within the main loop (so each loop iteration is limited to 30 seconds rather than the whole script).
I do this in multiple database update scripts, which routinely take several minutes to complete but less than a second for each iteration - keeping the 30 second limit means the script won't get stuck in an infinite loop if I am stupid enough to create one.
I must admit that my choice of 30 seconds for the limit is somewhat arbitrary - my scripts could actually get away with 2 seconds instead, but I feel more comfortable with 30 seconds given the actual application - of course you could use whatever value you feel is suitable.
Hope this helps!
If you want to include a "Title" field within it that can be selected with the <select>
HTML element, that too is possible
CODE SNIPPET
<div class="form-group">
<div class="input-group input-group-lg">
<div class="input-group-addon">
<select>
<option>Mr.</option>
<option>Mrs.</option>
<option>Dr</option>
</select>
</div>
<div class="input-group-addon">
<span class="fa fa-user"></span>
</div>
<input type="text" class="form-control" placeholder="Name...">
</div>
</div>
With borrowing from this post we know about choosing between the multithreading, multiprocessing, and async/asyncio
and their usage.
Python 3 has a new built-in library in order to make concurrency and parallelism: concurrent.futures
So I'll demonstrate through an experiment to run four tasks (i.e. .sleep()
method) by Threading-Pool
:
from concurrent.futures import ThreadPoolExecutor, as_completed
from time import sleep, time
def concurrent(max_worker):
futures = []
tic = time()
with ThreadPoolExecutor(max_workers=max_worker) as executor:
futures.append(executor.submit(sleep, 2)) # Two seconds sleep
futures.append(executor.submit(sleep, 1))
futures.append(executor.submit(sleep, 7))
futures.append(executor.submit(sleep, 3))
for future in as_completed(futures):
if future.result() is not None:
print(future.result())
print(f'Total elapsed time by {max_worker} workers:', time()-tic)
concurrent(5)
concurrent(4)
concurrent(3)
concurrent(2)
concurrent(1)
Output:
Total elapsed time by 5 workers: 7.007831811904907
Total elapsed time by 4 workers: 7.007944107055664
Total elapsed time by 3 workers: 7.003149509429932
Total elapsed time by 2 workers: 8.004627466201782
Total elapsed time by 1 workers: 13.013478994369507
[NOTE]:
multiprocessing
instead of threading
) you can change the ThreadPoolExecutor
to ProcessPoolExecutor
.This is just an add-on to the solution in case you want to compute not only unique values but other aggregate functions:
df.groupby(['group']).agg(['min','max','count','nunique'])
Hope you find it useful
Change the "MSBuild project build output verbosity" to "Detailed" or above. To do this, follow these steps:
In the tools/options page that appears, set the MSBuild project build output verbosity level to the appropriate setting depending on your version:
Check out the MSBuild messages. The ResolveAssemblyReferences
task, which is the task from which MSB3247 originates, should help you debug this particular issue.
My specific case was an incorrect reference to SqlServerCe. See below. I had two projects referencing two different versions of SqlServerCe. I went to the project with the older version, removed the reference, then added the correct reference.
Target ResolveAssemblyReferences:
Consider app.config remapping of assembly "System.Data.SqlServerCe, ..."
from Version "3.5.1.0" [H:\...\Debug\System.Data.SqlServerCe.dll]
to Version "9.0.242.0" [C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PublicAssemblies\System.Data.SqlServerCe.dll]
to solve conflict and get rid of warning.
C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets :
warning MSB3247: Found conflicts between different versions of the same dependent assembly.
You do not have to open each assembly to determine the versions of referenced assemblies.
I actually came across this same problem recently and ended up with a slightly different approach (I wasn't able to use background images). It does require a tiny bit of jQuery though to determine the orientation of the images (I' sure you could use plain JS instead though).
I wrote a blog post about it if you are interested in more explaination but the code is pretty simple:
HTML:
<ul class="cropped-images">
<li><img src="http://fredparke.com/sites/default/files/cat-portrait.jpg" /></li>
<li><img src="http://fredparke.com/sites/default/files/cat-landscape.jpg" /></li>
</ul>
CSS:
li {
width: 150px; // Or whatever you want.
height: 150px; // Or whatever you want.
overflow: hidden;
margin: 10px;
display: inline-block;
vertical-align: top;
}
li img {
max-width: 100%;
height: auto;
width: auto;
}
li img.landscape {
max-width: none;
max-height: 100%;
}
jQuery:
$( document ).ready(function() {
$('.cropped-images img').each(function() {
if ($(this).width() > $(this).height()) {
$(this).addClass('landscape');
}
});
});
If you set the interval in setInterval
too short, it may fire before the previous call to the function has been completed. I ran into this problem with a recent browser (Firefox 78). It resulted in the garbage collection not being able to free memory fast enough and built up a huge memory leak.
Using setTimeout(function, 500);
gave the garbage collection enough time to clean up and keep the memory stable over time.
Serg Hospodarets mentioned the problem in his answer and I fully agree with his remarks, but he didn't include the memory leak/garbage collection-problem. I experienced some freezing, too, but the memory usage ran up to 4 GB in no time for some minuscule task, which was the real bummer for me. Thus, I think this answer is still beneficial to others in my situation. I would have put it in a comment, but lack the reputation to do so. I hope you don't mind.
??!
is a trigraph that translates to |
. So it says:
!ErrorHasOccured() || HandleError();
which, due to short circuiting, is equivalent to:
if (ErrorHasOccured())
HandleError();
Guru of the Week (deals with C++ but relevant here), where I picked this up.
Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.
From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):
The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.
EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.
Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:
$result = mysql_query 'INSERT INTO table (
data
) VALUES (
\'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';
A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.
Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.
UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it
Here's how to do it with mysqli in procedural mode:
$result = mysqli_query ($db, 'INSERT INTO table (
data
) VALUES (
\'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');
The ideal way of doing it is with MySQLI/PDO prepared statements.
In your situation, git rebase
would also do the trick. Since you have no changes that master doesn't have, git will just fast-forward. If you are working with a rebase workflow, that might be more advisable, as you wouldn't end up with a merge commit if you mess up.
username@workstation:~/work$ git status
# On branch master
# Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.
# (use "git pull" to update your local branch)
#
nothing to commit, working directory clean
username@workstation:~/work$ git rebase
First, rewinding head to replay your work on top of it...
Fast-forwarded master to refs/remotes/origin/master.
# On branch master
nothing to commit, working directory clean
I had this problem with Django and it was because I had forgotten to start the virtual environment on the backend.
Regardless of following a naming convention that avoids using reserved words, Microsoft does add new reserved words. Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft's newly reserved words out of your client code. That editing can be a significant concern. It may cause your project to be prematurely retired....
Brackets can also be useful when you want to Replace All in a script. If your batch contains a variable named @String and a column named [String], you can rename the column to [NewString], without renaming @String to @NewString.
If you can get i["MyPhone"]
as a long
, you can use the long.ToString()
method to format it:
Convert.ToLong(i["MyPhone"]).ToString("###-###-####");
See the MSDN page on Numeric Format Strings.
Be careful to use long rather than int: int could overflow.
From the Bjarne Stroustrup C++0x FAQ:
__cplusplus
In C++11 the macro
__cplusplus
will be set to a value that differs from (is greater than) the current199711L
.
Although this isn't as helpful as one would like. gcc
(apparently for nearly 10 years) had this value set to 1
, ruling out one major compiler, until it was fixed when gcc 4.7.0 came out.
These are the C++ standards and what value you should be able to expect in __cplusplus
:
__cplusplus
is 1
.__cplusplus
is 199711L
.__cplusplus
is 201103L
.__cplusplus
is 201402L
.__cplusplus
is 201703L
.If the compiler might be an older gcc
, we need to resort to compiler specific hackery (look at a version macro, compare it to a table with implemented features) or use Boost.Config (which provides relevant macros). The advantage of this is that we actually can pick specific features of the new standard, and write a workaround if the feature is missing. This is often preferred over a wholesale solution, as some compilers will claim to implement C++11, but only offer a subset of the features.
The Stdcxx Wiki hosts a comprehensive matrix for compiler support of C++0x features (archive.org link) (if you dare to check for the features yourself).
Unfortunately, more finely-grained checking for features (e.g. individual library functions like std::copy_if
) can only be done in the build system of your application (run code with the feature, check if it compiled and produced correct results - autoconf
is the tool of choice if taking this route).
You need to specify the radix. There's an overload of Integer#parseInt()
which allows you to.
int foo = Integer.parseInt("1001", 2);
my work code. Returns utf8 xml enable empty namespace.
// override StringWriter
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
private string GenerateXmlResponse(Object obj)
{
Type t = obj.GetType();
var xml = "";
using (StringWriter sww = new Utf8StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
var ns = new XmlSerializerNamespaces();
// add empty namespace
ns.Add("", "");
XmlSerializer xsSubmit = new XmlSerializer(t);
xsSubmit.Serialize(writer, obj, ns);
xml = sww.ToString(); // Your XML
}
}
return xml;
}
Example returns response Yandex api payment Aviso url:
<?xml version="1.0" encoding="utf-8"?><paymentAvisoResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" performedDatetime="2017-09-01T16:22:08.9747654+07:00" code="0" shopId="54321" invoiceId="12345" orderSumAmount="10643" />
=AND(LEN($A1), COLUMN()<3, COUNTBLANK($E1:$H1))
=AND(LEN($A1), OR(COLUMN()<3, AND(COLUMN()>4, COUNTBLANK(A1))), COUNTBLANK($E1:$H1))
=$A:$H
.Results should be similar to the following.
¹ The COUNTBLANK function was introduced with Excel 2007. It will count both true blanks and zero-length strings left by formulas (e.g. ""
).
Here's my proposition:
for i in range(len(rserver.keys())):
salt = uuid.uuid4().hex
print(salt)
mdp_hash = rserver.get(rserver.keys()[i])
rserver.set(rserver.keys()[i], hashlib.sha256(salt.encode() + mdp_hash.encode()).hexdigest() + salt)
rsalt.set(rserver.keys()[i], salt)
I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site
package javasandbox;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {
private static String sURL;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws MalformedURLException, IOException {
sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
System.out.println(sURL);
URL url = new URL(sURL);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
//set http request headers
httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
httpCon.addRequestProperty("Connection", "keep-alive");
httpCon.addRequestProperty("Cache-Control", "max-age=0");
httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
//httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
HttpURLConnection.setFollowRedirects(false);
httpCon.setInstanceFollowRedirects(false);
httpCon.setDoOutput(true);
httpCon.setUseCaches(true);
httpCon.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
System.out.println(a.toString());
httpCon.disconnect();
}
}
I had the same problem. When I added Static content feaute for IIS, It works fine.
If, like me, you use Spyder IDE, you have to disable the interactive mode with :
plt.ioff()
(this command is automatically launched with the scientific startup)
If you want to enable it again, use :
plt.ion()
Well, I simply could not find this (for me) mythical "Use dynamic ports" option. I have post screenshots.
On a more constructive note, I believe that the port numbers are to be found in the solution file AND CRUCIALLY cross referenced against the IIS Express config file
C:\Users\<username>\Documents\IISExpress\config\applicationhost.config
I tried editing the port number in just the solution file but strange things happened. I propose (no time yet) that it needs a consistent edit across both the solution file and the config file.
Anyone looking for running jupyter as sudo, when jupyter installed with virtualenv (without sudo) - this worked for me:
First verify this is a PATH issue:
Check if the path returned by which jupyter
is covered by the sudo user:
sudo env | grep ^PATH
(As opposed to the current user: env | grep ^PATH
)
If its not covered - add a soft link from it to one of the covered paths. For ex:
sudo ln -s /home/user/venv/bin/jupyter /usr/local/bin
Now you sould be able to run:
sudo jupyter notebook
Found the solution from here
This gets the last second of the previous day:
DateAdd("s",-1,DateAdd("d",1,Today())
This returns the last second of the previous week:
=dateadd("d", -Weekday(Now), (DateAdd("s",-1,DateAdd("d",1,Today()))))
Another solutions are assign RangeIndex
or range
:
df.index = pd.RangeIndex(len(df.index))
df.index = range(len(df.index))
It is faster:
df = pd.DataFrame({'a':[8,7], 'c':[2,4]}, index=[7,8])
df = pd.concat([df]*10000)
print (df.head())
In [298]: %timeit df1 = df.reset_index(drop=True)
The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 105 µs per loop
In [299]: %timeit df.index = pd.RangeIndex(len(df.index))
The slowest run took 15.05 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.84 µs per loop
In [300]: %timeit df.index = range(len(df.index))
The slowest run took 7.10 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.2 µs per loop
As in API 26 getDeviceId()
is depreciated so you can use following code to cater API 26 and earlier versions
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String imei="";
if (android.os.Build.VERSION.SDK_INT >= 26) {
imei=telephonyManager.getImei();
}
else
{
imei=telephonyManager.getDeviceId();
}
Don't forget to add permission requests for READ_PHONE_STATE
to use the above code.
UPDATE: From Android 10 its is restricted for user apps to get non-resettable hardware identifiers like IMEI.
Because System.exit()
is just another method to the compiler. It doesn't read ahead and figure out that the whole program will quit at that point (the JVM quits). Your OS or shell can read the integer that is passed back in the System.exit()
method. It is standard for 0
to mean "program quit and everything went OK" and any other value to notify an error occurred. It is up to the developer to document these return values for any users.
return
on the other hand is a reserved key word that the compiler knows well.
return
returns a value and ends the current function's run moving back up the stack to the function that invoked it (if any). In your code above it returns void
as you have not supplied anything to return.
My experience when working with large & complicated XML files is that sometimes neither Elements nor Descendants seem to work in retrieving a specific Element (and I still do not know why).
In such cases, I found that a much safer option is to manually search for the Element, as described by the following MSDN post:
In short, you can create a GetElement function:
private XElement GetElement(XDocument doc,string elementName)
{
foreach (XNode node in doc.DescendantNodes())
{
if (node is XElement)
{
XElement element = (XElement)node;
if (element.Name.LocalName.Equals(elementName))
return element;
}
}
return null;
}
Which you can then call like this:
XElement element = GetElement(doc,"Band");
Note that this will return null if no matching element is found.
I wanted to throw this up for good measure. I think the way @micahtan posted is preferred.
typeof(MyProgram).Name
Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs
This method fills html forms inside Google Forms. Hope it helps someone using Swift.
var url = NSURL(string: urlstring)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)
You can also use Array.from
.
var m = "Hello world!";
console.log(Array.from(m))
_x000D_
This method has been introduced in ES6.
Ok, I know there is an accepted answer but… for more special cases you also could use this one:
array_map(function($n) { echo $n['filename']; echo $n['filepath'];},$array);
Or in a more un-complex way:
function printItem($n){
echo $n['filename'];
echo $n['filepath'];
}
array_map('printItem', $array);
This will allow you to manipulate the data in an easier way.
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
works in rails 4.1 and support symbols without quotes {:a => 'b'}
just add this to initializers folder:
class String
def to_hash_object
JSON.parse(self.gsub(/:([a-zA-z]+)/,'"\\1"').gsub('=>', ': ')).symbolize_keys
end
end
I have used Simple Hash map, linked list and Collections to sort a Map by values.
import java.util.*;
import java.util.Map.*;
public class Solution {
public static void main(String[] args) {
// create a simple hash map and insert some key-value pairs into it
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Python", 3);
map.put("C", 0);
map.put("JavaScript", 4);
map.put("C++", 1);
map.put("Golang", 5);
map.put("Java", 2);
// Create a linked list from the above map entries
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
// sort the linked list using Collections.sort()
Collections.sort(list, new Comparator<Entry<String, Integer>>(){
@Override
public int compare(Entry<String, Integer> m1, Entry<String, Integer> m2) {
return m1.getValue().compareTo(m2.getValue());
}
});
for(Entry<String, Integer> value: list) {
System.out.println(value);
}
}
}
The output is:
C=0
C++=1
Java=2
Python=3
JavaScript=4
Golang=5
You'll either need to modify the service, or wrap it inside a helper process: apart from session/drive access issues, persistent drive mappings are only restored on an interactive logon, which services typically don't perform.
The helper process approach can be pretty simple: just create a new service that maps the drive and starts the 'real' service. The only things that are not entirely trivial about this are:
The helper service will need to pass on all appropriate SCM commands (start/stop, etc.) to the real service. If the real service accepts custom SCM commands, remember to pass those on as well (I don't expect a service that considers UNC paths exotic to use such commands, though...)
Things may get a bit tricky credential-wise. If the real service runs under a normal user account, you can run the helper service under that account as well, and all should be OK as long as the account has appropriate access to the network share. If the real service will only work when run as LOCALSYSTEM or somesuch, things get more interesting, as it either won't be able to 'see' the network drive at all, or require some credential juggling to get things to work.
We can mute it in this way (device and simulator need different values):
Add the Name OS_ACTIVITY_MODE
and the Value ${DEBUG_ACTIVITY_MODE}
and check it (in Product -> Scheme -> Edit Scheme -> Run -> Arguments -> Environment).
Add User-Defined Setting DEBUG_ACTIVITY_MODE
, then add Any iOS Simulator SDK
for Debug
and set it's value to disable
(in Project -> Build settings -> + -> User-Defined Setting)
For excellent code-readability, Fest Assertions has nice support for asserting lists
So in this case, something like:
Assertions.assertThat(returnedComponents).containsExactly("One", "Two", "Three");
Or make the expected list to an array, but I prefer the above approach because it's more clear.
Assertions.assertThat(returnedComponents).containsExactly(argumentComponents.toArray());
Another possibility (esp. with multiple Oracle homes)
set ORACLE_SID=$SID
sqlplus /nolog
conn / as sysdba;
Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/
string[] allfiles = Directory.GetFiles("path/to/dir", "*.*", SearchOption.AllDirectories);
where *.*
is pattern to match files
If the Directory is also needed you can go like this:
foreach (var file in allfiles){
FileInfo info = new FileInfo(file);
// Do something with the Folder or just add them to a list via nameoflist.add();
}
None is a singleton object (meaning there is only one None), used in many places in the language and library to represent the absence of some other value.
For example:
if d
is a dictionary, d.get(k)
will return d[k]
if it exists, but None
if d
has no key k
.
Read this info from a great blog: http://python-history.blogspot.in/
Just my two cents : the best way (but probably not the quickest in the short term) would probably be for each developer to work on his own database instance (see rule #1 for database work).
Installing Oracle on a developer station has become a no brainer since Oracle Database 10g Express Edition.
i add ckEditor by adding DLL in toolBox.
html code:
<CKEditor:CKEditorControl ID="editor1" runat="server"
BasePath="ckeditor" ContentsCss="ckeditor/contents.css"
Height="250px"
TemplatesFiles="ckeditor/themes/default/theme.js" FilebrowserBrowseUrl="ckeditor/plugins/FileManager/index.html"
FilebrowserFlashBrowseUrl="ckeditor/plugins/FileManager/index.html" FilebrowserFlashUploadUrl="ckeditor/plugins/FileManager/index.html"
FilebrowserImageBrowseLinkUrl="ckeditor/plugins/FileManager/index.html" FilebrowserImageBrowseUrl="ckeditor/plugins/FileManager/index.html"
FilebrowserImageUploadUrl="ckeditor/plugins/FileManager/index.html"
FilebrowserUploadUrl="ckeditor/plugins/FileManager/index.html" BackColor="#FF0066"
DialogButtonsOrder="Rtl"
FontNames="B Yekan;B Yekan,tahoma;Arial/Arial, Helvetica, sans-serif; Comic Sans MS/Comic Sans MS, cursive; Courier New/Courier New, Courier, monospace; Georgia/Georgia, serif; Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif; Tahoma/Tahoma, Geneva, sans-serif; Times New Roman/Times New Roman, Times, serif; Trebuchet MS/Trebuchet MS, Helvetica, sans-serif; Verdana/Verdana, Geneva, sans-serif"
ResizeDir="Vertical" ResizeMinHeight="350" UIColor="#CACACA">dhd fdh</CKEditor:CKEditorControl>
for get data of it.
jquery:
var editor = $('textarea iframe html body').html();
alert(editor);
While React.js is a parent Javascript library for developing web applications.
While you use tags like <View>
, <Text>
very frequently in React-Native, React.js uses web html tags like <div>
<h1>
<h2>
, which are only synonyms in dictionary of web/mobile developments.
For React.js you need DOM for path rendering of html tags, while for mobile application: React-Native uses AppRegistry to register your app.
I hope this is an easy explanation for quick differences/similarities in React.js and React-Native.
for f, b in zip(foo, bar):
print(f, b)
zip
stops when the shorter of foo
or bar
stops.
In Python 3, zip
returns an iterator of tuples, like itertools.izip
in Python2. To get a list
of tuples, use list(zip(foo, bar))
. And to zip until both iterators are
exhausted, you would use
itertools.zip_longest.
In Python 2, zip
returns a list of tuples. This is fine when foo
and bar
are not massive. If they are both massive then forming zip(foo,bar)
is an unnecessarily massive
temporary variable, and should be replaced by itertools.izip
or
itertools.izip_longest
, which returns an iterator instead of a list.
import itertools
for f,b in itertools.izip(foo,bar):
print(f,b)
for f,b in itertools.izip_longest(foo,bar):
print(f,b)
izip
stops when either foo
or bar
is exhausted.
izip_longest
stops when both foo
and bar
are exhausted.
When the shorter iterator(s) are exhausted, izip_longest
yields a tuple with None
in the position corresponding to that iterator. You can also set a different fillvalue
besides None
if you wish. See here for the full story.
Note also that zip
and its zip
-like brethen can accept an arbitrary number of iterables as arguments. For example,
for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'],
['red', 'blue', 'green']):
print('{} {} {}'.format(num, color, cheese))
prints
1 red manchego
2 blue stilton
3 green brie
Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.
They can be removed using pod spec remove SPEC_NAME
then pod setup
It may help to do pod spec remove master
then pod setup
Yes strings must be quoted and in some cases like in applescript, quotes must be escaped
do JavaScript "document.querySelector('span[" & attrName & "=\"" & attrValue & "\"]').click();"
if (CollectionUtils.isNotEmpty(listName))
Is the same as:
if(listName != null && !listName.isEmpty())
In first approach listName
can be null and null pointer exception will not be thrown. In second approach you have to check for null manually. First approach is better because it requires less work from you. Using .size() != 0
is something unnecessary at all, also i learned that it is slower than using .isEmpty()
If you're looking for a solution that returns proper number or days between e.g. 11/30/2014 23:59
and 12/01/2014 00:01
here's solution using Joda Time.
private int getDayDifference(long past, long current) {
DateTime currentDate = new DateTime(current);
DateTime pastDate = new DateTime(past);
return currentDate.getDayOfYear() - pastDate.getDayOfYear();
}
This implementation will return 1
as a difference in days. Most of the solutions posted here calculate difference in milliseconds between two dates. It means that 0
would be returned because there's only 2 minutes difference between these two dates.
Both node-schedule and node-cron we can use to implement cron-based schedullers.
NOTE : for generating cron expressions , you can use this cron_maker
Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.
You could build it like this:
<?php
Schema::create('feeds', function($table) {
$table->increments('id');
$table->timestamps();
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->morphs('target');
});
Build the feed model like so:
<?php
class Feed extends Eloquent
{
protected $fillable = ['user_id', 'target_type', 'target_id'];
public function user()
{
return $this->belongsTo('User');
}
public function target()
{
return $this->morphTo();
}
}
Then keep it up to date with something like:
<?php
Vote::created(function(Vote $vote) {
$target_type = 'Vote';
$target_id = $vote->id;
$user_id = $vote->user_id;
Feed::create(compact('target_type', 'target_id', 'user_id'));
});
You could make the above much more generic/robust—this is just for demonstration purposes.
At this point, your feed items are really easy to retrieve all at once:
<?php
Feed::whereIn('user_id', $my_friend_ids)
->with('user', 'target')
->orderBy('created_at', 'desc')
->get();
Its Simple use this command:
git push -f origin master
and it will get your work done
The problem is that the path to GraphViz was not found by the pydot module as shown in the traceback:
'GraphViz\'s executables not found'
I solved this problem on my windows 7 machine by adding the GraphViz bin directory to my computer's PATH. Then restarting my python IDE to use the updated path.
Hint 1: You might want to study the Python code in the bisect module.
Hint 2: Slicing can be used for list insertion:
>>> s = ['a', 'b', 'd', 'e']
>>> s[2:2] = ['c']
>>> s
['a', 'b', 'c', 'd', 'e']
I got this error for my Linux Jenkins slave. I fixed it by changing from the node from "Known hosts file Verification Strategy" to "Non verifying Verification Strategy".
The issue isn't actually a syntax error, the Hive ParseException is just caused by a reserved keyword in Hive (in this case, end
).
The solution: use backticks around the offending column name:
CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
"dynamodb.column.mapping" = "cid:cid,end:end,category:category");
With the added backticks around end
, the query works as expected.
IF, HAVING, WHERE, SELECT, UNIQUEJOIN, JOIN, ON, TRANSFORM, MAP, REDUCE, TABLESAMPLE, CAST, FUNCTION, EXTENDED, CASE, WHEN, THEN, ELSE, END, DATABASE, CROSS
Source: This Hive ticket from the Facebook Phabricator tracker
You could use Array.prototype.every().(A polyfill is needed for IE < 9 and other old browsers.)
var array1 = [4,8,9,10];
var array2 = [4,8,9,10];
var is_same = (array1.length == array2.length) && array1.every(function(element, index) {
return element === array2[index];
});
The accepted answer above did not work for me, because it ordered the weeks by alphabetical order, not chronological order:
2012/1
2012/10
2012/11
...
2012/19
2012/2
Here's my solution to count and group by week:
SELECT CONCAT(YEAR(date), '/', WEEK(date)) AS week_name,
YEAR(date), WEEK(date), COUNT(*)
FROM column_name
GROUP BY week_name
ORDER BY YEAR(DATE) ASC, WEEK(date) ASC
Generates:
YEAR/WEEK YEAR WEEK COUNT
2011/51 2011 51 15
2011/52 2011 52 14
2012/1 2012 1 20
2012/2 2012 2 14
2012/3 2012 3 19
2012/4 2012 4 19
If you know in advance which fields to use to make the comparison, then other people gave right answers.
What you may be interested in is to sort your collection in case you don't know at compile-time which criteria to apply.
Imagine you have a program dealing with cities:
protected Set<City> cities;
(...)
Field temperatureField = City.class.getDeclaredField("temperature");
Field numberOfInhabitantsField = City.class.getDeclaredField("numberOfInhabitants");
Field rainfallField = City.class.getDeclaredField("rainfall");
program.showCitiesSortBy(temperatureField, numberOfInhabitantsField, rainfallField);
(...)
public void showCitiesSortBy(Field... fields) {
List<City> sortedCities = new ArrayList<City>(cities);
Collections.sort(sortedCities, new City.CityMultiComparator(fields));
for (City city : sortedCities) {
System.out.println(city.toString());
}
}
where you can replace hard-coded field names by field names deduced from a user request in your program.
In this example, City.CityMultiComparator<City>
is a static nested class of class City
implementing Comparator
:
public static class CityMultiComparator implements Comparator<City> {
protected List<Field> fields;
public CityMultiComparator(Field... orderedFields) {
fields = new ArrayList<Field>();
for (Field field : orderedFields) {
fields.add(field);
}
}
@Override
public int compare(City cityA, City cityB) {
Integer score = 0;
Boolean continueComparison = true;
Iterator itFields = fields.iterator();
while (itFields.hasNext() && continueComparison) {
Field field = itFields.next();
Integer currentScore = 0;
if (field.getName().equalsIgnoreCase("temperature")) {
currentScore = cityA.getTemperature().compareTo(cityB.getTemperature());
} else if (field.getName().equalsIgnoreCase("numberOfInhabitants")) {
currentScore = cityA.getNumberOfInhabitants().compareTo(cityB.getNumberOfInhabitants());
} else if (field.getName().equalsIgnoreCase("rainfall")) {
currentScore = cityA.getRainfall().compareTo(cityB.getRainfall());
}
if (currentScore != 0) {
continueComparison = false;
}
score = currentScore;
}
return score;
}
}
You may want to add an extra layer of precision, to specify, for each field, whether sorting should be ascendant or descendant. I guess a solution is to replace Field
objects by objects of a class you could call SortedField
, containing a Field
object, plus another field meaning ascendant or descendant.
It depends on nature of your data. The answer varies based on its size and data type. I saw a lot of SQL solutions based on ORDER BY
. I would like to suggest javascript alternatives.
In all answers, I don't see anyone mentioning pagination problem for your future table. Let's make it easier for you. If your table doesn't have pagination, it's more likely that a javascript solution makes everything neat and clean for you on the client side. If you think this table will explode after you put data in it, you have to think about pagination as well. (you have to go to first page every time when you change the sorting column)
Another aspect is the data type. If you use SQL you have to be careful about the type of your data and what kind of sorting suites for it. For example, if in one of your VARCHAR columns you store integer numbers, the sorting will not take their integer value into account: instead of 1, 2, 11, 22
you will get 1, 11, 2, 22
.
You can find jquery plugins or standalone javascript sortable tables on google. It worth mentioning that the <table>
in HTML5 has sortable
attribute, but apparently it's not implemented yet.
the diff
method returns the difference in milliseconds. Instantiating moment(diff)
isn't meaningful.
You can define a variable :
var dayInMilliseconds = 1000 * 60 * 60 * 24;
and then use it like so :
diff / dayInMilliseconds // --> 15
Edit
actually, this is built into the diff
method, dubes' answer is better
Here are a couple different methods...
Docker version 1.3 or newer supports the command exec
that behave similar to nsenter
. This command can run new process in already running container (container must have PID 1 process running already). You can run /bin/bash
to explore container state:
docker exec -t -i mycontainer /bin/bash
see Docker command line documentation
You can evaluate container filesystem this way:
# find ID of your running container:
docker ps
# create image (snapshot) from container filesystem
docker commit 12345678904b5 mysnapshot
# explore this filesystem using bash (for example)
docker run -t -i mysnapshot /bin/bash
This way, you can evaluate filesystem of the running container in the precise time moment. Container is still running, no future changes are included.
You can later delete snapshot using (filesystem of the running container is not affected!):
docker rmi mysnapshot
If you need continuous access, you can install sshd to your container and run the sshd daemon:
docker run -d -p 22 mysnapshot /usr/sbin/sshd -D
# you need to find out which port to connect:
docker ps
This way, you can run your app using ssh (connect and execute what you want).
Use nsenter
, see Why you don't need to run SSHd in your Docker containers
The short version is: with nsenter, you can get a shell into an existing container, even if that container doesn’t run SSH or any kind of special-purpose daemon
If you need direct access:
WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...
Using appendEncodePath()
could save you multiple lines than appendPath()
, the following code snippet builds up this url: http://api.openweathermap.org/data/2.5/forecast/daily?zip=94043
Uri.Builder urlBuilder = new Uri.Builder();
urlBuilder.scheme("http");
urlBuilder.authority("api.openweathermap.org");
urlBuilder.appendEncodedPath("data/2.5/forecast/daily");
urlBuilder.appendQueryParameter("zip", "94043,us");
URL url = new URL(urlBuilder.build().toString());
There is an stable release on the react-router-dom
(v5) with the fix for this issue.
How about a very simple method
+call your while loop in a function
- set your value inside (nonsense, but shows the example)
- return your value inside
+capture your value outside
+set outside
+display outside
#!/bin/bash
# set -e
# set -u
# No idea why you need this, not using here
foo=0
bar="hello"
if [[ "$bar" == "hello" ]]
then
foo=1
echo "Setting \$foo to $foo"
fi
echo "Variable \$foo after if statement: $foo"
lines="first line\nsecond line\nthird line"
function my_while_loop
{
echo -e $lines | while read line
do
if [[ "$line" == "second line" ]]
then
foo=2; return 2;
echo "Variable \$foo updated to $foo inside if inside while loop"
fi
echo -e $lines | while read line
do
if [[ "$line" == "second line" ]]
then
foo=2;
echo "Variable \$foo updated to $foo inside if inside while loop"
return 2;
fi
# Code below won't be executed since we returned from function in 'if' statement
# We aready reported the $foo var beint set to 2 anyway
echo "Value of \$foo in while loop body: $foo"
done
}
my_while_loop; foo="$?"
echo "Variable \$foo after while loop: $foo"
Output:
Setting $foo 1
Variable $foo after if statement: 1
Value of $foo in while loop body: 1
Variable $foo after while loop: 2
bash --version
GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
Copyright (C) 2007 Free Software Foundation, Inc.
these 2 are the same:
Print CAST(GETDATE() as Datetime2 (3) )
PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))
On SuSE, there are two different configuration files for PHP: one for Apache, and one for CLI (command line interface). In the /etc/php5/ directory, you will find an "apache2" directory and a "cli" directory. Each has a "php.ini" file. The files are for the same purpose (php configuration), but apply to the two different ways of running PHP. These files, among other things, load the modules PHP uses.
If your OS is similar, then these two files are probably not the same. Your Apache php.ini is probably loading the gearman module, while the cli php.ini isn't. When the module was installed (auto or manual), it probably only updated the Apache php.ini file.
You could simply copy the Apache php.ini file over into the cli directory to make the CLI environment exactly like the Apache environment.
Or, you could find the line that loads the gearman module in the Apache file and copy/paste just it to the CLI file.
I recently used Spring Security 3.0 for this (combined with Wicket btw), and am quite happy with it. Here's a good thorough tutorial and documentation. Also take a look at this tutorial which gives a good explanation of the hashing/salting/decoding setup for Spring Security 2.
Use the date function:
select date(timestamp_field) from table
From a character field representation to a date you can use:
select date(substring('2011/05/26 09:00:00' from 1 for 10));
Test code:
create table test_table (timestamp_field timestamp);
insert into test_table (timestamp_field) values(current_timestamp);
select timestamp_field, date(timestamp_field) from test_table;
Test result:
The size member function.
myList.size();
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
"div" tag can not be used above "tr" tag. Instead you can use "tbody" tag to do your work. If you are planning to give id attribute to div tag and doing some processing, same purpose you can achieve through "tbody" tag. Div and Table are both block level elements. so they can not be nested. For further information visit this page
For example:
<table>
<tbody class="green">
<tr>
<td>Data</td>
</tr>
</tbody>
<tbody class="blue">
<tr>
<td>Data</td>
</tr>
</tbody>
</table>
secondly, you can put "div" tag inside "td" tag.
<table>
<tr>
<td>
<div></div>
</td>
</tr>
</table>
Further questions are always welcome.
Use boolalpha
to print bool to string.
std::cout << std::boolalpha << b << endl;
std::cout << std::noboolalpha << b << endl;
A comment about Will's answer, you might want to replace HttpContext.Current.Response.End();
with HttpContext.Current.ApplicationInstance.CompleteRequest();
The reason is that Response.End()
throws a System.Threading.ThreadAbortException
. It aborts a thread. If you have an exception logger, it will be littered with ThreadAbortExceptions, which in this case is expected behavior.
Intuitively, sending a CSV file to the browser should not raise an exception.
See here for more Is Response.End() considered harmful?
If you start having to mentally count off the parameters in the signature and match them to the call, then it is time to refactor!
While the results vary in this case because the column names are numbers, another way I've used is data.frame(rbind(mytable))
. Using the example from @X.X:
> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)
> freq_t
gear
cyl 3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
> data.frame(rbind(freq_t))
X3 X4 X5
4 1 8 2
6 2 4 1
8 12 0 2
If the column names do not start with numbers, the X
won't get added to the front of them.
case 1-->9 8 7 6 5 4 3 2 1
case 2--> 50 10 8 25 ........
case 3--> 50 50 10 8 25.........
case 4--> 50 50 10 8 50 25.......
public void second element()
{
int a[10],i,max1,max2;
max1=a[0],max2=a[1];
for(i=1;i<a.length();i++)
{
if(a[i]>max1)
{
max2=max1;
max1=a[i];
}
else if(a[i]>max2 &&a[i]!=max1)
max2=a[i];
else if(max1==max2)
max2=a[i];
}
}
The second approach is right to execute JavaScript code after the page has finished loading - but you don't actually execute JavaScript code there, you inserted plain HTML.
The first thing works, but loads the JavaScript immediately and clears the page (so your tag will be there - but nothing else).
(Plus: language="javascript" has been deprecated for years, use type="text/javascript" instead!)
To get that working, you have to use the DOM manipulating methods included in JavaScript. Basically you'll need something like this:
var scriptElement=document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = filename;
document.head.appendChild(scriptElement);
Not to say other answers are not great for certain circumstances, but this is one snippet I always user from Google:
- (void)runSigninThenInvokeSelector:(SEL)signInDoneSel {
if (signInDoneSel) {
[self performSelector:signInDoneSel];
}
}
Yes, but you need to move the variable assignment into the query:
SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;
Test case:
CREATE TABLE user (`user` int, `group` int);
INSERT INTO user VALUES (123456, 5);
INSERT INTO user VALUES (111111, 5);
Result:
SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;
+--------+-------+
| user | group |
+--------+-------+
| 123456 | 5 |
| 111111 | 5 |
+--------+-------+
2 rows in set (0.00 sec)
Note that for SET
, either =
or :=
can be used as the assignment operator. However inside other statements, the assignment operator must be :=
and not =
because =
is treated as a comparison operator in non-SET statements.
UPDATE:
Further to comments below, you may also do the following:
SET @user := 123456;
SELECT `group` FROM user LIMIT 1 INTO @group;
SELECT * FROM user WHERE `group` = @group;
Change:
struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
delcare a variable with
no name. */
to:
struct timeval tvalBefore, tvalAfter;
It is less likely (IMO) to make this mistake if there is a single declaration per line:
struct timeval tvalBefore;
struct timeval tvalAfter;
It becomes more error prone when declaring pointers to types on a single line:
struct timeval* tvalBefore, tvalAfter;
tvalBefore
is a struct timeval*
but tvalAfter
is a struct timeval
.
The only subquery appears to be this - try adding a ROWNUM
limit to the where to be sure:
(SELECT C.I_WORKDATE
FROM T_COMPENSATION C
WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
AND C.I_EMPID = A.I_EMPID)
You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE
on the matched date.
For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.
SELECT
...
REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
' ',
'') AS WORKDATE,
...
INNER JOIN T_EMPLOYEE_MS E
...
LEFT OUTER JOIN T_COMPENSATION C
ON C.I_COMPENSATEDDATE = A.I_REQDATE
AND C.I_EMPID = A.I_EMPID
...
Add an id attribute to a html tag
<ul class="nav nav-tabs">
<li><a href="#aaa" data-toggle="tab" id="tab_aaa">AAA</a></li>
<li><a href="#bbb" data-toggle="tab" id="tab_bbb">BBB</a></li>
<li><a href="#ccc" data-toggle="tab" id="tab_ccc">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
<div class="tab-pane" id="aaa">...Content...</div>
<div class="tab-pane" id="bbb">...Content...</div>
<div class="tab-pane" id="ccc">...Content...</div>
</div>
Then using JQuery
$("#tab_aaa").tab('show');
You could possibly create a cookie if thats allowed in your requirment. If you choose to take the cookie route then the solution could be as follows. Also the benefit with cookie is after the user closes the Browser and Re-opens, if the cookie has not been deleted the value will be persisted.
Cookie *Create and Store a Cookie:*
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
The function which will return the specified cookie:
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Display a welcome message if the cookie is set
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{
alert("Welcome again " + username);
}
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{
setCookie("username",username,365);
}
}
}
The above solution is saving the value through cookies. Its a pretty standard way without storing the value on the server side.
Jquery
Set a value to the session storage.
Javascript:
$.sessionStorage( 'foo', {data:'bar'} );
Retrieve the value:
$.sessionStorage( 'foo', {data:'bar'} );
$.sessionStorage( 'foo' );Results:
{data:'bar'}
Local Storage Now lets take a look at Local storage. Lets say for example you have an array of variables that you are wanting to persist. You could do as follows:
var names=[];
names[0]=prompt("New name?");
localStorage['names']=JSON.stringify(names);
//...
var storedNames=JSON.parse(localStorage['names']);
Server Side Example using ASP.NET
Adding to Sesion
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;
// When retrieving an object from session state, cast it to // the appropriate type.
ArrayList stockPicks = (ArrayList)Session["StockPicks"];
// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;
I hope that answered your question.
This might work for you:
cat <<\! >names.txt
> alison
> barb
> charlie
> david
> !
OIFS=$IFS; IFS=$'\n'; NAMES=($(<names.txt)); IFS=$OIFS
echo "${NAMES[@]}"
alison barb charlie david
echo "${NAMES[0]}"
alison
for NAME in "${NAMES[@]}";do echo $NAME;done
alison
barb
charlie
david
Here is my solution for that issue:
in Activity A:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE)
{
if(resultCode == Activity.RESULT_OK)
{
tvTitle.setText(data.getExtras().getString("title", ""));
}
}
}
in Activity B:
@Override
public void onBackPressed()
{
setResult(Activity.RESULT_OK, getIntent());
super.onBackPressed();
}
activity b holds the fragment.
in fragment:
private void setText(String text)
{
Intent intent = new Intent();
intent.putExtra("title", text);
getActivity().setIntent(intent);
}
in that way the Intent Object "data" in activity A will get the string from the fragment