Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt");
to open a stream to this file.
Use the constructor that takes a File
and a boolean
FileOutputStream(File file, boolean append)
and set the boolean to true
. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.
Another bug in Java. I seldom find them, only my second in my 10 year career. This is my solution, as others have mentioned. I have nether used System.gc()
. But here, in my case, it is absolutely crucial. Weird? YES!
finally
{
try
{
in.close();
in = null;
out.flush();
out.close();
out = null;
System.gc();
}
catch (IOException e)
{
logger.error(e.getMessage());
e.printStackTrace();
}
}
new FileOutputStream(f)
will create a file in most cases, but unfortunately you will get a FileNotFoundException
if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
I other word there might be plenty of cases where you would get FileNotFoundException meaning "Could not create your file", but you would not be able to find the reason of why the file creation failed.
A solution is to remove any call to the File API and use the Files API instead as it provides much better error handling. Typically replace any new FileOutputStream(f)
with Files.newOutputStream(p)
.
In cases where you do need to use the File API (because you use an external interface using File for example), using Files.createFile(p)
is a good way to make sure your file is created properly and if not you would know why it didn't work. Some people commented above that this is redundant. It is true, but you get better error handling which might be necessary in some cases.
It's not a big issue but beginner level developers as like me, we things what kind of error is this and finally we weast huge time for solve it.
Actually if you delete the db and create the db once again and after try to create the collection then it's will be work properly.
? mongo
use dbName;
db.dropDatabase();
exit
This can be done with a switch statement as well. The order of the conditional is reversed but this really doesn't make a difference (and it's slightly simpler anyways).
switch(test) {
case A:
case B:
do other stuff;
break;
default:
do stuff;
}
I wanted to add some information to help understand the problem. Forms Authentication allows for storing user data either in a cookie, or in the query string of the URL. The method your site supports can be configured in the web.config file.
The SignOut method removes the forms-authentication ticket information from the cookie or the URL if CookiesSupported is false.
At the same time, they say:
One of the HttpCookieMode values that indicates whether the application is configured for cookieless forms authentication. The default is UseDeviceProfile.
Lastly, regarding UseDeviceProfile, they say:
If the CookieMode property is set to UseDeviceProfile, the CookiesSupported property will return true if the Browser for the current Request supports both cookies and redirecting with cookies; otherwise, the CookiesSupported property will return false.
Piecing this all together, depending on the user's browser, the default configuration may result in CookiesSupported being true, which means the SignOut method doesn't clear the ticket from the cookie. This seems counter-intuitive and I don't know why it works this way -- I would expect SignOut to actually sign the user out under any circumstances.
One way to make the SignOut work by itself is to change the cookie mode to "UseCookies" (i.e. cookies are required) in the web.config file:
<authentication mode="Forms">
<forms loginUrl="~/Account/SignIn" cookieless="UseCookies"/>
</authentication>
According to my tests, doing this makes SignOut work by itself at the cost of your site now requiring cookies to function properly.
I had this issue because a method I was trying to implement required a std::unique_ptr<Queue>(myQueue)
as a parameter, but the Queue
class is abstract. I solved that by using a QueuePtr(myQueue)
constructor like so:
using QueuePtr = std::unique_ptr<Queue>;
and used that in the parameter list instead. This fixes it because the initializer tries to create a copy of Queue
when you make a std::unique_ptr
of its type, which can't happen.
I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />
I'm targeting API 22, so don't need to explicitly ask for permissions.
I had a similar issue when trying to use the Experimental Instance of Visual Studio 2013. This was for a vsix project (Creating Snippets).
Solution was:
Right Click Project in Solution Explorer > Properties > Debug
Setting the Start Action to "Start external program"
and using the following path:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe
This option was set to "Start project"
which won't work for the application output type Class Library, which caused that same error.
Note: Yours may differ depending on how you installed VS.
oltp- mostly used for business transaction.used to collect business data.In sql we use insert,update and delete command for retrieving small source of data.like wise they are highly normalised.... OLTP Mostly used for maintaining the data integrity.
olap- mostly use for reporting,data mining and business analytic purpose. for the large or bulk data.deliberately it is de-normalised. it stores Historical data..
It's not supported just yet... If you want to use it you will have to install Babel.
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
$id = implode(',',$_POST['id']);
echo $id
you cannot echo an array because it will just print out Array. If you wanna print out an array use print_r
.
print_r($_POST['id']);
BigDecimal
isn't a primitive, so you cannot use the <
, >
operators. However, since it's a Comparable
, you can use the compareTo(BigDecimal)
to the same effect. E.g.:
public class Domain {
private BigDecimal unitPrice;
public boolean isCheaperThan(BigDecimal other) {
return unitPirce.compareTo(other.unitPrice) < 0;
}
// etc...
}
I had a problem with this too. It said wrong directory when it was correct. So I just created a local variable with the name of JAVA_HOME omitting the final /bin/java. It worked fine for me.
It's working with me :
echo Auth::guard('guard_name')->user()->id;
So why don't you simply use a key-value literal?
var params = {
'slide0001.html': 'Looking Ahead',
'slide0002.html': 'Forecase',
...
};
return params['slide0001.html']; // returns: Looking Ahead
tried all proposed solutions, all seem to have issues of their own.
If you actually look into the Orchestrator source, particularly the .start()
implementation you will see that if the last parameter is a function it will treat it as a callback.
I wrote this snippet for my own tasks:
gulp.task( 'task1', () => console.log(a) )
gulp.task( 'task2', () => console.log(a) )
gulp.task( 'task3', () => console.log(a) )
gulp.task( 'task4', () => console.log(a) )
gulp.task( 'task5', () => console.log(a) )
function runSequential( tasks ) {
if( !tasks || tasks.length <= 0 ) return;
const task = tasks[0];
gulp.start( task, () => {
console.log( `${task} finished` );
runSequential( tasks.slice(1) );
} );
}
gulp.task( "run-all", () => runSequential([ "task1", "task2", "task3", "task4", "task5" ));
a very common try_files line which can be applied on your condition is
location / {
try_files $uri $uri/ /test/index.html;
}
you probably understand the first part, location /
matches all locations, unless it's matched by a more specific location, like location /test
for example
The second part ( the try_files
) means when you receive a URI that's matched by this block try $uri
first, for example http://example.com/images/image.jpg
nginx will try to check if there's a file inside /images
called image.jpg
if found it will serve it first.
Second condition is $uri/
which means if you didn't find the first condition $uri
try the URI as a directory, for example http://example.com/images/
, ngixn will first check if a file called images
exists then it wont find it, then goes to second check $uri/
and see if there's a directory called images
exists then it will try serving it.
Side note: if you don't have autoindex on
you'll probably get a 403 forbidden error, because directory listing is forbidden by default.
EDIT: I forgot to mention that if you have
index
defined, nginx will try to check if the index exists inside this folder before trying directory listing.
Third condition /test/index.html
is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html
inside the folder test
and serve it if it exists.
If the third condition fails too, then nginx will serve the 404 error page.
Also there's something called named locations, like this
location @error {
}
You can call it with try_files
like this
try_files $uri $uri/ @error;
TIP: If you only have 1 condition you want to serve, like for example inside folder images
you only want to either serve the image or go to 404 error, you can write a line like this
location /images {
try_files $uri =404;
}
which means either serve the file or serve a 404 error, you can't use only $uri
by it self without =404
because you need to have a fallback option.
You can also choose which ever error code you want, like for example:
location /images {
try_files $uri =403;
}
This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..
The slickest method woud be to use LINQ:
var fileCount = (from file in Directory.EnumerateFiles(@"H:\iPod_Control\Music", "*.mp3", SearchOption.AllDirectories)
select file).Count();
Very easy no need create class extends LocationListener 1- Variable
private LocationManager mLocationManager;
private LocationListener mLocationListener;
private static double currentLat =0;
private static double currentLon =0;
2- onStartService()
@Override public void onStartService() {
addListenerLocation();
}
3- Method addListenerLocation()
private void addListenerLocation() {
mLocationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
currentLat = location.getLatitude();
currentLon = location.getLongitude();
Toast.makeText(getBaseContext(),currentLat+"-"+currentLon, Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(lastKnownLocation!=null){
currentLat = lastKnownLocation.getLatitude();
currentLon = lastKnownLocation.getLongitude();
}
}
@Override
public void onProviderDisabled(String provider) {
}
};
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 500, 10, mLocationListener);
}
4- onDestroy()
@Override
public void onDestroy() {
super.onDestroy();
mLocationManager.removeUpdates(mLocationListener);
}
Change table_name
and field
to match your table name and field in question:
UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE INSTR(field, 'foo') > 0;
100% working Concept to send email with attachment in php :
if (isset($_POST['submit'])) {
extract($_POST);
require_once('mail/class.phpmailer.php');
$subject = "$name Applied For - $position";
$email_message = "<div>Thanks for Applying ....</div> ";
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.companyname.com"; // SMTP server
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = "[email protected]"; // GMAIL username
$mail->Password = "mailPassword"; // GMAIL password
$mail->SetFrom('[email protected]', 'new application submitted');
$mail->AddReplyTo("[email protected]","First Last");
$mail->Subject = "your subject";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($email_message);
$address = '[email protected]';
$mail->AddAddress($address, "companyname");
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']); // attachment
if (!$mail->Send()) {
/* Error */
echo 'Message not Sent! Email at [email protected]';
} else {
/* Success */
echo 'Sent Successfully! <b> Check your Mail</b>';
}
}
I used this code for google smtp mail sending with Attachment....
Note: Download PHPMailer Library from here -> https://github.com/PHPMailer/PHPMailer
You can use pydash:
import pydash as _
_.get(example_dict, 'key1.key2', default='Default')
You can try importing them and then handle the ImportError if the module doesn't exist.
try:
import numpy
except ImportError:
print "numpy is not installed"
When I posted this question the version of JQuery that I was using didn't include an isArray
function. If it had have I would have probably just used it trusting that implementation to be the best browser independant way to perform this particular type check.
Since JQuery now does offer this function, I would always use it...
$.isArray(obj);
(as of version 1.6.2) It is still implemented using comparisons on strings in the form
toString.call(obj) === "[object Array]"
Ok, I think I was able to find a proper solution for that.
Now, instead of sending <Link/>
as prop to Document, I send <NextLink/>
which is a custom wrapper for the react-router Link. By doing that, I'm able to have the right arrow as part of the Link structure while still avoiding to have routing code inside Document object.
The updated code looks like follows:
//in NextLink.js
var React = require('react');
var Right = require('./Right');
var NextLink = React.createClass({
propTypes: {
link: React.PropTypes.node.isRequired
},
contextTypes: {
transitionTo: React.PropTypes.func.isRequired
},
_onClickRight: function() {
this.context.transitionTo(this.props.link.props.to);
},
render: function() {
return (
<div>
{this.props.link}
<Right onClick={this._onClickRight} />
</div>
);
}
});
module.exports = NextLink;
...
//in MasterPage.js
var sampleLink = <Link to="/sample">Go To Sample</Link>
var nextLink = <NextLink link={sampleLink} />
<Document next={nextLink} />
//in Document.js
...
var Document = React.createClass({
render: function() {
return (
...
<div>{this.props.next}</div>
...
);
}
});
...
P.S: If you are using the latest version of react-router you may need to use this.context.router.transitionTo
instead of this.context.transitionTo
. This code will work fine for react-router version 0.12.X.
You can give the tr an id and do it.
tr#element{
background-color: green;
cursor: pointer;
height: 30px;
}
tr#element:hover{
background-color: blue;
cursor: pointer;
}
<table width="400px">
<tr id="element">
<td></td>
</tr>
</table>
I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.
Main Class:-
String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n"
+ " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n"
+ " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n"
+ " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n"
+ " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n"
+ " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of getName is: " + itr.getName());
System.out.println("Val of getCity is: " + itr.getCity());
System.out.println("Val of getJob is: " + itr.getJob());
System.out.println("Val of getCars is: " + itr.getCars() + "\n");
}
POJO:
public class MyPojo {
private List<String> cars = new ArrayList<String>();
private String name;
private String job;
private String city;
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} }
RESULT:-
Val of getName is: John
Val of getCity is: Berlin
Val of getJob is: Teacher
Val of getCars is: [FIAT, Toyata]
Val of getName is: Mark
Val of getCity is: Oslo
Val of getJob is: Doctor
Val of getCars is: [VW, Toyata]
This information is available in the sys.version
string in the sys
module:
>>> import sys
Human readable:
>>> print(sys.version) # parentheses necessary in python 3.
2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]
For further processing, use sys.version_info
or sys.hexversion
:
>>> sys.version_info
(2, 5, 2, 'final', 0)
# or
>>> sys.hexversion
34014192
To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:
assert sys.version_info >= (2, 5)
This compares major and minor version information. Add micro (=0
, 1
, etc) and even releaselevel (='alpha'
,'final'
, etc) to the tuple as you like. Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out). Sometimes features go away in newer releases, being replaced by others.
I wound up writing my own command-line tool to take care of this. It's similar to cut
, except it knows what to do with quoted fields, etc. This tool, paired with @Jimothy's answer, allows me to get a headerless CSV from a remote MySQL server I have no filesystem access to onto my local machine with this command:
$ mysql -N -e "select people, places from things" | csvm -i '\t' -o ','
Bill,"Raleigh, NC"
You can do execute this command : rails g migration rename_{old_table_name}to{new_table_name}
after you edit the file and add this code in the method change
rename_table :{old_table_name}, :{new_table_name}
Also you can use ss utility to dump sockets statistics.
To dump summary:
ss -s
Total: 91 (kernel 0)
TCP: 18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0
Transport Total IP IPv6
* 0 - -
RAW 0 0 0
UDP 4 2 2
TCP 18 16 2
INET 22 18 4
FRAG 0 0 0
To display all sockets:
ss -a
To display UDP sockets:
ss -u -a
To display TCP sockets:
ss -t -a
Here you can read ss man: ss
I updated spring tool suits by going help
> check for update
.
Use the FROM_UNIXTIME()
function in MySQL
Remember that if you are using a framework that stores it in milliseconds (for example Java's timestamp) you have to divide by 1000 to obtain the right Unix time in seconds.
I found some elegant solution on MSDN
System.Console.Write('\uXXXX') //XXXX is hex Unicode for character
This simple program writes ? right on the screen.
using System;
public class Test
{
public static void Main()
{
Console.Write('\u2103'); //? character code
}
}
For those wanting to create a dynamic class just properties (i.e. POCO), and create a list of this class. Using the code provided later, this will create a dynamic class and create a list of this.
var properties = new List<DynamicTypeProperty>()
{
new DynamicTypeProperty("doubleProperty", typeof(double)),
new DynamicTypeProperty("stringProperty", typeof(string))
};
// create the new type
var dynamicType = DynamicType.CreateDynamicType(properties);
// create a list of the new type
var dynamicList = DynamicType.CreateDynamicList(dynamicType);
// get an action that will add to the list
var addAction = DynamicType.GetAddAction(dynamicList);
// call the action, with an object[] containing parameters in exact order added
addAction.Invoke(new object[] {1.1, "item1"});
addAction.Invoke(new object[] {2.1, "item2"});
addAction.Invoke(new object[] {3.1, "item3"});
Here are the classes that the previous code uses.
Note: You'll also need to reference the Microsoft.CodeAnalysis.CSharp library.
/// <summary>
/// A property name, and type used to generate a property in the dynamic class.
/// </summary>
public class DynamicTypeProperty
{
public DynamicTypeProperty(string name, Type type)
{
Name = name;
Type = type;
}
public string Name { get; set; }
public Type Type { get; set; }
}
public static class DynamicType
{
/// <summary>
/// Creates a list of the specified type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static IEnumerable<object> CreateDynamicList(Type type)
{
var listType = typeof(List<>);
var dynamicListType = listType.MakeGenericType(type);
return (IEnumerable<object>) Activator.CreateInstance(dynamicListType);
}
/// <summary>
/// creates an action which can be used to add items to the list
/// </summary>
/// <param name="listType"></param>
/// <returns></returns>
public static Action<object[]> GetAddAction(IEnumerable<object> list)
{
var listType = list.GetType();
var addMethod = listType.GetMethod("Add");
var itemType = listType.GenericTypeArguments[0];
var itemProperties = itemType.GetProperties();
var action = new Action<object[]>((values) =>
{
var item = Activator.CreateInstance(itemType);
for(var i = 0; i < values.Length; i++)
{
itemProperties[i].SetValue(item, values[i]);
}
addMethod.Invoke(list, new []{item});
});
return action;
}
/// <summary>
/// Creates a type based on the property/type values specified in the properties
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static Type CreateDynamicType(IEnumerable<DynamicTypeProperty> properties)
{
StringBuilder classCode = new StringBuilder();
// Generate the class code
classCode.AppendLine("using System;");
classCode.AppendLine("namespace Dexih {");
classCode.AppendLine("public class DynamicClass {");
foreach (var property in properties)
{
classCode.AppendLine($"public {property.Type.Name} {property.Name} {{get; set; }}");
}
classCode.AppendLine("}");
classCode.AppendLine("}");
var syntaxTree = CSharpSyntaxTree.ParseText(classCode.ToString());
var references = new MetadataReference[]
{
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(DictionaryBase).GetTypeInfo().Assembly.Location)
};
var compilation = CSharpCompilation.Create("DynamicClass" + Guid.NewGuid() + ".dll",
syntaxTrees: new[] {syntaxTree},
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
var result = compilation.Emit(ms);
if (!result.Success)
{
var failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
var message = new StringBuilder();
foreach (var diagnostic in failures)
{
message.AppendFormat("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
throw new Exception($"Invalid property definition: {message}.");
}
else
{
ms.Seek(0, SeekOrigin.Begin);
var assembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms);
var dynamicType = assembly.GetType("Dexih.DynamicClass");
return dynamicType;
}
}
}
}
OK. If you don't want to use the correct way ng-options
, you can add ng-selected
attribute with a condition check logic for the option
directive to to make the pre-select work.
<select ng-model="filterCondition.operator">
<option ng-selected="{{operator.value == filterCondition.operator}}"
ng-repeat="operator in operators"
value="{{operator.value}}">
{{operator.displayName}}
</option>
</select>
If you have libpq-dev installed and are still having this problem it is likely due to conflicting versions of OpenSSL's libssl and friends - the Ubuntu system version in /usr/lib (which libpq is built against) and a second version RVM installed in $HOME/.rvm/usr/lib (or /usr/local/rvm/usr/lib if it's a system install). You can verify this by temporarily renaming $HOME/.rvm/usr/lib and seeing if "gem install pg" works.
To solve the problem have rvm rebuild using the system OpenSSL libraries (you may need to manually remove libssl.* and libcrypto.* from the rvm/usr/lib dir):
rvm reinstall 1.9.3 --with-openssl-dir=/usr
This finally solved the problem for me on Ubunto 12.04.
A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:
if(!GlobalTestingBool)
{
try
{
SomeErrorProneMethod();
}
catch (...)
{
// ... Error handling ...
}
}
else
{
SomeErrorProneMethod();
}
I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.
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
Short version of Franci's answer:
for(Iterator<String> iter = json.keys();iter.hasNext();) {
String key = iter.next();
...
}
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Vibrate on"
android:textOff="Vibrate off"
android:onClick="onToggleClicked"/>
Within the Activity that hosts this layout, the following method handles the click event:
public void onToggleClicked(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
// Enable vibrate
} else {
// Disable vibrate
}
}
If using underscore or lodash, this is the simplest thing to do:
_.countBy(array);
Such that:
_.countBy([5, 5, 5, 2, 2, 2, 2, 2, 9, 4])
=> Object {2: 5, 4: 1, 5: 3, 9: 1}
As pointed out by others, you can then execute the _.keys()
and _.values()
functions on the result to get just the unique numbers, and their occurrences, respectively. But in my experience, the original object is much easier to deal with.
In most project types, your async
"up" and "down" will end at an async void
event handler or returning a Task
to your framework.
However, Console apps do not support this.
You can either just do a Wait
on the returned task:
static void Main()
{
MainAsync().Wait();
// or, if you want to avoid exceptions being wrapped into AggregateException:
// MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
...
}
or you can use your own context like the one I wrote:
static void Main()
{
AsyncContext.Run(() => MainAsync());
}
static async Task MainAsync()
{
...
}
More information for async
Console apps is on my blog.
The easy way and fast way to do this is:
three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]
Alternatively, you can use numpy sum:
from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])
Looks like you're trying to both inherit the groupId from the parent, and simultaneously specify the parent using an inherited groupId!
In the child pom, use something like this:
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.felipe</groupId>
<artifactId>tutorial_maven</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>tutorial_maven_jar</artifactId>
Using properties like ${project.groupId}
won't work there. If you specify the parent in this way, then you can inherit the groupId and version in the child pom. Hence, you only need to specify the artifactId in the child pom.
i have used following line of code & it works fine Thanks.... @Mithun Sasidharan **
SELECT DATE_FORMAT(column_name, '%d/%m/%Y') FROM tablename
**
It could be that there is a previous instance of the client still running and listening on port 5000.
I want to propose other one with using $.each:
We may to declare ajax function like:
function ajaxFn(someData) {
this.someData = someData;
var that = this;
return function () {
var promise = $.Deferred();
$.ajax({
method: "POST",
url: "url",
data: that.someData,
success: function(data) {
promise.resolve(data);
},
error: function(data) {
promise.reject(data);
}
})
return promise;
}
}
Part of code where we creating array of functions with ajax to send:
var arrayOfFn = [];
for (var i = 0; i < someDataArray.length; i++) {
var ajaxFnForArray = new ajaxFn(someDataArray[i]);
arrayOfFn.push(ajaxFnForArray);
}
And calling functions with sending ajax:
$.when(
$.each(arrayOfFn, function(index, value) {
value.call()
})
).then(function() {
alert("Cheer!");
}
)
df['year_month']=df.datetime_column.apply(lambda x: str(x)[:7])
This worked fine for me, didn't think pandas would interpret the resultant string date as date, but when i did the plot, it knew very well my agenda and the string year_month where ordered properly... gotta love pandas!
You might have set oracle not to start automatically. Goto Start and search for Services. Scroll down and look for OracleServiceORCL (or OracleServiceSID). Double click and change startup type to automatic if it is set as manual.
If you absolutely do not want to use code-behind, you can try conditional operator for this:
<%# ((int)Eval("Percentage") < 50) ? "0 %" : Eval("Percentage") %>
That is assuming field Percentage
contains integer.
Update: Version for VB.NET, just in case, provided by tomasofen:
<%# If(Eval("Status") < 50, "0 %", Eval("Percentage")) %>
I know this is an older post, but I spent a long time trying to find a solution. I came across a decent one using only ReportLab and PyPDF so I thought I'd share:
PdfFileReader()
, we'll call this inputPdfFileReader()
, we'll call this textPdfFileWriter()
, we'll call this output.mergePage(*text*.getPage(0))
for each page you want the text added to, then use output.addPage()
to add the modified pages to a new documentThis works well for simple text additions. See PyPDF's sample for watermarking a document.
Here is some code to answer the question below:
packet = StringIO.StringIO()
can = canvas.Canvas(packet, pagesize=letter)
<do something with canvas>
can.save()
packet.seek(0)
input = PdfFileReader(packet)
From here you can merge the pages of the input file with another document.
y <- mean(x, na.rm=TRUE)
sd(y)
for standard deviation var(y)
for variance.
Both derivations use n-1
in the denominator so they are based on sample data.
For the love of $DEITY please do not make a busy-wait sleep function. setTimeout
and setInterval
do everything you need.
var showHide = document.getElementById('showHide');_x000D_
setInterval(() => {_x000D_
showHide.style.visibility = "initial";_x000D_
setTimeout(() => {_x000D_
showHide.style.visibility = "hidden"_x000D_
}, 1000);_x000D_
;_x000D_
}, 2000);
_x000D_
<div id="showHide">Hello! Goodbye!</div>
_x000D_
Every two second interval hide text for one second. This shows how to use setInterval and setTimeout to show and hide text each second.
Select JoiningDate ,Dateadd (day , 30 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (month , 10 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (year , 10 , JoiningDate )
from Emp
Select DateAdd(Hour, 10 , JoiningDate )
from emp
Select dateadd (hour , 10 , getdate()), getdate()
Select dateadd (hour , 10 , joiningDate)
from Emp
Select DateAdd (Second , 120 , JoiningDate ) , JoiningDate
From EMP
I hope this complete example will help you.
This is the TaxiInfo class which holds information about a taxi ride:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
We also have a convenience model which holds a List of TaxiInfo(s):
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
The code for the view is as follows:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: [email protected]</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
This returns a the following view:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>
A visual tour:
The problem with your code seems to be the elseif-statement which should be else if
(Notice the space).
I rewrote and simplyfied the code to this:
$(document).ready(function () {
if (screen.width < 1024) {
$(".yourClass").hide();
}
else {
$(".yourClass").show();
}
});
for month
DateTime.Now.ToString("MM");
for day
DateTime.Now.ToString("dd");
for year
DateTime.Now.ToString("yyyy");
Wikipedia has this to say:
Additionally, such icon files can be either 16×16 or 32×32 pixels in size, and either 8-bit or 24-bit in color depth (note that GIF files have a limited, 256 color palette entries).
I think the best way is to use a 32x32 gif and test it with different browsers.
For anyone needs to change the options of the menu dynamically:
private Menu menu;
// ...
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
this.menu = menu;
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
// ...
private void hideOption(int id)
{
MenuItem item = menu.findItem(id);
item.setVisible(false);
}
private void showOption(int id)
{
MenuItem item = menu.findItem(id);
item.setVisible(true);
}
private void setOptionTitle(int id, String title)
{
MenuItem item = menu.findItem(id);
item.setTitle(title);
}
private void setOptionIcon(int id, int iconRes)
{
MenuItem item = menu.findItem(id);
item.setIcon(iconRes);
}
;with C as
(
select Rel.t2ID,
Rel.t1ID,
t1.Price,
row_number() over(partition by Rel.t2ID order by t1.Price desc) as rn
from @t1 as T1
inner join @relation as Rel
on T1.ID = Rel.t1ID
)
select T2.ID as T2ID,
T2.Name as T2Name,
T2.Orders,
T1.ID as T1ID,
T1.Name as T1Name,
T1Sum.Price
from @t2 as T2
inner join (
select C1.t2ID,
sum(C1.Price) as Price,
C2.t1ID
from C as C1
inner join C as C2
on C1.t2ID = C2.t2ID and
C2.rn = 1
group by C1.t2ID, C2.t1ID
) as T1Sum
on T2.ID = T1Sum.t2ID
inner join @t1 as T1
on T1.ID = T1Sum.t1ID
you can try with awk:
awk '/blah/{getline; print}' logfile
Sorry, but I don't think I see any correct answers in my opinion.
The TOP
x function shows the records in undefined order. From that definition follows that a BOTTOM
function can not be defined.
Independent of any index or sort order. When you do an ORDER BY y DESC
you get the rows with the highest y value first. If this is an autogenerated ID, it should show the records last added to the table, as suggested in the other answers. However:
TOP
functionThe correct answer should be that there is not, and cannot be, an equivalent to TOP
for getting the bottom rows.
If you call your classes tests Maven seems to run them automatically, at least they did for me. Rename the classes and Maven will just go through to verification without running them.
If your address1 = '123 Center St'
and address2 = 'Apt 3B'
then even if you combine and do a LIKE
, you cannot search on searchstring as 'Center St 3B'
. However, if your searchstring was 'Center St Apt'
, then you can do it using -
WHERE (address1 + ' ' + address2) LIKE '%searchstring%'
A very simple flex solution that does not assume fixed heights or changing position of elements.
HTML
<div class="container">
<header></header>
<main></main>
<footer></footer>
</div>
CSS
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1;
}
Browser Support
All major browsers, except IE11 and below.
Make sure to use Autoprefixer for appropriate prefixes.
.container {_x000D_
display: -webkit-box;_x000D_
display: -ms-flexbox;_x000D_
display: flex;_x000D_
-webkit-box-orient: vertical;_x000D_
-webkit-box-direction: normal;_x000D_
-ms-flex-direction: column;_x000D_
flex-direction: column;_x000D_
min-height: 100vh;_x000D_
}_x000D_
_x000D_
main {_x000D_
-webkit-box-flex: 1;_x000D_
-ms-flex: 1;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
/////////////////////////////////////////////_x000D_
_x000D_
body,_x000D_
html {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
header,_x000D_
main,_x000D_
footer {_x000D_
margin: 0;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
header,_x000D_
footer {_x000D_
min-height: 80px; _x000D_
}_x000D_
_x000D_
header {_x000D_
background-color: #ccc;_x000D_
}_x000D_
_x000D_
main {_x000D_
background-color: #f4f4f4;_x000D_
}_x000D_
_x000D_
footer {_x000D_
background-color: orange;_x000D_
}
_x000D_
<div class="container">_x000D_
<header></header>_x000D_
<main></main>_x000D_
<footer></footer>_x000D_
</div>
_x000D_
I would suggest you check out the various tutorials that are coming out lately. My current fav is:
Hope this helps.
You can use git revert <commit-id>
.
And for getting the commit ID, just use git log
.
Personally I like the & function for this
Assuming that you are using cells A1 and A2 for John Smith
=left(a1,1) & b1
If you want to add text between, for example a period
=left(a1,1) & "." & b1
Apache Commons has tuple and triple for this:
ImmutablePair<L,R>
An immutable pair consisting of two Object
elements.ImmutableTriple<L,M,R>
An immutable triple consisting of
three Object elements.MutablePair<L,R>
A mutable pair consisting of
two Object elements.MutableTriple<L,M,R>
A mutable triple
consisting of three Object elements.Pair<L,R>
A pair consisting of
two elements.Triple<L,M,R>
A triple consisting of three elements.What you are trying to achieve should be done in the web browser because javascript simply doesn't work with html email design. The various email clients that are out there e.g. gmail, outlook, yahoo strip scripts put of the code for security reasons.
It is best to just use HTML and CSS to style your emails. Maybe you could have a call to action (cta) in your html email that sends the user to a web page with your expanding and collapsing content feature.
aspirinemaga, just replace:
$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);
for it:
$this->db->set('time', 'NOW() + INTERVAL 1 DAY', FALSE);
$this->db->insert('mytable', $data);
git log --pretty=oneline tagA...tagB
(i.e. three dots)
If you just wanted commits reachable from tagB but not tagA:
git log --pretty=oneline tagA..tagB
(i.e. two dots)
or
git log --pretty=oneline ^tagA tagB
Just wrap floated elements in a <div>
and give it this CSS:
.wrapper {
display: table;
margin: auto;
}
By default .
(any character) does not match newline characters.
This means you can simply match zero or more of any character then append the end tag.
Find: <li><a href="#">.*
Replace: $0</a>
.line {_x000D_
width: 53px;_x000D_
height: 0;_x000D_
border: 1px solid #C4C4C4;_x000D_
margin: 3px;_x000D_
display:inline-block;_x000D_
}
_x000D_
<html>_x000D_
<body>_x000D_
<div class="line"></div>_x000D_
<div style="display:inline-block;">OR</div>_x000D_
<div class="line"></div>_x000D_
</body>_x000D_
</html>
_x000D_
Here is a version of the currently accepted answer (from @Trevor) with key instead of keyCode:
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
I like to place all my sql connections in using
statements. I think they look cleaner, and they clean up after themselves when your done with them. I also recommend parameterizing every query, not only is it much safer but it is easier to maintain if you need to come back and make changes.
// create/open connection
using (SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI")
{
try
{
conn.Open();
// initialize command
using (SqlCommand cmd = conn.CreateCommand())
{
// generate query with parameters
with cmd
{
.CommandType = CommandType.Text;
.CommandText = "insert into time(project,iteration) values(@name, @iteration)";
.Parameters.Add(new SqlParameter("@name", this.name1.SelectedValue));
.Parameters.Add(new SqlParameter("@iteration", this.iteration.SelectedValue));
.ExecuteNonQuery();
}
}
}
catch (Exception)
{
//throw;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
{
conn.Close;
}
}
}
This is how I would do it
myArray.splice( myArray.indexOf('bar') , 1)
While @jackofallcode answer is correct, it can be written in one line:
((RelativeLayout.LayoutParams) viewToLayout.getLayoutParams()).addRule(RelativeLayout.BELOW, R.id.below_id);
Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:
version: '2'
services:
mysql:
container_name: mysql
image: mysql:latest
restart: always
environment:
- MYSQL_ROOT_PASSWORD=root
ports:
- "3306:3306"
networks:
vpcbr:
ipv4_address: 10.5.0.5
apigw-tomcat:
container_name: apigw-tomcat
build: tomcat/.
ports:
- "8080:8080"
- "8009:8009"
networks:
vpcbr:
ipv4_address: 10.5.0.6
depends_on:
- mysql
networks:
vpcbr:
driver: bridge
ipam:
config:
- subnet: 10.5.0.0/16
gateway: 10.5.0.1
If you do not want to include the brackets in the match, here's the regex: (?<=\[).*?(?=\])
The .
matches any character except for line terminators. The ?=
is a positive lookahead. A positive lookahead finds a string when a certain string comes after it. The ?<=
is a positive lookbehind. A positive lookbehind finds a string when a certain string precedes it. To quote this,
Look ahead positive (?=)
Find expression A where expression B follows:
A(?=B)
Look behind positive (?<=)
Find expression A where expression B precedes:
(?<=B)A
If your regex engine does not support lookaheads and lookbehinds, then you can use the regex \[(.*?)\]
to capture the innards of the brackets in a group and then you can manipulate the group as necessary.
The parentheses capture the characters in a group. The .*?
gets all of the characters between the brackets (except for line terminators, unless you have the s
flag enabled) in a way that is not greedy.
There aren't trees built in, but you can easily construct one by subclassing a Node type from List and writing the traversal methods. If you do this, I've found bisect useful.
There are also many implementations on PyPi that you can browse.
If I remember correctly, the Python standard lib doesn't include tree data structures for the same reason that the .NET base class library doesn't: locality of memory is reduced, resulting in more cache misses. On modern processors it's usually faster to just bring a large chunk of memory into the cache, and "pointer rich" data structures negate the benefit.
None of the above solutions seem to work if the width/height is less than the line resolution of quality you select. For example, the following doesn't work for me in Chrome:
<iframe width="720" height="480" src="//youtube.com/embed/hUezoHa1ZF4?autoplay=true&rel=0&vq=hd720" frameborder="0" allowfullscreen></iframe>
I want to show the high quality video, but not use up 1280 x 720 pixels on the webpage.
When I go to youtube itself, playing 720p video in a 720x480 window looks better than 480p at the same size. I want to play 720p in a 720x480 window (downsampled better quality). There is no good solution yet afaik.
String pooling
String pooling (sometimes also called as string canonicalisation) is a process of replacing several String objects with equal value but different identity with a single shared String object. You can achieve this goal by keeping your own Map (with possibly soft or weak references depending on your requirements) and using map values as canonicalised values. Or you can use String.intern() method which is provided to you by JDK.
At times of Java 6 using String.intern() was forbidden by many standards due to a high possibility to get an OutOfMemoryException if pooling went out of control. Oracle Java 7 implementation of string pooling was changed considerably. You can look for details in http://bugs.sun.com/view_bug.do?bug_id=6962931 and http://bugs.sun.com/view_bug.do?bug_id=6962930.
String.intern() in Java 6
In those good old days all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool. Besides explicitly interned strings, PermGen string pool also contained all literal strings earlier used in your program (the important word here is used – if a class or method was never loaded/called, any constants defined in it will not be loaded).
The biggest issue with such string pool in Java 6 was its location – the PermGen. PermGen has a fixed size and can not be expanded at runtime. You can set it using -XX:MaxPermSize=96m option. As far as I know, the default PermGen size varies between 32M and 96M depending on the platform. You can increase its size, but its size will still be fixed. Such limitation required very careful usage of String.intern – you’d better not intern any uncontrolled user input using this method. That’s why string pooling at times of Java 6 was mostly implemented in the manually managed maps.
String.intern() in Java 7
Oracle engineers made an extremely important change to the string pooling logic in Java 7 – the string pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All strings are now located in the heap, as most of other ordinary objects, which allows you to manage only the heap size while tuning your application. Technically, this alone could be a sufficient reason to reconsider using String.intern() in your Java 7 programs. But there are other reasons.
String pool values are garbage collected
Yes, all strings in the JVM string pool are eligible for garbage collection if there are no references to them from your program roots. It applies to all discussed versions of Java. It means that if your interned string went out of scope and there are no other references to it – it will be garbage collected from the JVM string pool.
Being eligible for garbage collection and residing in the heap, a JVM string pool seems to be a right place for all your strings, isn’t it? In theory it is true – non-used strings will be garbage collected from the pool, used strings will allow you to save memory in case then you get an equal string from the input. Seems to be a perfect memory saving strategy? Nearly so. You must know how the string pool is implemented before making any decisions.
Found an interesting and neat way to export environment variables from a file:
in env.vars
:
foo=test
test script:
eval `cat env.vars`
echo $foo # => test
sh -c 'echo $foo' # =>
export eval `cat env.vars`
echo $foo # => test
sh -c 'echo $foo' # => test
# a better one. "--" stops processing options,
# key=value list given as params
export -- `cat env.vars`
echo $foo # => test
sh -c 'echo $foo' # => test
You're looking for the onblur
event. Look here, for more details.
FOR %%A IN (list) DO command parameters
list is a list of any elements, separated by either spaces, commas or semicolons.
command can be any internal or external command, batch file or even - in OS/2 and NT - a list of commands
parameters contains the command line parameters for command. In this example, command will be executed once for every element in list, using parameters if specified.
A special type of parameter (or even command) is %%A, which will be substituted by each element from list consecutively.
From FOR loops
You can use the function parseInt
to get a truncated result.
parseInt(a/b)
To get a remainder, use mod operator:
a%b
parseInt have some pitfalls with strings, to avoid use radix parameter with base 10
parseInt("09", 10)
In some cases the string representation of the number can be a scientific notation, in this case, parseInt will produce a wrong result.
parseInt(100000000000000000000000000000000, 10) // 1e+32
This call will produce 1 as result.
As of Python 3.4, the hashlib
module in the standard library contains key derivation functions which are "designed for secure password hashing".
So use one of those, like hashlib.pbkdf2_hmac
, with a salt generated using os.urandom
:
from typing import Tuple
import os
import hashlib
import hmac
def hash_new_password(password: str) -> Tuple[bytes, bytes]:
"""
Hash the provided password with a randomly-generated salt and return the
salt and hash to store in the database.
"""
salt = os.urandom(16)
pw_hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
return salt, pw_hash
def is_correct_password(salt: bytes, pw_hash: bytes, password: str) -> bool:
"""
Given a previously-stored salt and hash, and a password provided by a user
trying to log in, check whether the password is correct.
"""
return hmac.compare_digest(
pw_hash,
hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
)
# Example usage:
salt, pw_hash = hash_new_password('correct horse battery staple')
assert is_correct_password(salt, pw_hash, 'correct horse battery staple')
assert not is_correct_password(salt, pw_hash, 'Tr0ub4dor&3')
assert not is_correct_password(salt, pw_hash, 'rosebud')
Note that:
os.urandom
always uses a cryptographically secure source of randomnesshmac.compare_digest
, used in is_correct_password
, is basically just the ==
operator for strings but without the ability to short-circuit, which makes it immune to timing attacks. That probably doesn't really provide any extra security value, but it doesn't hurt, either, so I've gone ahead and used it.For theory on what makes a good password hash and a list of other functions appropriate for hashing passwords with, see https://security.stackexchange.com/q/211/29805.
I can't comment yet, but make sure you made all the checks in this quide: How to enable remote connections in SQL Server 2008? It should work fine if all steps are made.
The JavaScript try…catch mechanism cannot be used to intercept errors generated by asynchronous APIs. A common mistake for beginners is to try to use throw inside an error-first callback:
// THIS WILL NOT WORK:
const fs = require('fs');
try {
fs.readFile('/some/file/that/does-not-exist', (err, data) => {
// Mistaken assumption: throwing here...
if (err) {
throw err;
}
});
} catch (err) {
// This will not catch the throw!
console.error(err);
}
This will not work because the callback function passed to fs.readFile() is called asynchronously. By the time the callback has been called, the surrounding code, including the try…catch block, will have already exited. Throwing an error inside the callback can crash the Node.js process in most cases. If domains are enabled, or a handler has been registered with process.on('uncaughtException'), such errors can be intercepted.
reference: https://nodejs.org/api/errors.html
I'm guessing from the responses that people aren't understanding your question... If I'm right in that you want to have ~\Desktop\github\ then changing the SDK location isn't what you're after.
From Android Studio 3.2.1: From the new project dialog, choose Configure -> Preferences -> Tools -> Terminal -> Start Directory
Put the folder you want as your project default in the field.
e.g. Mine is set to ~/Desktop/github/ since all my work is in ~/Desktop/github/
IBM defines it as:
The portion of a program or segment unit in which a declaration applies. An identifier declared in a routine is known within that routine and within all nested routines. If a nested routine declares an item with the same name, the outer item is not available in the nested routine.
Example 1:
function x() {
/*
Variable 'a' is only available to function 'x' and function 'y'.
In other words the area defined by 'x' is the lexical scope of
variable 'a'
*/
var a = "I am a";
function y() {
console.log( a )
}
y();
}
// outputs 'I am a'
x();
Example 2:
function x() {
var a = "I am a";
function y() {
/*
If a nested routine declares an item with the same name,
the outer item is not available in the nested routine.
*/
var a = 'I am inner a';
console.log( a )
}
y();
}
// outputs 'I am inner a'
x();
Another option:
$("#<%=dropDownId.ClientID%>").children("option:selected").val();
have you tried:
.image_block{
text-align: center;
vertical-align: bottom;
}
Use the Java 8 way of converting a Map<String, Object>
to Map<String, String>
. This solution handles null
values.
Map<String, String> keysValuesStrings = keysValues.entrySet().stream()
.filter(entry -> entry.getValue() != null)
.collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().toString()));
Change directory to tomcat/bin directory in cmd prompt
cd C:\Program Files\Apache Software Foundation\Tomcat 8.0\bin
Run the below command to start:
On Linux: >startup.sh
On Windows: >startup.bat
Run these commands to stop
On Linux: shutdown.sh
On Windows: shutdown.bat
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
Just assign the import to a data property
<script>
import json from './json/data.json'
export default{
data(){
return{
myJson: json
}
}
}
</script>
then loop through the myJson
property in your template using v-for
<template>
<div>
<div v-for="data in myJson">{{data}}</div>
</div>
</template>
NOTE
If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.
Vue converts all the properties in the data
option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue to setup getters/setters for data which is not going to change. See Reactivity in depth.
So you can create a custom option as follows:
<script>
import MY_JSON from './json/data.json'
export default{
//custom option named myJson
myJson: MY_JSON
}
</script>
then loop through the custom option in your template using $options
:
<template>
<div>
<div v-for="data in $options.myJson">{{data}}</div>
</div>
</template>
Here goes:
char str[] = "This is the end";
char input[100];
printf("%s\n", str);
printf("%c\n", *str);
scanf("%99s", input);
In one word: no. The only way to stretch an image is with the <img>
tag. You'll have to be creative.
This used to be true in 2008, when the answer was written. Today modern browsers support background-size
which solves this problem. Beware that IE8 doesn't support it.
The server at x3.chatforyoursite.com
needs to output the following header:
Access-Control-Allow-Origin: http://www.example.com
Where http://www.example.com
is your website address. You should check your settings on chatforyoursite.com
to see if you can enable this - if not their technical support would probably be the best way to resolve this. However to answer your question, you need the remote site to allow your site to access AJAX responses client side.
To make the vertical line to center in the middle use:
position: absolute;
left: 50%;
I had this problem with git rebase -i origin/master
to a branch. I wanted to take master's version of the submodule ref, so I simply did:
git reset master path/to/submodule
and then
git rebase --continue
That solved the problem for me.
If you want to remove punctuation from any string you should use the P
Unicode class.
But, because classes are not accepted in the JavaScript RegEx, you could try this RegEx that should match all the punctuation. It matches the following categories: Pc Pd Pe Pf Pi Po Ps Sc Sk Sm So GeneralPunctuation SupplementalPunctuation CJKSymbolsAndPunctuation CuneiformNumbersAndPunctuation.
I created it using this online tool that generates Regular Expressions specifically for JavaScript. That's the code to reach your goal:
var punctuationRegEx = /[!-/:-@[-`{-~¡-©«-¬®-±´¶-¸»¿×÷?-??-??-???-??;?-?????-?:-??????-??-???-?%-????-??-??-??-???-?????-???-??????-??-??-?????-???-??-??-??-??-???-??-??-??-??-??-??-??-??-???-??-??-??-??-??-??-???-??-??-??-??-?\u2000-\u206e?-??-??-??-??-??-???-P?-????e?-??-??-???-??-??-??-?--??-??-??-??-??-??-???-??|-??-???-??-??-???-??-??-??-??-??-\u2e7e?-??-??-??-?\u3000-??-??·?-??-??-??-??-???-??-??-??-??-??-??-????-??-??-??-??-??-??-???-???-??-??-??-??-??-?!-/:-@[-`{-??-??-??-?]|\ud800[\udd00-\udd02\udd37-\udd3f\udd79-\udd89\udd90-\udd9b\uddd0-\uddfc\udf9f\udfd0]|\ud802[\udd1f\udd3f\ude50-\ude58]|\ud809[\udc00-\udc7e]|\ud834[\udc00-\udcf5\udd00-\udd26\udd29-\udd64\udd6a-\udd6c\udd83-\udd84\udd8c-\udda9\uddae-\udddd\ude00-\ude41\ude45\udf00-\udf56]|\ud835[\udec1\udedb\udefb\udf15\udf35\udf4f\udf6f\udf89\udfa9\udfc3]|\ud83c[\udc00-\udc2b\udc30-\udc93]/g;_x000D_
var string = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";_x000D_
var newString = string.replace(punctuationRegEx, '').replace(/(\s){2,}/g, '$1');_x000D_
console.log(newString)
_x000D_
You can also plot to a png file using gnuplot (which is free):
terminal commands
gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'
note: you always need to give the right extension (.png here) at set output
Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:
plot '<Fromfile.csv>' with line lt -1 lw 2
More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html
apt-get install gnuplot
)brew install gnuplot
)I did it like this in my Jtable its autorefreshing after 300 ms;
DefaultTableModel tableModel = new DefaultTableModel(){
public boolean isCellEditable(int nRow, int nCol) {
return false;
}
};
JTable table = new JTable();
Timer t = new Timer(300, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addColumns();
remakeData(set);
table.setModel(model);
}
});
t.start();
private void addColumns() {
model.setColumnCount(0);
model.addColumn("NAME");
model.addColumn("EMAIL");}
private void remakeData(CollectionType< Objects > name) {
model.setRowCount(0);
for (CollectionType Objects : name){
String n = Object.getName();
String e = Object.getEmail();
model.insertRow(model.getRowCount(),new Object[] { n,e });
}}
I doubt it will do good with large number of objects like over 500, only other way is to implement TableModelListener in your class, but i did not understand how to use it well. look at http://download.oracle.com/javase/tutorial/uiswing/components/table.html#modelchange
In my case, I've added an Environment variable VCTargetPath
with path
"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\VC\VCTargets\"
('\' at the end is crucial, as the project solution files has a reference to "Microsoft cpp targets" file.
Also, starting from Visual Studio 2017 MSBUILD comes along within Visual Studio - so, the PATH variable
needs to be updated with
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin
Updating VCTargetPath
and MSBUILD's PATH
variables and building fixed the error.
Not mentioned as of yet:
The unsort
util. Syntax (somewhat playlist oriented):
unsort [-hvrpncmMsz0l] [--help] [--version] [--random] [--heuristic]
[--identity] [--filenames[=profile]] [--separator sep] [--concatenate]
[--merge] [--merge-random] [--seed integer] [--zero-terminated] [--null]
[--linefeed] [file ...]
msort
can shuffle by line, but it's usually overkill:
seq 10 | msort -jq -b -l -n 1 -c r
Just use the change directory (cd) command.
cd d:\windows\movie
Dim fso
Dim ObjOutFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set ObjOutFile = fso.CreateTextFile("OutputFiles.csv")
ObjOutFile.WriteLine("Type,File Name,File Path")
GetFiles("YOUR LOCATION")
ObjOutFile.Close
WScript.Echo("Completed")
Function GetFiles(FolderName)
On Error Resume Next
Dim ObjFolder
Dim ObjSubFolders
Dim ObjSubFolder
Dim ObjFiles
Dim ObjFile
Set ObjFolder = fso.GetFolder(FolderName)
Set ObjFiles = ObjFolder.Files
For Each ObjFile In ObjFiles
ObjOutFile.WriteLine("File," & ObjFile.Name & "," & ObjFile.Path)
Next
Set ObjSubFolders = ObjFolder.SubFolders
For Each ObjFolder In ObjSubFolders
ObjOutFile.WriteLine("Folder," & ObjFolder.Name & "," & ObjFolder.Path)
GetFiles(ObjFolder.Path)
Next
End Function
Save the code as vbs and run it. you will get a list in that directory
Technically, ANSI should be the same as US-ASCII. It refers to the ANSI X3.4 standard, which is simply the ANSI organisation's ratified version of ASCII. Use of the top-bit-set characters is not defined in ASCII/ANSI as it is a 7-bit character set.
However years of misuse of the term by the DOS and subsequently Windows community has left its practical meaning as “the system codepage of whatever machine is being used”. The system codepage is also sometimes known as ‘mbcs’, since on East Asian systems that can be a multiple-byte-per-character encoding. Some code pages can even use top-bit-clear bytes as trailing bytes in a multibyte sequence, so it's not even strict compatible with plain ASCII... but even then, it's still called “ANSI”.
On US and Western European default settings, “ANSI” maps to Windows code page 1252. This is not the same as ISO-8859-1 (although it is quite similar). On other machines it could be anything else at all. This makes “ANSI” utterly useless as an external encoding identifier.
From version 9.1.4 you only need to import ReactiveFormsModule
To export user variables, open a command prompt and use regedit with /e
Example :
regedit /e "%userprofile%\Desktop\my_user_env_variables.reg" "HKEY_CURRENT_USER\Environment"
You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.
For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.
If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp
. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.
For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.
If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.
I think this code should work fine
while ($personCount < 10) {
$result = $personCount . "people ';
$personCount++;
}
// do not understand why do you need the (+) with the result.
echo $result;
I had the same issue. I solved it, truncating the SQL Server LOG. Check doing that, and then tell us, if this solution helped you.
If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.
Starting with your example array:
import numpy as np
x = np.array([[1000, 10, 0.5],
[ 765, 5, 0.35],
[ 800, 7, 0.09]])
x_normed = x / x.max(axis=0)
print(x_normed)
# [[ 1. 1. 1. ]
# [ 0.765 0.5 0.7 ]
# [ 0.8 0.7 0.18 ]]
x.max(0)
takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,)
containing the maximum value in each column. You can then divide x
by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.
If x
contains negative values you would need to subtract the minimum first:
x_normed = (x - x.min(0)) / x.ptp(0)
Here, x.ptp(0)
returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.
Using javac ClassName.java to compile the program, then use java ClassName to execute the compiled code. You can't mix javac with the ClassName only (without the java extension).
map
isn't particularly pythonic. I would recommend using list comprehensions instead:
map(f, iterable)
is basically equivalent to:
[f(x) for x in iterable]
map
on its own can't do a Cartesian product, because the length of its output list is always the same as its input list. You can trivially do a Cartesian product with a list comprehension though:
[(a, b) for a in iterable_a for b in iterable_b]
The syntax is a little confusing -- that's basically equivalent to:
result = []
for a in iterable_a:
for b in iterable_b:
result.append((a, b))
The "reference" Java implementation by Sean Leary is here on github. Make sure to have the latest version - different libraries pull in versions buggy old versions from 2009.
Java EE 7 has a JSON API in javax.json
, see the Javadoc. From what I can tell, it doesn't have a simple method to marshall any object to JSON, you need to construct a JsonObject
or a JsonArray
.
import javax.json.*;
JsonObject value = Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Smith")
.add("age", 25)
.add("address", Json.createObjectBuilder()
.add("streetAddress", "21 2nd Street")
.add("city", "New York")
.add("state", "NY")
.add("postalCode", "10021"))
.add("phoneNumber", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "home")
.add("number", "212 555-1234"))
.add(Json.createObjectBuilder()
.add("type", "fax")
.add("number", "646 555-4567")))
.build();
JsonWriter jsonWriter = Json.createWriter(...);
jsonWriter.writeObject(value);
jsonWriter.close();
But I assume the other libraries like GSON will have adapters to create objects implementing those interfaces.
We can calculate intersection minus union of lists:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two', 'Five']
set(temp1+temp2)-(set(temp1)&set(temp2))
Out: set(['Four', 'Five', 'Three'])
I navigated to C:\wamp\bin\apache\Apache2.4.4\bin run httpd and the apache (pink and white icon) loads into the system tray. The orange W also turned green.
The apacheapache service wasn't running, it wasn't on the services list (start > type services) which is why it's orange not green.
Solution: A re-install worked for me.
My version is: WAMPSERVER (64Bits & PHP 5.4) 2.4 Apache : 2.4.4 MySQL : 5.6.12 PHP : 5.4.12 PHPMyAdmin : 4.0.4 SqlBuddy : 1.3.3 XDebug : 2.2.3 http://www.wampserver.com/en/
Of course you can use the StringTokenizer
class to split the String with '.' or '/', and check if the last word is "work".
you can try
isfar <- get(load('c:/users/isfar.Rdata'))
this will assign the variable in isfar.Rdata to isfar . After this assignment, you can use str(isfar) or ls(isfar) or head(isfar) to get a rough look of the isfar.
I had similar problems just a while ago. After trying more than 5 suggestions I decided to go back to the basics and start from the beginning. Which meant removing my postgresql installation and following this guide upon re-installing postgresql. https://help.ubuntu.com/lts/serverguide/postgresql.html
You are not selecting multiple indexes with PriceList[0][1][2][3][4][5][6] , instead each [] is going into a sub index.
Try this
PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))
PriceList[0:7]=[PizzaChange]*7
PriceList[7:11]=[PizzaChange+3]*4
Here is another approach that hasn't been mentioned by the others here (as of this writing).
You can use custom events like so:
// your index.html template
<html ng-app="app">
<head>
<title ng-bind="pageTitle">My App</title>
// your main app controller that is declared on the <html> element
app.controller('AppController', function($scope) {
$scope.$on('title-updated', function(newTitle) {
$scope.pageTitle = newTitle;
});
});
// some controller somewhere deep inside your app
mySubmodule.controller('SomeController', function($scope, dynamicService) {
$scope.$emit('title-updated', dynamicService.title);
});
This approach has the advantage of not requiring extra services to be written and then injected into every controller that needs to set the title, and also doesn't (ab)use the $rootScope
. It also allows you to set a dynamic title (as in the code example), which is not possible using custom data attributes on the router's config object (as far as I know at least).
I needed this command to make it work on El Capitan:
sudo security add-trust -d -r trustRoot -p basic -p codeSign -k /Library/Keychains/System.keychain ~/Desktop/gdb-cert.cer
A1 --> conditional formatting --> cell value is B1 --> format: whatever you want
hope that helps
Yes, you can use the native javascript Date() object and its methods.
For instance you can create a function like:
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var e = formatDate(d);
alert(e);
And display also the am / pm and the correct time.
Remember to use getFullYear() method and not getYear() because it has been deprecated.
Complete example here:-
<!DOCTYPE html >
<html ng-app="dashboard">
<head>
<title>AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="./bootstrap.min.css">
<script src="./bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
</head>
<body ng-controller="myController">
<table border='1'>
<tr ng-repeat="(key,val) in collValues">
<td ng-if="!hasChildren(val)">{{key}}</td>
<td ng-if="val === 'string'">
<input type="text" name="{{key}}"></input>
</td>
<td ng-if="val === 'number'">
<input type="number" name="{{key}}"></input>
</td>
<td ng-if="hasChildren(val)" td colspan='2'>
<table border='1' ng-repeat="arrVal in val">
<tr ng-repeat="(key,val) in arrVal">
<td>{{key}}</td>
<td ng-if="val === 'string'">
<input type="text" name="{{key}}"></input>
</td>
<td ng-if="val === 'number'">
<input type="number" name="{{key}}"></input>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
<script type="text/javascript">
var app = angular.module("dashboard",[]);
app.controller("myController",function($scope){
$scope.collValues = {
'name':'string',
'id':'string',
'phone':'number',
'depart':[
{
'depart':'string',
'name':'string'
}
]
};
$scope.hasChildren = function(bigL1) {
return angular.isArray(bigL1);
}
});
</script>
</html>
If you prefer the diff output style from git diff
, you can use it with the --no-index
flag to compare files not in a git repository:
git diff --no-index a.txt b.txt
Using a couple of files with around 200k file name strings in each, I benchmarked (with the built-in time
command) this approach vs some of the other answers here:
git diff --no-index a.txt b.txt
# ~1.2s
comm -23 <(sort a.txt) <(sort b.txt)
# ~0.2s
diff a.txt b.txt
# ~2.6s
sdiff a.txt b.txt
# ~2.7s
vimdiff a.txt b.txt
# ~3.2s
comm
seems to be the fastest by far, while git diff --no-index
appears to be the fastest approach for diff-style output.
Update 2018-03-25 You can actually omit the --no-index
flag unless you are inside a git repository and want to compare untracked files within that repository. From the man pages:
This form is to compare the given two paths on the filesystem. You can omit the --no-index option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.
Something the other answers are missing is that it must be understood that Authentication and Authorization in the context of RFC 2616 refers ONLY to the HTTP Authentication protocol of RFC 2617. Authentication by schemes outside of RFC2617 is not supported in HTTP status codes and are not considered when deciding whether to use 401 or 403.
Unauthorized indicates that the client is not RFC2617 authenticated and the server is initiating the authentication process. Forbidden indicates either that the client is RFC2617 authenticated and does not have authorization or that the server does not support RFC2617 for the requested resource.
Meaning if you have your own roll-your-own login process and never use HTTP Authentication, 403 is always the proper response and 401 should never be used.
From RFC2616
10.4.2 401 Unauthorized
The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8).
and
10.4.4 403 Forbidden The server understood the request but is refusing to fulfil it. Authorization will not help and the request SHOULD NOT be repeated.
The first thing to keep in mind is that "Authentication" and "Authorization" in the context of this document refer specifically to the HTTP Authentication protocols from RFC 2617. They do not refer to any roll-your-own authentication protocols you may have created using login pages, etc. I will use "login" to refer to authentication and authorization by methods other than RFC2617
So the real difference is not what the problem is or even if there is a solution. The difference is what the server expects the client to do next.
401 indicates that the resource can not be provided, but the server is REQUESTING that the client log in through HTTP Authentication and has sent reply headers to initiate the process. Possibly there are authorizations that will permit access to the resource, possibly there are not, but let's give it a try and see what happens.
403 indicates that the resource can not be provided and there is, for the current user, no way to solve this through RFC2617 and no point in trying. This may be because it is known that no level of authentication is sufficient (for instance because of an IP blacklist), but it may be because the user is already authenticated and does not have authority. The RFC2617 model is one-user, one-credentials so the case where the user may have a second set of credentials that could be authorized may be ignored. It neither suggests nor implies that some sort of login page or other non-RFC2617 authentication protocol may or may not help - that is outside the RFC2616 standards and definition.
Many to Many (n:m) One to Many (1:n)
Simply using below code in Kotlin works for me
WebView(applicationContext).clearCache(true)
curl -X PUT -d 'new_value' URL_PATH/key
where,
X - option to be used for request command
d - option to be used in order to put data on remote url
URL_PATH - remote url
new_value - value which we want to put to the server's key
If you are thinking that previously it was running properly and now on it started showing the particular issue. Then it is just a hit and trial method to solve. so to get better solution you could follow below steps
It's very simple. Right click inside the internal browser and click "refresh".
By default TortoiseSVN always has a GUI (Graphical User Interface) associated with it. But on the installer (of version 1.7 and later) you can select the "command line client tools" option so you can call svn commands (like svn commit and svn update) from the command line.
Here's a screenshot of the "command line client tools" option in the installer, you need to make sure you select it:
Just want to add this for the future programmer.
This code limits the date min and max. The year is fully controlled by getting the current year as max year.
Hope this could help to anyone.
Here's the code.
var dateToday = new Date();
var yrRange = '2014' + ":" + (dateToday.getFullYear());
$(function () {
$("[id$=txtDate]").datepicker({
showOn: 'button',
changeMonth: true,
changeYear: true,
showButtonPanel: true,
buttonImageOnly: true,
yearRange: yrRange,
buttonImage: 'calendar3.png',
buttonImageOnly: true,
minDate: new Date(2014,1-1,1),
maxDate: '+50Y',
inline:true
});
});
Here's an improved version based on code written by blade
The code:
class Crypto
{
/**
* Encrypt data using OpenSSL (AES-256-CBC)
* @param string $plaindata Data to be encrypted
* @param string $cryptokey key for encryption (with 256 bit of entropy)
* @param string $hashkey key for hashing (with 256 bit of entropy)
* @return string IV+Hash+Encrypted as raw binary string. The first 16
* bytes is IV, next 32 bytes is HMAC-SHA256 and the rest is
* $plaindata as encrypted.
* @throws Exception on internal error
*
* Based on code from: https://stackoverflow.com/a/46872528
*/
public static function encrypt($plaindata, $cryptokey, $hashkey)
{
$method = "AES-256-CBC";
$key = hash('sha256', $cryptokey, true);
$iv = openssl_random_pseudo_bytes(16);
$cipherdata = openssl_encrypt($plaindata, $method, $key, OPENSSL_RAW_DATA, $iv);
if ($cipherdata === false)
{
$cryptokey = "**REMOVED**";
$hashkey = "**REMOVED**";
throw new \Exception("Internal error: openssl_encrypt() failed:".openssl_error_string());
}
$hash = hash_hmac('sha256', $cipherdata.$iv, $hashkey, true);
if ($hash === false)
{
$cryptokey = "**REMOVED**";
$hashkey = "**REMOVED**";
throw new \Exception("Internal error: hash_hmac() failed");
}
return $iv.$hash.$cipherdata;
}
/**
* Decrypt data using OpenSSL (AES-256-CBC)
* @param string $encrypteddata IV+Hash+Encrypted as raw binary string
* where the first 16 bytes is IV, next 32 bytes is HMAC-SHA256 and
* the rest is encrypted payload.
* @param string $cryptokey key for decryption (with 256 bit of entropy)
* @param string $hashkey key for hashing (with 256 bit of entropy)
* @return string Decrypted data
* @throws Exception on internal error
*
* Based on code from: https://stackoverflow.com/a/46872528
*/
public static function decrypt($encrypteddata, $cryptokey, $hashkey)
{
$method = "AES-256-CBC";
$key = hash('sha256', $cryptokey, true);
$iv = substr($encrypteddata, 0, 16);
$hash = substr($encrypteddata, 16, 32);
$cipherdata = substr($encrypteddata, 48);
if (!hash_equals(hash_hmac('sha256', $cipherdata.$iv, $hashkey, true), $hash))
{
$cryptokey = "**REMOVED**";
$hashkey = "**REMOVED**";
throw new \Exception("Internal error: Hash verification failed");
}
$plaindata = openssl_decrypt($cipherdata, $method, $key, OPENSSL_RAW_DATA, $iv);
if ($plaindata === false)
{
$cryptokey = "**REMOVED**";
$hashkey = "**REMOVED**";
throw new \Exception("Internal error: openssl_decrypt() failed:".openssl_error_string());
}
return $plaindata;
}
}
If you truly cannot have proper encryption and hash keys but have to use an user entered password as the only secret, you can do something like this:
/**
* @param string $password user entered password as the only source of
* entropy to generate encryption key and hash key.
* @return array($encryption_key, $hash_key) - note that PBKDF2 algorithm
* has been configured to take around 1-2 seconds per conversion
* from password to keys on a normal CPU to prevent brute force attacks.
*/
public static function generate_encryptionkey_hashkey_from_password($password)
{
$hash = hash_pbkdf2("sha512", "$password", "salt$password", 1500000);
return str_split($hash, 64);
}
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
You are trying to compare strings inside an arithmetic command (((...))
). Use [[
instead.
if [[ $username == "$username1" && $password == "$password1" ]] ||
[[ $username == "$username2" && $password == "$password2" ]]; then
Note that I've reduced this to two separate tests joined by ||
, with the &&
moved inside the tests. This is because the shell operators &&
and ||
have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d
is equivalent to the intended ( a && b ) || ( c && d )
.
If you are talking about the issue where multiple and non-space whitespace characters are stripped specifically from attribute values, then yes, encoding them as character references such as 	 will fix it.
Use -1
index (negative indices count backward from the end of the array):
a[-1] # => 5
b[-1] # => 6
or Array#last
method:
a.last # => 5
b.last # => 6
You have to fetch that one record, it will contain the result of Count()
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
Open the find and replace dialog (press CTRL+H).
Then select Regular expression
in the 'Search Mode' section at the bottom.
In the Find what
field enter this: [\r\n]+
In the Replace with
: ,
There is a space after the comma.
This will also replace lines like
Apples
Apricots
Pear
Avocados
Bananas
Where there are empty lines.
If your lines have trailing blank spaces you should remove those first. The simplest way to achieve this is
EDIT -> Blank Operations -> Trim Trailing Space
OR
TextFX -> TextFX Edit -> Trim trailing spaces
Be sure to set the Search Mode to "Regular expression".
As @David Heffeman indicates the recommendation is to use .yaml
when possible, and the recommendation has been that way since September 2006.
That some projects use .yml
is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).
The best way to approach this is to be rigorous when creating new files (i.e. use .yaml
) and be permissive when accepting input (i.e. allow .yml
when you encounter it), possible automatically upgrading/correcting these errors when possible.
The other recommendation I have is to document the argument(s) why you have to use .yml
, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml
has more pages than .yaml
" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml
extension instead of the correct .yaml
, but I think you will be hard pressed to do so.
Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose
used .yml
, but in later versions started to use .yaml
, although they still support .yml
). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml
instead of appveyor.yml
for building the windows wheels of my YAML parser for Python).
On the other hand:
The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.
So it seems fitting that they also use a subset of the recommended extension.
Here's something that I just wrote along those lines::
#include <random>
#include <chrono>
#include <thread>
using namespace std;
//==============================================================
// RANDOM BACKOFF TIME
//==============================================================
class backoff_time_t {
public:
random_device rd;
mt19937 mt;
uniform_real_distribution<double> dist;
backoff_time_t() : rd{}, mt{rd()}, dist{0.5, 1.5} {}
double rand() {
return dist(mt);
}
};
thread_local backoff_time_t backoff_time;
int main(int argc, char** argv) {
double x1 = backoff_time.rand();
double x2 = backoff_time.rand();
double x3 = backoff_time.rand();
double x4 = backoff_time.rand();
return 0;
}
~
Considering you have 3 nodes.
export ES_HOST=localhost:9200
# Disable shard allocation
curl -X PUT "$ES_HOST/_cluster/settings" -H 'Content-Type: application/json' -d'
{
"persistent": {
"cluster.routing.allocation.enable": "none"
}
}
'
# Stop non-essential indexing and perform a synced flush
curl -X POST "$ES_HOST/_flush/synced"
# check nodes
export ES_HOST=localhost:9200
curl -X GET "$ES_HOST/_cat/nodes"
# node 1
systemctl stop elasticsearch.service
# node 2
systemctl stop elasticsearch.service
# node 3
systemctl stop elasticsearch.service
# start
systemctl start elasticsearch.service
# Reenable shard allocation once the node has joined the cluster
curl -X PUT "$ES_HOST/_cluster/settings" -H 'Content-Type: application/json' -d'
{
"persistent": {
"cluster.routing.allocation.enable": null
}
}
'
Tested on Elasticseach 6.5
Source:
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
Considering the files were not uploaded via media uploader, they are present in the server but there's no reference to them in your database (in a little more detail).
In order to fix it, install the Media Sync plugin. Once it's active, under Media > Media Sync > Scan Files and select the files you want to import by click the checkbox next to them. Make sure also you untick the selectbox Dry Run (test without making database changes).
Then, when the time comes for you to be ready, just click "Import Selected" and you should see something like this
Once it is finished, you can visit Media > Library and you'll see all your imported files there.
On mac, press Command + R
or got to Database
-> Reverse Engineer
and keep selecting your requirements and continue
One scenario where final is important, when you want to prevent inheritance of a class, for security reasons. This allows you to make sure that code you are running cannot be overridden by someone.
Another scenario is for optimization: I seem to remember that the Java compiler inlines some function calls from final classes. So, if you call a.x()
and a is declared final
, we know at compile-time what the code will be and can inline into the calling function. I have no idea whether this is actually done, but with final it is a possibility.
You can use the setspace package which gives you spacing environments, e.g.:
\documentclass{article}
\usepackage{setspace}
\begin{document}
\doublespace
my line of text blah blah blah
new line of text with blank line between
\end{document}
Or use a verbatim
environment to control the layout of your code precisely.
Index:
------------>
0 1 2 3 4
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
0 -4 -3 -2 -1
<------------
Slice:
<---------------|
|--------------->
: 1 2 3 4 :
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
: -4 -3 -2 -1 :
|--------------->
<---------------|
I hope this will help you to model the list in Python.
Reference: http://wiki.python.org/moin/MovingToPythonFromOtherLanguages
In management studio:
Properties
, then Options
.Tasks
-> Shrink
-> Files
Alternatively, the SQL to do it:
ALTER DATABASE mydatabase SET RECOVERY SIMPLE
DBCC SHRINKFILE (mydatabase_Log, 1)
try:
$(window).scrollTop( $('body').height() );
timeout = (connection timeout, data read timeout) or give a single argument(timeout=1)
import requests
try:
req = requests.request('GET', 'https://www.google.com',timeout=(1,1))
print(req)
except requests.ReadTimeout:
print("READ TIME OUT")
Quoting the spec
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.
And here's a table for typeof
To add some background, there are two data types in JavaScript:
An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.
An array can be considered to be an object with the following properties/keys:
Hope this helped shed more light on why typeof Array returns an object. Cheers!
There is no difference between the two in how they are stored in memory and registers, there is no signed and unsigned version of int registers there is no signed info stored with the int, the difference only becomes relevant when you perform maths operations, there are signed and unsigned version of the maths ops built into the CPU and the signedness tell the compiler which version to use.
Using execComand:
<input type="button" name="save" value="Save" onclick="javascript:document.execCommand('SaveAs','true','your_file.txt')">
In the next link: execCommand
You don't need the date
validator. It doesn't support dd/mm/yyyy format, and that's why you are getting "Please enter a valid date" message for input like 13/01/2014. You already have the dateITA
validator, which uses dd/mm/yyyy format as you need.
Just like the date
validator, your code for dateGreaterThan
and dateLessThan
calls new Date
for input string and has the same issue parsing dates. You can use a function like this to parse the date:
function parseDMY(value) {
var date = value.split("/");
var d = parseInt(date[0], 10),
m = parseInt(date[1], 10),
y = parseInt(date[2], 10);
return new Date(y, m - 1, d);
}
Instant.now() // Capture the current moment in UTC.
.atZone( ZoneId.systemDefault() ) // Adjust into the JVM's current default time zone. Same moment, different wall-clock time. Produces a `ZonedDateTime` object.
.toInstant() // Extract a `Instant` (always in UTC) object from the `ZonedDateTime` object.
.atZone( ZoneId.of( "Europe/Paris" ) ) // Adjust the `Instant` into a specific time zone. Renders a `ZonedDateTime` object. Same moment, different wall-clock time.
.toInstant() // And back to UTC again.
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes (Date
, Calendar
, etc.).
Your use of the word "local" contradicts the usage in the java.time class. In java.time, "local" means any locality or all localities, but not any one particular locality. The java.time classes with names starting with "Local…" all lack any concept of time zone or offset-from-UTC. So they do not represent a specific moment, they are not a point on the timeline, whereas your Question is all about moments, points on the timeline viewed through various wall-clock times.
Get the current system time (local time)
If you want to capture the current moment in UTC, use Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Adjust into a time zone by applying a ZoneId
to get a ZonedDateTime
. Same moment, same point on the timeline, different wall-clock time.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
As a shortcut, you can skip the usage of Instant
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Convert Local time to UTC // Works Fine Till here
You can adjust from the zoned date-time to UTC by extracting an Instant
from a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Instant instant = zdt.toInstant() ;
Reverse the UTC time, back to local time.
As shown above, apply a ZoneId
to adjust the same moment into another wall-clock time used by the people of a certain region (a time zone).
Instant instant = Instant.now() ; // Capture current moment in UTC.
ZoneId zDefault = ZoneId.systemDefault() ; // The JVM's current default time zone.
ZonedDateTime zdtDefault = instant.atZone( zDefault ) ;
ZoneId zTunis = ZoneId.of( "Africa/Tunis" ) ; // The JVM's current default time zone.
ZonedDateTime zdtTunis = instant.atZone( zTunis ) ;
ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" ) ; // The JVM's current default time zone.
ZonedDateTime zdtAuckland = instant.atZone( zAuckland ) ;
Going back to UTC from a zoned date-time, call ZonedDateTime::toInstant
. Think of it conceptually as: ZonedDateTime = Instant + ZoneId.
Instant instant = zdtAuckland.toInstant() ;
All of these objects, the Instant
and the three ZonedDateTime
objects all represent the very same simultaneous moment, the same point in history.
Followed 3 different approaches (listed below) but all the 3 approaches retains the time in UTC only.
Forget about trying to fix code using those awful Date
, Calendar
, and GregorianCalendar
classes. They are a wretched mess of bad design and flaws. You need never touch them again. If you must interface with old code not yet updated to java.time, you can convert back-and-forth via new conversion methods added to the old classes.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
.add() also works.
var daySelect = document.getElementById("myDaySelect");
var myOption = document.createElement("option");
myOption.text = "test";
myOption.value = "value";
daySelect.add(option);
Your format specifier is incorrect. From the printf()
man page on my machine:
0
A zero '0
' character indicating that zero-padding should be used rather than blank-padding. A '-
' overrides a '0
' if both are used;Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);
Precision: An optional period, '
.
', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;
For your case, your format would be %09.3f
:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%09.3f\n", 4917.24);
return 0;
}
Output:
$ make testapp
cc testapp.c -o testapp
$ ./testapp
04917.240
Note that this answer is conditional on your embedded system having a printf()
implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.
I had the same error from a different cause: I'd created a starter POM containing our "good practice" dependencies, and built & installed it locally to test it. I could "see" it in the repo, but a project that used it got the above error. What I'd done was set the starter POM to pom, so there was no JAR. Maven was quite correct that it wasn't in Nexus -- but I wasn't expecting it to be, so the error was, ummm, unhelpful. Changing the starter POM to normal packaging & reinstalling fixed the issue.
You can increase to 2GB
on a 32
bit system. If you're on a 64 bit system you can go higher. No need to worry if you've chosen incorrectly, if you ask for 5g on a 32 bit system java will complain about an invalid value and quit.
As others have posted, use the cmd-line flags - e.g.
java -Xmx6g myprogram
You can get a full list (or a nearly full list, anyway) by typing java -X.
lodash
included in their project:Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.
var object = { 'a': [{ 'b': { 'c': 3 } }] };_x000D_
_x000D_
console.log(_x000D_
_.get(object, 'a[0].b.c'), // => 3_x000D_
_.get(object, ['a', '0', 'b', 'c']), // => 3_x000D_
_.get(object, 'a.b.c'), // => undefined _x000D_
_.get(object, 'a.b.c', 'default') // => 'default'_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
_x000D_
This will effectively check if that key, however deep, is defined and will not throw an error which might harm the flow of your program if that key is not defined.
You need to add the path to Tomcat's /lib/servlet-api.jar
file to the compile time classpath.
javac -cp .;/path/to/Tomcat/lib/servlet-api.jar com/example/MyServletClass.java
The classpath is where Java needs to look for imported dependencies. It will otherwise default to the current folder which is included as .
in the above example. The ;
is the path separator for Windows; if you're using an Unix based OS, then you need to use :
instead.
If you're still facing the same complation error, and you're actually using Tomcat 10 or newer, then you should be migrating the imports in your source code from javax.*
to jakarta.*
.
import jakarta.servlet.*;
import jakarta.servlet.http.*;
Factory
and Service
is a just wrapper of a provider
.
Factory
Factory
can return anything which can be a class(constructor function)
, instance of class
, string
, number
or boolean
. If you return a constructor
function, you can instantiate in your controller.
myApp.factory('myFactory', function () {
// any logic here..
// Return any thing. Here it is object
return {
name: 'Joe'
}
}
Service
Service does not need to return anything. But you have to assign everything in this
variable. Because service will create instance by default and use that as a base object.
myApp.service('myService', function () {
// any logic here..
this.name = 'Joe';
}
Actual angularjs code behind the service
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
It just a wrapper around the factory
. If you return something from service
, then it will behave like Factory
.
IMPORTANT
: The return result from Factory and Service will be cache and same will be returned for all controllers.
When should i use them?
Factory
is mostly preferable in all cases. It can be used when you have constructor
function which needs to be instantiated in different controllers.
Service
is a kind of Singleton
Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application.
Eg: Authenticated user details.
For further understanding, read
http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html
http://viralpatel.net/blogs/angularjs-service-factory-tutorial/
In newer versions of typescript you can use:
type Customers = Record<string, Customer>
In older versions you can use:
var map: { [email: string]: Customer; } = { };
map['[email protected]'] = new Customer(); // OK
map[14] = new Customer(); // Not OK, 14 is not a string
map['[email protected]'] = 'x'; // Not OK, 'x' is not a customer
You can also make an interface if you don't want to type that whole type annotation out every time:
interface StringToCustomerMap {
[email: string]: Customer;
}
var map: StringToCustomerMap = { };
// Equivalent to first line of above
I found a way to convert the response.result.value (inside an Alamofire responseJSON closure) into JSON format that I use in my app.
I'm using Alamofire 3 and Swift 2.2.
Here's the code I used:
Alamofire.request(.POST, requestString,
parameters: parameters,
encoding: .JSON,
headers: headers).validate(statusCode: 200..<303)
.validate(contentType: ["application/json"])
.responseJSON { (response) in
NSLog("response = \(response)")
switch response.result {
case .Success:
guard let resultValue = response.result.value else {
NSLog("Result value in response is nil")
completionHandler(response: nil)
return
}
let responseJSON = JSON(resultValue)
// I do any processing this function needs to do with the JSON here
// Here I call a completionHandler I wrote for the success case
break
case .Failure(let error):
NSLog("Error result: \(error)")
// Here I call a completionHandler I wrote for the failure case
return
}
The most idiomatic way to do this is to use symbols. For example, instead of:
enum {
FOO,
BAR,
BAZ
}
myFunc(FOO);
...you can just use symbols:
# You don't actually need to declare these, of course--this is
# just to show you what symbols look like.
:foo
:bar
:baz
my_func(:foo)
This is a bit more open-ended than enums, but it fits well with the Ruby spirit.
Symbols also perform very well. Comparing two symbols for equality, for example, is much faster than comparing two strings.
Nothing stops you from doing
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;
Check this example
var a, b, c;_x000D_
a = b = c = 10;_x000D_
console.log(a + b + c)
_x000D_
Since pip v1.5
, (released Jan 1 2014: CHANGELOG, PR) you may also specify a subdirectory of a git repo to contain your module. The syntax looks like this:
pip install -e git+https://git.repo/some_repo.git#egg=my_subdir_pkg&subdirectory=my_subdir_pkg # install a python package from a repo subdirectory
Note: As a pip module author, ideally you'd probably want to publish your module in it's own top-level repo if you can. Yet this feature is helpful for some pre-existing repos that contain python modules in subdirectories. You might be forced to install them this way if they are not published to pypi too.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wb = new WebView(this);
wb.loadUrl("file:///android_asset/index.html");
setContentView(wb);
}
keep your .html in `asset` folder
Based upon dwanderson's helpful comment, I was able to do this in a Bash one-liner:
conda create --name envpython2 --file <(conda list -n env1 -e )
My badly named env was "env1" and the new one I wish to clone from it is "envpython2".
For me, I was writing to a file that is opened in Excel.
img {
filter: blur(var(--blur));
}
Another alternative altogether is to use the printf function.
printf -v str 'hello'
Moreover, this construct, combined with the use of single quotes where appropriate, helps to avoid the multi-escape problems of subshells and other forms of interpolative quoting.
Adding data-dismiss="modal"
on any buttons in my modal worked for me. I wanted my button to call a function with angular to fire an ajax call AND close the modal so I added a .toggle()
within the function and it worked well. (In my case I used a bootstrap modal
and used some angular
, not an actual modal controller).
<button type="button" class="btn btn-primary" data-dismiss="modal"
ng-click="functionName()"> Do Something </button>
$scope.functionName = function () {
angular.element('#modalId').toggle();
$.ajax({ ajax call })
}
How about the alternate form of for
mentioned in (bashref)Looping Constructs?
The September 4th release for 3.7 recommends the following:
conda install python=3.7 anaconda=custom
If you want to create a new environment, they recommend:
conda create -n example_env numpy scipy pandas scikit-learn notebook
anaconda-navigator
conda activate example_env
Add the following code to the .htaccess file:
Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^ https://[your domain name]%{REQUEST_URI} [R,L]
Where [your domain name] is your website's domain name.
You can also redirect specific folders off of your domain name by replacing the last line of the code above with:
RewriteRule ^ https://[your domain name]/[directory name]%{REQUEST_URI} [R,L]
Here goes:
DECLARE @var nvarchar(max) = 'Man''s best friend';
You will note that the '
is escaped by doubling it to ''
.
Since the string delimiter is '
and not "
, there is no need to escape "
:
DECLARE @var nvarchar(max) = '"My Name is Luca" is a great song';
The second example in the MSDN page on DECLARE
shows the correct syntax.
It depends on when the self executing anonymous function is running. It is possible that it is running before window.document
is defined.
In that case, try adding a listener
window.addEventListener('load', yourFunction, false);
// ..... or
window.addEventListener('DOMContentLoaded', yourFunction, false);
yourFunction () {
// some ocde
}
Update: (after the update of the question and inclusion of the code)
Read the following about the issues in referencing DOM elements from a JavaScript inserted and run in head
element:
- “getElementsByTagName(…)[0]” is undefined?
- Traversing the DOM
Try using SweetAlert its just simply the best . You will get a lot of customization and flexibility.
sweetAlert(
{
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!"
},
deleteIt()
);
Assertions are used to check post-conditions and "should never fail" pre-conditions. Correct code should never fail an assertion; when they trigger, they should indicate a bug (hopefully at a place that is close to where the actual locus of the problem is).
An example of an assertion might be to check that a particular group of methods is called in the right order (e.g., that hasNext()
is called before next()
in an Iterator
).
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
This is the way I got it working for me:
Tasks:
- name: checking if the file 1 exists
stat:
path: /path/to/foo abc.xts
register: stat_result
- name: moving file 1
command: mv /path/to/foo abc.xts /tmp
when: stat_result.stat.exists == True
the playbook above, will check if file abc.xts exists before move the file to tmp folder.
It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.
@Request/View/Flow/Session/ApplicationScoped
A @RequestScoped
bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped
bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null
/void
without any navigation/redirect. A @FlowScoped
bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped
bean lives as long as the established HTTP session. An @ApplicationScoped
bean lives as long as the web application runs. Note that the CDI @Model
is basically a stereotype for @Named @RequestScoped
, so same rules apply.
Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped
for simple and non-ajax forms/presentations. Use @ViewScoped
for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped
for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped
for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped
for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.
Abusing an @ApplicationScoped
bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped
bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped
bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped
bean for request, session or application scoped data, and abusing a @SessionScoped
bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.
Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped
beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty
in case of JSF managed beans or @Inject
in case of CDI managed beans.
@CustomScoped/NoneScoped/Dependent
It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped
and @NoneScoped
, which are rarely used in real world. The @CustomScoped
must refer a custom Map<K, Bean>
implementation in some broader scope which has overridden Map#put()
and/or Map#get()
in order to have more fine grained control over bean creation and/or destroy.
The JSF @NoneScoped
and CDI @Dependent
basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped
or @Dependent
is injected in a @SessionScoped
, then it will live as long as the @SessionScoped
bean.
As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.
This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped
. The flash scope is only available as a map via ExternalContext#getFlash()
in managed beans and #{flash}
in EL.
You could also reuse SwingConstants.{LEFT,RIGHT}. They are not enums, but they do already exist and are used in many places.
How about using a COUNT OVER (PARTITION BY {column to group by}) partitioning function in SQL Server?
For example, if you want to group product sales by ItemID and you want a count of each distinct ItemID, simply use:
SELECT
{columns you want} ,
COUNT(ItemID) OVER (PARTITION BY ItemID) as BandedItemCount ,
{more columns you want}... ,
FROM {MyTable}
If you use this approach, you can leave the GROUP BY out of the picture -- assuming you want to return the entire list (as you might do report banding where you need to know the entire count of items you are going to band without having to display the entire set of data, i.e. Reporting Services).
Use the predefined PHP_EOL
constant:
echo $clientid, ' ', $lastname, PHP_EOL;
The constant value will be set according to the line endings of the operating system where PHP is executing. On Linux, it will be "\n"
; on Windows, it will be "\r\n"
.
An alternative to javax.comm
is the rxtx
library which supports more platforms than javax.comm
.
Just do a require('./yourfile.js');
Declare all the variables that you want outside access as global variables. So instead of
var a = "hello"
it will be
GLOBAL.a="hello"
or just
a = "hello"
This is obviously bad. You don't want to be polluting the global scope.
Instead the suggest method is to export
your functions/variables.
If you want the MVC pattern take a look at Geddy.