It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.
Using _blank
will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).
What Arne said - you can't reliably style select boxes and have them look anything like consistent across browsers.
Uniform: https://github.com/pixelmatrix/uniform is a javascript solution which gives you good graphic control over your form elements - it's still Javascript, but it's about as nice as javascript gets for solving this problem.
You'll need to store the old value manually. You could store it a lot of different ways. You could use a javascript object to store values for each textbox, or you could use a hidden field (I wouldn't recommend it - too html heavy), or you could use an expando property on the textbox itself, like this:
<input type="text" onfocus="this.oldvalue = this.value;" onchange="onChangeTest(this);this.oldvalue = this.value;" />
Then your javascript function to handle the change looks like this:
<script type="text/javascript">
function onChangeTest(textbox) {
alert("Value is " + textbox.value + "\n" + "Old Value is " + textbox.oldvalue);
}
</script>
I could do this on Linux.
$ pip3 install --user 'requests[socks]'
$ https_proxy=socks5://<hostname or ip>:<port> python3 -c \
> 'import requests;print(requests.get("https://httpbin.org/ip").text)'
To plot text on a ggplot
you use the geom_text
. But I find it helpful to summarise the data first using ddply
dfl <- ddply(df, .(x), summarize, y=length(x))
str(dfl)
Since the data is pre-summarized, you need to remember to change add the stat="identity"
parameter to geom_bar
:
ggplot(dfl, aes(x, y=y, fill=x)) + geom_bar(stat="identity") +
geom_text(aes(label=y), vjust=0) +
opts(axis.text.x=theme_blank(),
axis.ticks=theme_blank(),
axis.title.x=theme_blank(),
legend.title=theme_blank(),
axis.title.y=theme_blank()
)
This is the most elegant and clean way I've found so far:
list.stream().collect(Collectors.joining(delimiter));
For SDK 29 :
String str1 = "";
folder1 = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
if (folder1.exists()) {str1 = folder1.toString() + File.separator;}
public static void createTextFile(String sBody, String FileName, String Where) {
try {
File gpxfile = new File(Where, FileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then you can save your file like this :
createTextFile("This is Content","file.txt",str1);
The difference between those will depend largely on what browser you are currently referring to. Each one implements these properties differently, or not at all. Quirksmode has great documentation regarding browser differences in regards to W3C standards like the DOM and JavaScript Events.
I'm a big fan of hdf5 for storing large numpy arrays. There are two options for dealing with hdf5 in python:
Both are designed to work with numpy arrays efficiently.
If you only want to run the function given to useEffect
after the initial render, you can give it an empty array as second argument.
function MyComponent() {
useEffect(() => {
loadDataOnlyOnce();
}, []);
return <div> {/* ... */} </div>;
}
I would only recommend using @ to suppress warnings when it's a straight forward operation (e.g. $prop = @($high/($width - $depth)); to skip division by zero warnings). However in most cases it's better to handle.
You need to add an action
into your form like:
<form name='form1' method='post' action='<?php echo($_SERVER['PHP_SELF']);'>
<!-- All your input for the form here -->
</form>
Then put your snippet at the top of the document en send the mail. What echo($_SERVER['PHP_SELF']);
does is that it sends your information to the top of your script so you could use it.
Depending on which OS you're using, if you are flexible, then CHOICE
can be used to wait on almost any key EXCEPT
enter
If you are really referring to what Microsoft insists on calling "Command Prompt" which is simply an MS-DOS emulator, then perhaps TIMEOUT
may suit your purpose (timeout /t -1
waits on any key, not just ENTER
) and of course CHOICE
is available again in recent WIN editions.
And a warning on SET /P
- whereas set /p DUMMY=Hit ENTER to continue...
will work,
set "dummy="
set /p DUMMY=Hit ENTER to continue...
if defined dummy (echo not just ENTER was pressed) else (echo just ENTER was pressed)
will detect whether just ENTER or something else, ending in ENTER was keyed in.
Here's another way to do it: add a div
in your form with a classname dropzone, and implement dropzone programmatically.
HTML :
<div id="dZUpload" class="dropzone">
<div class="dz-default dz-message"></div>
</div>
JQuery:
$(document).ready(function () {
Dropzone.autoDiscover = false;
$("#dZUpload").dropzone({
url: "hn_SimpeFileUploader.ashx",
addRemoveLinks: true,
success: function (file, response) {
var imgName = response;
file.previewElement.classList.add("dz-success");
console.log("Successfully uploaded :" + imgName);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
}
});
});
Note : Disabling autoDiscover, otherwise Dropzone will try to attach twice
Blog Article : Dropzone js + Asp.net: Easy way to upload Bulk images
This is for bootstrap v4 compiled via grunt or some other task runner
You would need to change $table-hover-bg
to set the highlight on hover
$table-cell-padding: .75rem !default;
$table-sm-cell-padding: .3rem !default;
$table-bg: transparent !default;
$table-accent-bg: rgba(0,0,0,.05) !default;
$table-hover-bg: rgba(0,0,0,.075) !default;
$table-active-bg: $table-hover-bg !default;
$table-border-width: $border-width !default;
$table-border-color: $gray-lighter !default;
Does this work? Untested but should get the point across.
UPDATE FUNCTIONS
SET Func_TaxRef =
(
SELECT Min(TAX.Tax_Code) AS MinOfTax_Code
FROM TAX, FUNCTIONS F1
WHERE F1.Func_Pure <= [Tax_ToPrice]
AND F1.Func_Year=[Tax_Year]
AND F1.Func_ID = FUNCTIONS.Func_ID
GROUP BY F1.Func_ID;
)
Basically for each row in FUNCTIONS, the subquery determines the minimum current tax code and sets FUNCTIONS.Func_TaxRef to that value. This is assuming that FUNCTIONS.Func_ID is a Primary or Unique key.
What you want is Themes. They're important for a lot more than the AppBar color.
Remove the display:none
, and use ng-show
instead:
<ul class="procedures">
<li ng-repeat="procedure in procedures | filter:query | orderBy:orderProp">
<h4><a href="#" ng-click="showDetails = ! showDetails">{{procedure.definition}}</a></h4>
<div class="procedure-details" ng-show="showDetails">
<p>Number of patient discharges: {{procedure.discharges}}</p>
<p>Average amount covered by Medicare: {{procedure.covered}}</p>
<p>Average total payments: {{procedure.payments}}</p>
</div>
</li>
</ul>
Here's the fiddle: http://jsfiddle.net/asmKj/
You can also use ng-class
to toggle a class:
<div class="procedure-details" ng-class="{ 'hidden': ! showDetails }">
I like this more, since it allows you to do some nice transitions: http://jsfiddle.net/asmKj/1/
corona is nice. From the tutorial:
corona::Image* image = corona::OpenImage("img.jpg", corona::PF_R8G8B8A8);
if (!image) {
// error!
}
int width = image->getWidth();
int height = image->getHeight();
void* pixels = image->getPixels();
// we're guaranteed that the first eight bits of every pixel is red,
// the next eight bits is green, and so on...
typedef unsigned char byte;
byte* p = (byte*)pixels;
for (int i = 0; i < width * height; ++i) {
byte red = *p++;
byte green = *p++;
byte blue = *p++;
byte alpha = *p++;
}
pixels would be a one dimensional array, but you could easily convert a given x and y position to a position in a 1D array. Something like pos = (y * width) + x
Instead of
background-repeat-x: no-repeat;
background-repeat-y: no-repeat;
which is not correct, use
background-repeat: no-repeat;
In my case, I had the following structure of a project:
When I was running the test, I kept receiving problems with auro-wiring both facade and kafka attributes - error came back with information about missing instances, even though the test and the API classes reside in the very same package. Apparently those were not scanned.
What actually helped was adding @Import annotation bringing the missing classes to Spring classpath and making them being instantiated.
I know you asked how to disable console.log, but this might be what you're really after. This way you don't have to explicitly enable or disable the console. It simply prevents those pesky console errors for people who don't have it open or installed.
if(typeof(console) === 'undefined') {
var console = {};
console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
}
Add a $event
to the ng-click
, for example:
<button type="button" ng-click="saveOffer($event)" accesskey="S"></button>
Then the jQuery.Event
was passed to the callback:
Don't forget that you can also redirect constructors to other constructors at the same level of inheritance:
public Bar(int i, int j) : this(i) { ... }
^^^^^
While it is not free (but $39), FireDaemon has worked so well for me I have to recommend it. It will run your batch file but has loads of additional and very useful functionality such as scheduling, service up monitoring, GUI or XML based install of services, dependencies, environmental variables and log management.
I started out using FireDaemon to launch JBoss application servers (run.bat) but shortly after realized that the richness of the FireDaemon configuration abilities allowed me to ditch the batch file and recreate the intent of its commands in the FireDaemon service definition.
There's also a SUPER FireDaemon called Trinity which you might want to look at if you have a large number of Windows servers on which to manage this service (or technically, any service).
function url_exists($url) {
$headers = @get_headers($url);
return (strpos($headers[0],'200')===false)? false:true;
}
You can execute parallel jobs in Powershell 2 using Background Jobs. Check out Start-Job and the other job cmdlets.
# Loop through the server list
Get-Content "ServerList.txt" | %{
# Define what each job does
$ScriptBlock = {
param($pipelinePassIn)
Test-Path "\\$pipelinePassIn\c`$\Something"
Start-Sleep 60
}
# Execute the jobs in parallel
Start-Job $ScriptBlock -ArgumentList $_
}
Get-Job
# Wait for it all to complete
While (Get-Job -State "Running")
{
Start-Sleep 10
}
# Getting the information back from the jobs
Get-Job | Receive-Job
An example, available for POSIX compliant systems :
/*
* This program displays the names of all files in the current directory.
*/
#include <dirent.h>
#include <stdio.h>
int main(void) {
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}
Beware that such an operation is platform dependant in C.
Source : http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608
With introduction of ContraintLayout, it's possible to implement with Guidelines:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.eugene.test1.MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#AAA"
android:text="TextView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toTopOf="@+id/guideline" />
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5" />
</android.support.constraint.ConstraintLayout>
You can read more in this article Building interfaces with ConstraintLayout.
You can do something like this
SELECT IFNULL(`price`.`fPrice`,100) as fPrice,product.ProductId,ProductName
FROM `products` left join `price` ON
price.ProductId=product.ProductId AND (GeoFancingId=1 OR GeoFancingId
IS NULL) WHERE Status="Active" AND Delete="No"
We can also use Kotlin lambda
editText.setOnKeyListener { _, keyCode, keyEvent ->
if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
Log.d("Android view component", "Enter button was pressed")
return@setOnKeyListener true
}
return@setOnKeyListener false
}
If case anyone is looking for a regex that allows only numbers with an optional 2 decimal places
^\d*(\.\d{0,2})?$
For an example, I have found solution below to be fairly reliable
HTML:
<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />
JS / JQuery:
$(document).on('keydown', 'input[pattern]', function(e){
var input = $(this);
var oldVal = input.val();
var regex = new RegExp(input.attr('pattern'), 'g');
setTimeout(function(){
var newVal = input.val();
if(!regex.test(newVal)){
input.val(oldVal);
}
}, 0);
});
Update
setTimeout is not working correctly anymore for this, maybe browsers have changed. Some other async solution will need to be devised.
To add the latest solution for 2021...
I found that the project nanoid provides unique string ids that can be used as key while also being fast and very small.
After installing using npm install nanoid
, use as follows:
import { nanoid } from 'nanoid';
// Have the id associated with the data.
const todos = [{id: nanoid(), text: 'first todo'}];
// Then later, it can be rendered using a stable id as the key.
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
)
I had the hardest time with this error, because of my unique circumstances, but finally found a solution.
My situation: I am using a separate view (XML) which holds a WebView
, then opens in an AlertDialog
when I click a button in my main activity view. But somehow or another the WebView
belonged to the main activity view (probably because I pull the resource from here), so right before I assigned it to my AlertDialog
(as a view), I had to get the parent of my WebView
, put it into a ViewGroup
, then remove all the views on that ViewGroup
. This worked, and my error went away.
// set up Alert Dialog box
AlertDialog.Builder alert = new AlertDialog.Builder(this);
// inflate other xml where WebView is
LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.your_webview_layout, null);
final WebView webView = (WebView) v.findViewById(R.id.your_webview_id);
// more code...
.... later on after I loaded my WebView
....
// first, remove the parent of WebView from it's old parent so can be assigned a new one.
ViewGroup vg = (ViewGroup) webView.getParent();
vg.removeAllViews();
// put WebView in Dialog box
alert.setView(webView);
alert.show();
Choose & memorize 1 of the following!!! :)
[\s\S]*
[\w\W]*
[\d\D]*
Explanation:
\s
: whitespace \S
: not whitespace
\w
: word \W
: not word
\d
: digit \D
: not digit
(You can exchange the *
for +
if you want 1 or MORE characters [instead of 0 or more]).
BONUS EDIT:
If you want to match everything on a single line, you can use this:
[^\n]+
Explanation:
^
: not
\n
: linebreak
+
: for 1 character or more
You are initializing datatables twice, why?
// Take this off
/*
$(document).ready(function() {
$( '#example' ).dataTable();
} );
*/
$(document).ready( function() {
$( '#example' ).dataTable( {
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
// Bold the grade for all 'A' grade browsers
if ( aData[4] == "A" )
{
$('td:eq(4)', nRow).html( '<b>A</b>' );
}
}
} );
} );
you can render the page in express more easily
var app = require('express')();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.get('/signup',function(req,res){
res.sendFile(path.join(__dirname,'/signup.html'));
});
so if u request like http://127.0.0.1:8080/signup
that it will render signup.html page under views folder.
When a chip gets power all of it's registers contain random values. It's not possible to have an an initial value. It will always be random.
This is why we have reset signals, to reset registers to a known value. The reset is controlled by something off chip, and we write our code to use it.
always @(posedge clk) begin
if (reset == 1) begin // For an active high reset
data_reg = 8'b10101011;
end else begin
data_reg = next_data_reg;
end
end
You can use bit.ly api to create facebook short urls find the documentation here http://api.bitly.com
float currentSize = textEdit.getTextSize(); // default size
float newSize = currentSize * 2.0F; // new size is twice bigger than default one
textEdit.setTextSize(newSize);
If you want to get all the elements in the sequence pair wise, use this approach (the pairwise function is from the examples in the itertools module).
from itertools import tee, izip, chain
def pairwise(seq):
a,b = tee(seq)
b.next()
return izip(a,b)
for current_item, next_item in pairwise(y):
if compare(current_item, next_item):
# do what you have to do
If you need to compare the last value to some special value, chain that value to the end
for current, next_item in pairwise(chain(y, [None])):
I faced a similar situation:
I was trying to read raw response in case of an HTTP error consuming a SOAP service, using BasicHTTPBinding.
However, when reading the response using GetResponseStream()
, got the error:
Stream not readable
So, this code worked for me:
try
{
response = basicHTTPBindingClient.CallOperation(request);
}
catch (ProtocolException exception)
{
var webException = exception.InnerException as WebException;
var rawResponse = string.Empty;
var alreadyClosedStream = webException.Response.GetResponseStream() as MemoryStream;
using (var brandNewStream = new MemoryStream(alreadyClosedStream.ToArray()))
using (var reader = new StreamReader(brandNewStream))
rawResponse = reader.ReadToEnd();
}
The correct fix is to add the property in the type definition as explained in @Nitzan Tomer's answer. If that's not an option though:
You can assign the object to a constant of type any, then call the 'non-existing' property.
const newObj: any = oldObj;
return newObj.someProperty;
You can also cast it as any
:
return (oldObj as any).someProperty;
This fails to provide any type safety though, which is the point of TypeScript.
Another thing you may consider, if you're unable to modify the original type, is extending the type like so:
interface NewType extends OldType {
someProperty: string;
}
Now you can cast your variable as this NewType
instead of any
. Still not ideal but less permissive than any
, giving you more type safety.
return (oldObj as NewType).someProperty;
You can set the line size as per the width of the window and set wrap off using the following command.
set linesize 160;
set wrap off;
I have used 160 as per my preference you can set it to somewhere between 100 - 200
and setting wrap will not your data and it will display the data properly.
It is resolved using nodemailer-smtp-transport
module inside createTransport.
var smtpTransport = require('nodemailer-smtp-transport');
var transport = nodemailer.createTransport(smtpTransport({
service: 'gmail',
auth: {
user: '*******@gmail.com',
pass: '*****password'
}
}));
It looks like you're using the wrong tool there. Grep isn't that sophisticated, I think you want to step up to awk as the tool for the job:
awk '/blah/ { getline; print $0 }' logfile
If you get any problems let me know, I think its well worth learning a bit of awk, its a great tool :)
p.s. This example doesn't win a 'useless use of cat award' ;) http://porkmail.org/era/unix/award.html
It seems that now you can just mark the method parameter with @RequestParam
and it will do the job for you.
@PostMapping( "some/request/path" )
public void someControllerMethod( @RequestParam Map<String, String> body ) {
//work with Map
}
There are three options, that you can use. -I
is to exclude binary files in grep. Other are for line numbers and file names.
grep -I -n -H
-I -- process a binary file as if it did not contain matching data;
-n -- prefix each line of output with the 1-based line number within its input file
-H -- print the file name for each match
So this might be a way to run grep:
grep -InH your-word *
Inspired by PointZeroTwo's answer, here's a sample using NUnit and FakeItEasy.
SystemUnderTest
in this example is the class that you want to test - no sample content given for it but I assume you have that already!
[TestFixture]
public class HttpClientTests
{
private ISystemUnderTest _systemUnderTest;
private HttpMessageHandler _mockMessageHandler;
[SetUp]
public void Setup()
{
_mockMessageHandler = A.Fake<HttpMessageHandler>();
var httpClient = new HttpClient(_mockMessageHandler);
_systemUnderTest = new SystemUnderTest(httpClient);
}
[Test]
public void HttpError()
{
// Arrange
A.CallTo(_mockMessageHandler)
.Where(x => x.Method.Name == "SendAsync")
.WithReturnType<Task<HttpResponseMessage>>()
.Returns(Task.FromResult(new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent("abcd")
}));
// Act
var result = _systemUnderTest.DoSomething();
// Assert
// Assert.AreEqual(...);
}
}
If you have only one level and you use bootstrap 3 add pull-right
to the ul
element
<ul class="dropdown-menu pull-right" role="menu">
A bit verbose, but it's the standard way of parsing and formatting dates in Java:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
Date dt = formatter.parse("08:19:12");
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
} catch (ParseException e) {
// This can happen if you are trying to parse an invalid date, e.g., 25:19:12.
// Here, you should log the error and decide what to do next
e.printStackTrace();
}
If you want to be relax for installing libraries for python.
You should using pip
, that is python installer package.
To install pip:
Download ez_setup.py and then run:
python ez_setup.py
Then download get-pip.py and run:
python get-pip.py
upgrade installed setuptools
by pip:
pip install setuptools --upgrade
If you got this error:
Wheel installs require setuptools >= 0.8 for dist-info support.
pip's wheel support requires setuptools >= 0.8 for dist-info support.
Add --no-use-wheel
to above cmd:
pip install setuptools --no-use-wheel --upgrade
Now, you can install libraries for python, just by:
pip install library_name
For example:
pip install requests
Note that to install some library may they need to compile, so you need to have compiler.
On windows there is a site for Unofficial Windows Binaries for Python Extension Packages that have huge python packages and complied python packages for windows.
For example to install pip
using this site, just download and install setuptools and pip installer from that.
While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.
This can be resolved by specifying a primary key on the @new_super table, as follows:
DECLARE @new_super TABLE (
row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
super_id int
);
This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.
A MemoryStream can be helpful for this. You could put it in an extension method:
public static class ImageExtensions
{
public static byte[] ToByteArray(this Image image, ImageFormat format)
{
using(MemoryStream ms = new MemoryStream())
{
image.Save(ms, format);
return ms.ToArray();
}
}
}
You could just use it like:
var image = new Bitmap(10, 10);
// Draw your image
byte[] arr = image.ToByteArray(ImageFormat.Bmp);
I partially disagree with prestomanifto's answer in regards to the ImageConverter. Do not use ImageConverter. There's nothing technically wrong with it, but simply the fact that it uses boxing/unboxing from object tells me it's code from the old dark places of the .NET framework and its not ideal to use with image processing (it's overkill for converting to a byte[] at least), especially when you consider the following.
I took a look at the ImageConverter
code used by the .Net framework, and internally it uses code almost identical to the one I provided above. It creates a new MemoryStream
, saves the Bitmap
in whatever format it was in when you provided it, and returns the array. Skip the extra overhead of creating an ImageConverter
class by using MemoryStream
You should be able to put them in your ~/matlab on unix.
I'm not sure which directory matlab looks in for windows, but you should be able to figure it out by executing userpath
from the matlab command line.
I just created some directories, shared them and mapped using:
net use y: "\\mycomputername\folder with spaces"
So this solution gets "works on my machine" certificate. What error code do you get?
Technically, and from Comintern's accepted workaround,
I believe you actually want to Delete all the Cells in the Sheet. Which removes Formatting (See footnote for exceptions), etc. as well as the Cells Contents.
I.e. Sheets("Zeroes").Cells.Delete
Combined also with UsedRange, ScreenUpdating and Calculation skipping it should be nearly intantaneous:
Sub DeleteCells ()
Application.Calculation = XlManual
Application.ScreenUpdating = False
Sheets("Zeroes").UsedRange.Delete
Application.ScreenUpdating = True
Application.Calculation = xlAutomatic
End Sub
Or if you prefer to respect the Calculation State Excel is currently in:
Sub DeleteCells ()
Dim SaveCalcState
SaveCalcState = Application.Calculation
Application.Calculation = XlManual
Application.ScreenUpdating = False
Sheets("Zeroes").UsedRange.Delete
Application.ScreenUpdating = True
Application.Calculation = SaveCalcState
End Sub
Footnote: If formatting was applied for an Entire Column, then it is not deleted. This includes Font Colour, Fill Colour and Borders, the Format Category (like General, Date, Text, Etc.) and perhaps other properties too, but
Conditional formatting IS deleted, as is Entire Row formatting.
(Entire Column formatting is quite useful if you are importing raw data repeatedly to a sheet as it will conform to the Formats originally applied if a simple Paste-Values-Only type import is done.)
byte test[] = new byte[3];
test[0] = 0x0A;
test[1] = 0xFF;
test[2] = 0x01;
for (byte theByte : test)
{
System.out.println(Integer.toHexString(theByte));
}
NOTE: test[1] = 0xFF; this wont compile, you cant put 255 (FF) into a byte, java will want to use an int.
you might be able to do...
test[1] = (byte) 0xFF;
I'd test if I was near my IDE (if I was near my IDE I wouln't be on Stackoverflow)
DEVENV works well in many cases, but on a WIXPROJ to build my WIX installer, all I got is "CATASTROPHIC" error in the Out log.
This works: MSBUILD /Path/PROJECT.WIXPROJ /t:Build /p:Configuration=Release
In order to encode +
value using JavaScript, you can use encodeURIComponent
function.
Example:
var url = "+11";
var encoded_url = encodeURIComponent(url);
console.log(encoded_url)
_x000D_
Is it really worth it? Every protection mechanism can be broken with sufficient determination. Consider your market, price of the product, amount of customers, etc.
If you want something more reliable then go down the path of hardware keys, but that's rather troublesome (for the user) and more expensive. Software solutions would be probably a waste of time and resources, and the only thing they would give you is the false sense of 'security'.
Few more ideas (none is perfect, as there is no perfect one).
And don't waste too much time on it, because the crackers have a lot of experience with the typical techniques and are few steps ahead of you. Unless you want to use a lot of resources, probably change the programming language (do it the Skype way).
For Jenkins 2.121.3 version, Go to Manage jenkins -> Global tool configuration -> Git installations -> Path to Git executable: C:\Program Files\Git\bin\git.exe It works!
In Jenkins, give the http URL. SSH URL shows similar error.
I have just compile it and it compiles fine without the implicit import, probably you're seeing a stale cache or something of your IDE.
Have you tried compiling from the command line?
I have the exact same version:
Probably you're thinking the warning is an error.
UPDATE
It looks like you have a Arrays.class
file in the directory where you're trying to compile ( probably created before ). That's why the explicit import solves the problem. Try copying your source code to a clean new directory and try again. You'll see there is no error this time. Or, clean up your working directory and remove the Arrays.class
The >>
redirection operator will append lines to the end of the specified file, where-as the single greater than >
will empty and overwrite the file.
echo "text" > 'Users/Name/Desktop/TheAccount.txt'
This is another example using defined column/table names.
DELETE FROM jos_jomres_gdpr_optins WHERE `date_time` < '2020-10-21 08:21:22';
This worked for for me: getResources().openRawResource(R.raw.certificate)
first create database name "School" than create table "students" with following columns 1. id 2. name 3. address
now open visual studio and create connection:
namespace school { public partial class Form1 : Form { SqlConnection scon; public Form1() { InitializeComponent(); scon = new SqlConnection("Data Source = ABC-PC; trusted_connection = yes; Database = school; connection timeout = 30"); } //create command SqlCommand scom = new SqlCommand("insert into students (id,name,address) values(@id,@name,@address)", scon); //pass parameters scom.Parameters.Add("id", SqlDbType.Int); scom.Parameters["id"].Value = textBox1.Text; scom.Parameters.Add("name", SqlDbType.VarChar); scom.Parameters["name"].Value = this.textBox2.Text; scom.Parameters.Add("address", SqlDbType.VarChar); scom.Parameters["address"].Value = this.textBox6.Text; scon.Open(); scom.ExecuteNonQuery(); scon.Close(); reset(); }
also check solution here: http://solutions.musanitech.com/?p=6
in order to center the canvas within the window +"px" should be added to el.style.top
and el.style.left
.
el.style.top = (viewportHeight - canvasHeight) / 2 +"px";
el.style.left = (viewportWidth - canvasWidth) / 2 +"px";
[Range(0.01,100000000,ErrorMessage = "Price must be greter than zero !")]
Use the AutoSize and AutoSizeMode properties.
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.autosize.aspx
An example:
private void Form1_Load(object sender, EventArgs e)
{
// no smaller than design time size
this.MinimumSize = new System.Drawing.Size(this.Width, this.Height);
// no larger than screen size
this.MaximumSize = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, (int)System.Windows.SystemParameters.PrimaryScreenHeight);
this.AutoSize = true;
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
// rest of your code here...
}
If you've to support IE7, a more compatible solution is:
/* only the cells with no cell before (aka the first one) */
td {
padding-left: 20px;
}
/* only the cells with at least one cell before (aka all except the first one) */
td + td {
padding-left: 0;
}
Also works fine with li
; general sibling selector ~
may be more suitable with mixed elements like a heading h1 followed by paragraphs AND a subheading and then again other paragraphs.
I’ve recently come to this issue again and wrote the following category on NSObject
:
@implementation NSObject (Testing)
- (void) performSelector: (SEL) selector
withBlockingCallback: (dispatch_block_t) block
{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self performSelector:selector withObject:^{
if (block) block();
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_release(semaphore);
}
@end
This way I can easily turn asynchronous call with a callback into a synchronous one in tests:
[testedObject performSelector:@selector(longAsyncOpWithCallback:)
withBlockingCallback:^{
STAssert…
}];
Although the accepted answer is correct but if you are just trying to upload your image to cloudinary, there's a better way:
Map upload = cloudinary.uploader().upload(multipartFile.getBytes(), ObjectUtils.emptyMap());
Where multipartFile is your org.springframework.web.multipart.MultipartFile.
In my case this format worked on latest version of jQuery:
$('img#post_image_preview').src;
Assgining a value that starts with a "=" will kick in formula evaluation and gave in my case the above mentioned error #1004. Prepending it with a space was the ticket for me.
You also can use
start /MIN notepad.exe
PS: Unfortunatly, minimized window status depends on command to run. V.G. doen't work
start /MIN calc.exe
I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick
event handler for the radio buttons:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var ex1 = document.getElementById('example1');
var ex2 = document.getElementById('example2');
var ex3 = document.getElementById('example3');
ex1.onclick = handler;
ex2.onclick = handler;
ex3.onclick = handler;
}
function handler() {
alert('clicked');
}
</script>
</head>
<body>
<input type="radio" name="example1" id="example1" value="Example 1" />
<label for="example1">Example 1</label>
<input type="radio" name="example2" id="example2" value="Example 2" />
<label for="example1">Example 2</label>
<input type="radio" name="example3" id="example3" value="Example 3" />
<label for="example1">Example 3</label>
</body>
</html>
Here is what worked for me. It applies the same height to each column despite their parent div.
$(document).ready(function () {
var $sameHeightDivs = $('.column');
var maxHeight = 0;
$sameHeightDivs.each(function() {
maxHeight = Math.max(maxHeight, $(this).outerHeight());
});
$sameHeightDivs.css({ height: maxHeight + 'px' });
});
You can never check and see if a process is running, you can only check to see if a process was running at some point in the recent past. A process is an entity that is not controlled by your application and can exit at any moment in time. There is no way to guaranteed that a process will not exit in between the check to see if it's running and the corresponding action.
The best approach is to just do the action required and catch the exception that would be thrown if the process was not running.
Simple way:
System.out.println(java.lang.String.class.getResource(String.class.getSimpleName()+".class"));
Out Example:
jar:file:/D:/Java/jdk1.8/jre/lib/rt.jar!/java/lang/String.class
Or
String obj = "simple test"; System.out.println(obj.getClass().getResource(obj.getClass().getSimpleName()+".class"));
Out Example:
jar:file:/D:/Java/jdk1.8/jre/lib/rt.jar!/java/lang/String.class
For adding zeros I really don't see the need to have a full other function where you can simply use for example
var mins=Math.floor(StrTime/60);
var secs=StrTime-mins * 60;
var hrs=Math.floor(StrTime / 3600);
RoundTime.innerHTML=(hrs>9?hrs:"0"+hrs) + ":" + (mins>9?mins:"0"+mins) + ":" + (secs>9?secs:"0"+secs);
Its why we have conditional statements in the first place.
(condition?if true:if false) so if example seconds is more than 9 than just show seconds else add a string 0 before it.
Just use the name of the main folder which the .py file is in.
from problem_set_02.p_02_paying_debt_off_in_a_year import compute_balance_after
As others have said, you do not need internet for GPS.
GPS is basically a satellite based positioning system that is designed to calculate geographic coordinates based on timing information received from multiple satellites in the GPS constellation. GPS has a relatively slow time to first fix (TTFF), and from a cold start (meaning without a last known position), it can take up to 15 minutes to download the data it needs from the satellites to calculate a position. A-GPS used by cellular networks shortens this time by using the cellular network to deliver the satellite data to the phone.
But regardless of whether it is an A-GPS or GPS location, all that is derived is Geographic Coordinates (latitude/longitude). It is impossible to obtain more from GPS only.
To be able to return anything other than coordinates (such as an address), you need some mechanism to do Reverse Geocoding. Typically this is done by querying a server or a web service (like using Google Maps or Bing Maps, but there are others). Some of the services will allow you to cache data locally, but it would still require an internet connection for periods of time to download the map information in the surrounding area.
While it requires a significant amount of effort, you can write your own tool to do the reverse geocoding, but you still need to be able to house the data somewhere as the amount of data required to do this is far more you can store on a phone, which means you still need an internet connection to do it. If you think of tools like Garmin GPS Navigation units, they do store the data locally, so it is possible, but you will need to optimize it for maximum storage and would probably need more than is generally available in a phone.
The short answer to your question is, no you do not need an active internet connection to get coordinates, but unless you are building a specialized device or have unlimited storage, you will need an internet connection to turn those coordinates into anything else.
You should add reference to PresentationCore.dll.
In case of this similar error Warning: Error in $: object of type 'closure' is not subsettable [No stack trace available]
Just add corresponding package name using :: e.g.
instead of tags(....)
write shiny::tags(....)
Numpy has a convenience function, np.fft.fftfreq
to compute the frequencies associated with FFT components:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(301) - 0.5
ps = np.abs(np.fft.fft(data))**2
time_step = 1 / 30
freqs = np.fft.fftfreq(data.size, time_step)
idx = np.argsort(freqs)
plt.plot(freqs[idx], ps[idx])
Note that the largest frequency you see in your case is not 30 Hz, but
In [7]: max(freqs)
Out[7]: 14.950166112956811
You never see the sampling frequency in a power spectrum. If you had had an even number of samples, then you would have reached the Nyquist frequency, 15 Hz in your case (although numpy would have calculated it as -15).
Anytime we create a timeout we should s clear it on componentWillUnmount, if it hasn't fired yet.
let myVar;
const Component = React.createClass({
getInitialState: function () {
return {position: 0};
},
componentDidMount: function () {
myVar = setTimeout(()=> this.setState({position: 1}), 3000)
},
componentWillUnmount: () => {
clearTimeout(myVar);
};
render: function () {
return (
<div className="component">
{this.state.position}
</div>
);
}
});
ReactDOM.render(
<Component />,
document.getElementById('main')
);
Shelving is like your changes have been stored in the source control without affecting the existing changes. Means if you check in a file in source control it will modify the existing file but shelving is like storing your changes in source control but without modifying the actual changes.
Pattern.compile()
allow to reuse a regex multiple times (it is threadsafe). The performance benefit can be quite significant.
I did a quick benchmark:
@Test
public void recompile() {
var before = Instant.now();
for (int i = 0; i < 1_000_000; i++) {
Pattern.compile("ab").matcher("abcde").matches();
}
System.out.println("recompile " + Duration.between(before, Instant.now()));
}
@Test
public void compileOnce() {
var pattern = Pattern.compile("ab");
var before = Instant.now();
for (int i = 0; i < 1_000_000; i++) {
pattern.matcher("abcde").matches();
}
System.out.println("compile once " + Duration.between(before, Instant.now()));
}
compileOnce was between 3x and 4x faster.
I guess it highly depends on the regex itself but for a regex that is often used, I go for a static Pattern pattern = Pattern.compile(...)
If you want to table do following steps:-
views.py:
def view_info(request):
objs=Model_name.objects.all()
............
return render(request,'template_name',{'objs':obj})
.html page
{% for item in objs %}
<tr>
<td>{{ item.field1 }}</td>
<td>{{ item.field2 }}</td>
<td>{{ item.field3 }}</td>
<td>{{ item.field4 }}</td>
</tr>
{% endfor %}
I could not get the example working using the resizeMode
properties of Image
, but because the images will all be square there is a way to do it using the Dimensions of the window along with flexbox.
Set flexDirection: 'row'
, and flexWrap: 'wrap'
, then they will all line up as long as they are all the same dimensions.
I set it up here
https://snack.expo.io/HkbZNqjeZ
"use strict";
var React = require("react-native");
var {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
Dimensions,
ScrollView
} = React;
var deviceWidth = Dimensions.get("window").width;
var temp = "http://thumbs.dreamstime.com/z/close-up-angry-chihuahua-growling-2-years-old-15126199.jpg";
var SampleApp = React.createClass({
render: function() {
var images = [];
for (var i = 0; i < 10; i++) {
images.push(
<TouchableOpacity key={i} activeOpacity={0.75} style={styles.item}>
<Image style={styles.image} source={{ uri: temp }} />
</TouchableOpacity>
);
}
return (
<ScrollView style={{ flex: 1 }}>
<View style={styles.container}>
{images}
</View>
</ScrollView>
);
}
});
The column in the database is probably a DECIMAL
. You should process it as a BigInteger
, not an Integer
, otherwise you are losing digits. Or else change the column to int
.
Please check this example here: Accessing Structure Members
There is explained that the right way to do it is like this:
strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);
Unexpected end of input means that the parser has ended prematurely. For example, it might be expecting "abcd...wxyz"
but only sees "abcd...wxy
.
This can be a typo error somewhere, or it could be a problem you get when encodings are mixed across different parts of the application.
One example: consider you are receiving data from a native app using chrome.runtime.sendNativeMessage
:
chrome.runtime.sendNativeMessage('appname', {toJSON:()=>{return msg}}, (data)=>{
console.log(data);
});
Now before your callback is called, the browser would attempt to parse the message using JSON.parse
which can give you "unexpected end of input" errors if the supplied byte length does not match the data.
yourbox{
position:absolute;
right:<x>px;
top :<x>px;
}
positions it in the right corner. Note, that the position is dependent of the first ancestor-element which is not static
positioned!
EDIT:
You can follow this, more readable, not expectation raise due to key not found :
data.map((datum)=>{
return {
'id':datum.id,
'title':datum.login,
}
var classname=$('#div1').attr('class')
Try css:
.topcorner{
position:absolute;
top:10px;
right: 10px;
}
you can play with the top
and right
properties.
If you want to float the div
even when you scroll down, just change position:absolute;
to position:fixed;
.
Hope it helps.
Use JQuery keydown event.
$(document).keypress(function(){
if(event.which == 70){ //f
console.log("You have payed respect");
}
});
In JS; keyboard keys are identified by Javascript keycodes
EXEC sp_helpuser
or
SELECT * FROM sysusers
Both of these select all the users of the current database (not the server).
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).
With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615;
With one argument, the value specifies the number of rows to return from the beginning of the result set:
SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows
In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.
I actually did a console.log() for the second parameter in the callback function for insert. There is actually a lot of information returned apart from the inserted object itself. So the code below explains how you can access it's id.
collection.insert(objToInsert, function (err, result){
if(err)console.log(err);
else {
console.log(result["ops"][0]["_id"]);
// The above statement will output the id of the
// inserted object
}
});
First get the position of the div element upto which u want to scroll by jQuery position() method.
Example : var pos = $("div").position();
Then get the y cordinates (height) of that element with ".top" method.
Example : pos.top;
Then get the x cordinates of the that div element with ".left" method.
These methods are originated from CSS positioning.
Once we get x & y cordinates, then we can use javascript's scrollTo(); method.
This method scrolls the document upto specific height & width.
It takes two parameters as x & y cordinates. Syntax : window.scrollTo(x,y);
Then just pass the x & y cordinates of the DIV element in the scrollTo() function.
Refer the example below ↓ ↓
<!DOCTYPE HTML>
<html>
<head>
<title>
Scroll upto Div with jQuery.
</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#button1").click(function () {
var x = $("#element").position(); //gets the position of the div element...
window.scrollTo(x.left, x.top); //window.scrollTo() scrolls the page upto certain position....
//it takes 2 parameters : (x axis cordinate, y axis cordinate);
});
});
</script>
</head>
<body>
<button id="button1">
Click here to scroll
</button>
<div id="element" style="position:absolute;top:200%;left:0%;background-color:orange;height:100px;width:200px;">
The DIV element.
</div>
</body>
</html>
ul > li > a
selects only the direct children. In this case only the first level <a>
of the first level <li>
inside the <ul>
will be selected.
ul li a
on the other hand will select ALL <a>
-s in ALL <li>
-s in the unordered list
Example of ul > li
ul > li.bg {_x000D_
background: red;_x000D_
}
_x000D_
<ul>_x000D_
<li class="bg">affected</li>_x000D_
<li class="bg">affected</li> _x000D_
<li>_x000D_
<ol>_x000D_
<li class="bg">NOT affected</li>_x000D_
<li class="bg">NOT affected</li>_x000D_
</ol>_x000D_
</li>_x000D_
</ul>
_x000D_
if you'd be using ul li
- ALL of the li
-s would be affected
UPDATE The order of more to less efficient CSS selectors goes thus:
#header
.promo
div
h2 + p
li > ul
ul a
*
[type="text"]
a:hover
So your better bet is to use the children
selector instead of just descendant
. However the difference on a regular page (without tens of thousands elements to go through) might be absolutely negligible.
Check target-membership of PrimeNumberModel.swift in your testing target.
The cleanest way for you to accomplish this is to use the enumitem package (https://ctan.org/pkg/enumitem). For example,
\documentclass{article}
\usepackage{enumitem}% http://ctan.org/pkg/enumitem
\begin{document}
\noindent Here is some text and I want to make sure
there is no spacing the different items.
\begin{itemize}[noitemsep]
\item Item 1
\item Item 2
\item Item 3
\end{itemize}
\noindent Here is some text and I want to make sure
there is no spacing between this line and the item
list below it.
\begin{itemize}[noitemsep,topsep=0pt]
\item Item 1
\item Item 2
\item Item 3
\end{itemize}
\end{document}
Furthermore, if you want to use this setting globally across lists, you can use
\usepackage{enumitem}% http://ctan.org/pkg/enumitem
\setlist[itemize]{noitemsep, topsep=0pt}
However, note that this package does not work well with the beamer package which is used to make presentations in Latex.
Here is another construction which starts with the simplest number format and then, in a non-overlapping way, progressively adds more complex number formats:
Java regep:
(\d)|([1-9]\d+)|(\.\d+)|(\d\.\d*)|([1-9]\d+\.\d*)|([1-9]\d{0,2}(,\d{3})+(\.\d*)?)
As a Java String (note the extra \ needed to escape to \ and . since \ and . have special meaning in a regexp when on their own):
String myregexp="(\\d)|([1-9]\\d+)|(\\.\\d+)|(\\d\\.\\d*)|([1-9]\\d+\\.\\d*)|([1-9]\\d{0,2}(,\\d{3})+(\\.\\d*)?)";
Explanation:
This regexp has the form A|B|C|D|E|F where A,B,C,D,E,F are themselves regexps that do not overlap. Generally, I find it easier to start with the simplest possible matches, A. If A misses matches you want, then create a B that is a minor modification of A and includes a bit more of what you want. Then, based on B, create a C that catches more, etc. I also find it easier to create regexps that don't overlap; it is easier to understand a regexp with 20 simple non-overlapping regexps connected with ORs rather than a few regexps with more complex matching. But, each to their own!
A is (\d) and matches exactly one of 0,1,2,3,4,5,6,7,8,9 which can't be simpler!
B is ([1-9]\d+) and only matches numbers with 2 or more digits, the first excluding 0 . B matches exactly one of 10,11,12,... B does not overlap A but is a small modification of A.
C is (.\d+) and only matches a decimal followed by one or more digits. C matches exactly one of .0 .1 .2 .3 .4 .5 .6 .7 .8 .9 .00 .01 .02 ... . .23000 ... C allows trailing eros on the right which I prefer: if this is measurement data, the number of trailing zeros indicates the level of precision. If you don't want the trailing zeros on the right, change (.\d+) to (.\d*[1-9]) but this also excludes .0 which I think should be allowed. C is also a small modification of A.
D is (\d.\d*) which is A plus decimals with trailing zeros on the right. D only matches a single digit, followed by a decimal, followed by zero or more digits. D matches 0. 0.0 0.1 0.2 ....0.01000...9. 9.0 9.1..0.0230000 .... 9.9999999999... If you want to exclude "0." then change D to (\d.\d+). If you want to exclude trailing zeros on the right, change D to (\d.\d*[1-9]) but this excludes 2.0 which I think should be included. D does not overlap A,B,or C.
E is ([1-9]\d+.\d*) which is B plus decimals with trailing zeros on the right. If you want to exclude "13.", for example, then change E to ([1-9]\d+.\d+). E does not overlap A,B,C or D. E matches 10. 10.0 10.0100 .... 99.9999999999... Trailing zeros can be handled as in 4. and 5.
F is ([1-9]\d{0,2}(,\d{3})+(.\d*)?) and only matches numbers with commas and possibly decimals allowing trailing zeros on the right. The first group ([1-9]\d{0,2}) matches a non-zero digit followed zero, one or two more digits. The second group (,\d{3})+ matches a 4 character group (a comma followed by exactly three digits) and this group can match one or more times (no matches means no commas!). Finally, (.\d*)? matches nothing, or matches . by itself, or matches a decimal . followed by any number of digits, possibly none. Again, to exclude things like "1,111.", change (.\d*) to (.\d+). Trailing zeros can be handled as in 4. or 5. F does not overlap A,B,C,D, or E. I couldn't think of an easier regexp for F.
Let me know if you are interested and I can edit above to handle the trailing zeros on the right as desired.
Here is what matches regexp and what does not:
0
1
02 <- invalid
20
22
003 <- invalid
030 <- invalid
300
033 <- invalid
303
330
333
0004 <- invalid
0040 <- invalid
0400 <- invalid
4000
0044 <- invalid
0404 <- invalid
0440 <- invalid
4004
4040
4400
0444 <- invalid
4044
4404
4440
4444
00005 <- invalid
00050 <- invalid
00500 <- invalid
05000 <- invalid
50000
00055 <- invalid
00505 <- invalid
00550 <- invalid
05050 <- invalid
05500 <- invalid
50500
55000
00555 <- invalid
05055 <- invalid
05505 <- invalid
05550 <- invalid
50550
55050
55500
. <- invalid
.. <- invalid
.0
0.
.1
1.
.00
0.0
00. <- invalid
.02
0.2
02. <- invalid
.20
2.0
20.
.22
2.2
22.
.000
0.00
00.0 <- invalid
000. <- invalid
.003
0.03
00.3 <- invalid
003. <- invalid
.030
0.30
03.0 <- invalid
030. <- invalid
.033
0.33
03.3 <- invalid
033. <- invalid
.303
3.03
30.3
303.
.333
3.33
33.3
333.
.0000
0.000
00.00 <- invalid
000.0 <- invalid
0000. <- invalid
.0004
0.0004
00.04 <- invalid
000.4 <- invalid
0004. <- invalid
.0044
0.044
00.44 <- invalid
004.4 <- invalid
0044. <- invalid
.0404
0.404
04.04 <- invalid
040.4 <- invalid
0404. <- invalid
.0444
0.444
04.44 <- invalid
044.4 <- invalid
0444. <- invalid
.4444
4.444
44.44
444.4
4444.
.00000
0.0000
00.000 <- invalid
000.00 <- invalid
0000.0 <- invalid
00000. <- invalid
.00005
0.0005
00.005 <- invalid
000.05 <- invalid
0000.5 <- invalid
00005. <- invalid
.00055
0.0055
00.055 <- invalid
000.55 <- invalid
0005.5 <- invalid
00055. <- invalid
.00505
0.0505
00.505 <- invalid
005.05 <- invalid
0050.5 <- invalid
00505. <- invalid
.00550
0.0550
00.550 <- invalid
005.50 <- invalid
0055.0 <- invalid
00550. <- invalid
.05050
0.5050
05.050 <- invalid
050.50 <- invalid
0505.0 <- invalid
05050. <- invalid
.05500
0.5500
05.500 <- invalid
055.00 <- invalid
0550.0 <- invalid
05500. <- invalid
.50500
5.0500
50.500
505.00
5050.0
50500.
.55000
5.5000
55.000
550.00
5500.0
55000.
.00555
0.0555
00.555 <- invalid
005.55 <- invalid
0055.5 <- invalid
00555. <- invalid
.05055
0.5055
05.055 <- invalid
050.55 <- invalid
0505.5 <- invalid
05055. <- invalid
.05505
0.5505
05.505 <- invalid
055.05 <- invalid
0550.5 <- invalid
05505. <- invalid
.05550
0.5550
05.550 <- invalid
055.50 <- invalid
0555.0 <- invalid
05550. <- invalid
.50550
5.0550
50.550
505.50
5055.0
50550.
.55050
5.5050
55.050
550.50
5505.0
55050.
.55500
5.5500
55.500
555.00
5550.0
55500.
.05555
0.5555
05.555 <- invalid
055.55 <- invalid
0555.5 <- invalid
05555. <- invalid
.50555
5.0555
50.555
505.55
5055.5
50555.
.55055
5.5055
55.055
550.55
5505.5
55055.
.55505
5.5505
55.505
555.05
5550.5
55505.
.55550
5.5550
55.550
555.50
5555.0
55550.
.55555
5.5555
55.555
555.55
5555.5
55555.
, <- invalid
,, <- invalid
1, <- invalid
,1 <- invalid
22, <- invalid
2,2 <- invalid
,22 <- invalid
2,2, <- invalid
2,2, <- invalid
,22, <- invalid
333, <- invalid
33,3 <- invalid
3,33 <- invalid
,333 <- invalid
3,33, <- invalid
3,3,3 <- invalid
3,,33 <- invalid
,,333 <- invalid
4444, <- invalid
444,4 <- invalid
44,44 <- invalid
4,444
,4444 <- invalid
55555, <- invalid
5555,5 <- invalid
555,55 <- invalid
55,555
5,5555 <- invalid
,55555 <- invalid
666666, <- invalid
66666,6 <- invalid
6666,66 <- invalid
666,666
66,6666 <- invalid
6,66666 <- invalid
66,66,66 <- invalid
6,66,666 <- invalid
,666,666 <- invalid
1,111.
1,111.11
1,111.110
01,111.110 <- invalid
0,111.100 <- invalid
11,11. <- invalid
1,111,.11 <- invalid
1111.1,10 <- invalid
01111.11,0 <- invalid
0111.100, <- invalid
1,111,111.
1,111,111.11
1,111,111.110
01,111,111.110 <- invalid
0,111,111.100 <- invalid
1,111,111.
1,1111,11.11 <- invalid
11,111,11.110 <- invalid
01,11,1111.110 <- invalid
0,111111.100 <- invalid
0002,22.2230 <- invalid
.,5.,., <- invalid
2.0,345,345 <- invalid
2.334.456 <- invalid
in bootstrap 3.3.7 (and 4.0 presumably), this works:
instead of:
<nav class="navbar navbar-inverse navbar-fixed-top">
use:
<nav class="navbar bg-transparent navbar-fixed-top">
no CSS required!
Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .
*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*
So error is raised..
Please refere sample script:
DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)
insert into #temp1 values(@id)
Select * from #temp1
Drop Table #temp1
I was facing the same issue, I was adding
"types": ["node"]
to tsconfig.json of root folder.
There was one more tsconfig.app.json under src folder and I got solved this by adding
"types": ["node"]
to tsconfig.app.json file under compilerOptions
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": ["node"] ----------------------< added node to the array
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}
Addressing cases that some of the other answers don't handle well:
Many of the solutions on this page involve polling Console.KeyAvailable
or blocking on Console.ReadKey
. While it's true that the .NET Console
is not very cooperative here, you can use Task.Run
to move towards a more modern Async
mode of listening.
The main issue to be aware of is that, by default, your console thread isn't set up for Async
operation--meaning that, when you fall out of the bottom of your main
function, instead of awaiting Async
completions, your AppDoman and process will end. A proper way to address this would be to use Stephen Cleary's AsyncContext to establish full Async
support in your single-threaded console program. But for simpler cases, like waiting for a keypress, installing a full trampoline may be overkill.
The example below would be for a console program used in some kind of iterative batch file. In this case, when the program is done with its work, normally it should exit without requiring a keypress, and then we allow an optional key press to prevent the app from exiting. We can pause the cycle to examine things, possibly resuming, or use the pause as a known 'control point' at which to cleanly break out of the batch file.
static void Main(String[] args)
{
Console.WriteLine("Press any key to prevent exit...");
var tHold = Task.Run(() => Console.ReadKey(true));
// ... do your console app activity ...
if (tHold.IsCompleted)
{
#if false // For the 'hold' state, you can simply halt forever...
Console.WriteLine("Holding.");
Thread.Sleep(Timeout.Infinite);
#else // ...or allow continuing to exit
while (Console.KeyAvailable)
Console.ReadKey(true); // flush/consume any extras
Console.WriteLine("Holding. Press 'Esc' to exit.");
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
;
#endif
}
}
Now (2020) NetBeans 11 does it automatically with the "Build" command (right click on the project's name and choose "Build")
You can use any
function, with the str.isdigit
function, like this
>>> def hasNumbers(inputString):
... return any(char.isdigit() for char in inputString)
...
>>> hasNumbers("I own 1 dog")
True
>>> hasNumbers("I own no dog")
False
Alternatively you can use a Regular Expression, like this
>>> import re
>>> def hasNumbers(inputString):
... return bool(re.search(r'\d', inputString))
...
>>> hasNumbers("I own 1 dog")
True
>>> hasNumbers("I own no dog")
False
The full list of the 66 unreserved characters is in RFC3986, here: http://tools.ietf.org/html/rfc3986#section-2.3
This is any character in the following regex set:
[A-Za-z0-9_.\-~]
You can use SRV records:
_service._proto.name. TTL class SRV priority weight port target.
Service: the symbolic name of the desired service.
Proto: the transport protocol of the desired service; this is usually either TCP or UDP.
Name: the domain name for which this record is valid, ending in a dot.
TTL: standard DNS time to live field.
Class: standard DNS class field (this is always IN).
Priority: the priority of the target host, lower value means more preferred.
Weight: A relative weight for records with the same priority.
Port: the TCP or UDP port on which the service is to be found.
Target: the canonical hostname of the machine providing the service, ending in a dot.
Example:
_sip._tcp.example.com. 86400 IN SRV 0 5 5060 sipserver.example.com.
So what I think you're looking for is to add something like this to your DNS hosts file:
_sip._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25566 tekkit.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25567 pvp.arboristal.com.
On a side note, I highly recommend you go with a hosting company rather than hosting the servers yourself. It's just asking for trouble with your home connection (DDoS and Bandwidth/Connection Speed), but it's up to you.
Instead of Tick
event, use Elapsed
event.
timer.Elapsed += new EventHandler(TimerEventProcessor);
and change the signiture of TimerEventProcessor method;
private void TimerEventProcessor(object sender, ElapsedEventArgs e)
{
label1.Text = _counter.ToString();
_counter += 1;
}
For 'Bad' red:
For 'Good' green:
For 'Neutral' yellow:
I see this is a little old, but there might be a better solution here.
When you want a string, but you want the string to only match certain values, you can use enums.
For example:
enum Fruit {
Orange = "Orange",
Apple = "Apple",
Banana = "Banana"
}
let myFruit: Fruit = Fruit.Banana;
Now you'll know that no matter what, myFruit will always be the string "Banana" (Or whatever other enumerable value you choose). This is useful for many things, whether it be grouping similar values like this, or mapping user-friendly values to machine-friendly values, all while enforcing and restricting the values the compiler will allow.
For simple animations you can use an animated gif. I'm using one in this README file for instance.
As of React Native 0.4.2, View components have an onLayout
prop. Pass in a function that takes an event object. The event's nativeEvent
contains the view's layout.
<View onLayout={(event) => {
var {x, y, width, height} = event.nativeEvent.layout;
}} />
The onLayout
handler will also be invoked whenever the view is resized.
The main caveat is that the onLayout
handler is first invoked one frame after your component has mounted, so you may want to hide your UI until you have computed your layout.
You could use the following to replace the first occurrence of a word within the body of the page:
var replaced = $("body").html().replace('-9o0-9909','The new string');
$("body").html(replaced);
If you wanted to replace all occurrences of a word, you need to use regex and declare it global /g
:
var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);
If you wanted a one liner:
$("body").html($("body").html().replace(/12345-6789/g,'<b>abcde-fghi</b>'));
You are basically taking all of the HTML within the <body>
tags of the page into a string variable, using replace() to find and change the first occurrence of the found string with a new string. Or if you want to find and replace all occurrences of the string introduce a little regex to the mix.
See a demo here - look at the HTML top left to see the original text, the jQuery below, and the output to the bottom right.
You can do something like:
int countSetBits(int n)
{
n=((n&0xAAAAAAAA)>>1) + (n&0x55555555);
n=((n&0xCCCCCCCC)>>2) + (n&0x33333333);
n=((n&0xF0F0F0F0)>>4) + (n&0x0F0F0F0F);
n=((n&0xFF00FF00)>>8) + (n&0x00FF00FF);
return n;
}
int main()
{
int n=10;
printf("Number of set bits: %d",countSetBits(n));
return 0;
}
See heer: http://ideone.com/JhwcX
The working can be explained as follows:
First, all the even bits are shifted towards right & added with the odd bits to count the number of bits in group of two. Then we work in group of two, then four & so on..
I had similar problem, i solve using css ":before".. the code looks likes this:
.widgets li:before{
content:"• ";
}
The link to a function in a dynamic library is resolved when the library is loaded or at run time. Therefore, both the executable file and dynamic library are loaded into memory when the program is run. The memory address at which a dynamic library is loaded cannot be determined in advance, because a fixed address might clash with another dynamic library requiring the same address.
There are two commonly used methods for dealing with this problem:
1.Relocation. All pointers and addresses in the code are modified, if necessary, to fit the actual load address. Relocation is done by the linker and the loader.
2.Position-independent code. All addresses in the code are relative to the current position. Shared objects in Unix-like systems use position-independent code by default. This is less efficient than relocation if program run for a long time, especially in 32-bit mode.
The name "position-independent code" actually implies following:
The code section contains no absolute addresses that need relocation, but only self relative addresses. Therefore, the code section can be loaded at an arbitrary memory address and shared between multiple processes.
The data section is not shared between multiple processes because it often contains writeable data. Therefore, the data section may contain pointers or addresses that need relocation.
All public functions and public data can be overridden in Linux. If a function in the main executable has the same name as a function in a shared object, then the version in main will take precedence, not only when called from main, but also when called from the shared object. Likewise, when a global variable in main has the same name as a global variable in the shared object, then the instance in main will be used, even when accessed from the shared object.
This so-called symbol interposition is intended to mimic the behavior of static libraries.
A shared object has a table of pointers to its functions, called procedure linkage table (PLT) and a table of pointers to its variables called global offset table (GOT) in order to implement this "override" feature. All accesses to functions and public variables go through this tables.
p.s. Where dynamic linking cannot be avoided, there are various ways to avoid the timeconsuming features of the position-independent code.
You can read more from this article: http://www.agner.org/optimize/optimizing_cpp.pdf
First, elements inside a collection print their repr. you should learn about __repr__
and __str__
.
This is the difference between print repr(1.1) and print 1.1. Let's join all those strings instead of the representations:
numbers = [9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.07933]
print "repr:", " ".join(repr(n) for n in numbers)
print "str:", " ".join(str(n) for n in numbers)
Array.prototype.shuffle=function(){
var len = this.length,temp,i
while(len){
i=Math.random()*len-- |0;
temp=this[len],this[len]=this[i],this[i]=temp;
}
return this;
}
Running Ubuntu, I had to do:
sudo apt-get install python-mysqldb
SELECT RIGHT(RTRIM(column), 3),
LEFT(column, LEN(column) - 3)
FROM table
Use RIGHT
w/ RTRIM
(to avoid complications with a fixed-length column), and LEFT
coupled with LEN
(to only grab what you need, exempt of the last 3 characters).
if there's ever a situation where the length is <= 3, then you're probably going to have to use a CASE
statement so the LEFT
call doesn't get greedy.
I reworked Doug Glancy's solution to avoid rows deletion, which can lead to #Ref issue in formulae.
Sub ListReset(lst As ListObject)
'clears a listObject while leaving row 1 empty, with formulae
With lst
If .ShowAutoFilter Then .AutoFilter.ShowAllData
On Error Resume Next
With .DataBodyRange
.Offset(1).Rows.Clear
.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
End With
On Error GoTo 0
.Resize .Range.Rows("1:2")
End With
End Sub
ArrayIndexOutOfBounds means you are trying to index a position within an array that is not allocated.
In this case:
String[] name = { "tom", "dick", "harry" };
for (int i = 0; i <= name.length; i++) {
System.out.println(name[i]);
}
To get around this...
In your for loop, you can do i < name.length. This would prevent looping to name[3] and would instead stop at name[2]
for(int i = 0; i<name.length; i++)
Use a for each loop
String[] name = { "tom", "dick", "harry" };
for(String n : name) {
System.out.println(n);
}
Use list.forEach(Consumer action) (requires Java8)
String[] name = { "tom", "dick", "harry" };
Arrays.asList(name).forEach(System.out::println);
Convert array to stream - this is a good option if you want to perform additional 'operations' to your array e.g. filter, transform the text, convert to a map etc (requires Java8)
String[] name = { "tom", "dick", "harry" };
--- Arrays.asList(name).stream().forEach(System.out::println);
--- Stream.of(name).forEach(System.out::println);
You can use the @Qualifier annotation
From here
Fine-tuning annotation-based autowiring with qualifiers
Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value:
class Main {
private Country country;
@Autowired
@Qualifier("country")
public void setCountry(Country country) {
this.country = country;
}
}
This will use the UK add an id to USA bean and use that if you want the USA.
You can use private as well and you can call private methods with reflection. If you're using Visual Studio Team Suite it has some nice functionality that will generate a proxy to call your private methods for you. Here's a code project article that demonstrates how you can do the work yourself to unit test private and protected methods:
http://www.codeproject.com/KB/cs/testnonpublicmembers.aspx
In terms of which access modifier you should use, my general rule of thumb is start with private and escalate as needed. That way you will expose as little of the internal details of your class as are truly needed and it helps keep the implementation details hidden, as they should be.
That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.
If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat
to parse these kinds of strings.
I have an utility method to switch to the required window as shown below
public class Utility
{
public static WebDriver getHandleToWindow(String title){
//parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
System.err.println("No of windows : " + windowIterator.size());
for (String s : windowIterator) {
String windowHandle = s;
popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
System.out.println("Window Title : " + popup.getTitle());
System.out.println("Window Url : " + popup.getCurrentUrl());
if (popup.getTitle().equals(title) ){
System.out.println("Selected Window Title : " + popup.getTitle());
return popup;
}
}
System.out.println("Window Title :" + popup.getTitle());
System.out.println();
return popup;
}
}
It will take you to desired window once title of the window is passed as parameter. In your case you can do.
Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");
and then again switch to parent window using the same method
Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");
This method works effectively when dealing with multiple windows.
Yes, you can make a web method like..
[WebMethod]
public static String SetName(string name)
{
return "Your String"
}
And then call it in JavaScript like,
PageMethods.SetName(parameterValueIfAny, onSuccessMethod,onFailMethod);
This is also required :
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>
What you basically want to do is to force push your local branch, in order to overwrite the remote one.
If you want a more detailed explanation of each of the following commands, then see my details section below. You basically have 4 different options for force pushing with Git:
git push <remote> <branch> -f
git push origin master -f # Example
git push <remote> -f
git push origin -f # Example
git push -f
git push <remote> <branch> --force-with-lease
If you want a more detailed explanation of each command, then see my long answers section below.
Warning: force pushing will overwrite the remote branch with the state of the branch that you're pushing. Make sure that this is what you really want to do before you use it, otherwise you may overwrite commits that you actually want to keep.
You can completely specify specific branches and a remote. The -f
flag is the short version of --force
git push <remote> <branch> --force
git push <remote> <branch> -f
When the branch to push branch is omitted, Git will figure it out based on your config settings. In Git versions after 2.0, a new repo will have default settings to push the currently checked-out branch:
git push <remote> --force
while prior to 2.0, new repos will have default settings to push multiple local branches. The settings in question are the remote.<remote>.push
and push.default
settings (see below).
When both the remote and the branch are omitted, the behavior of just git push --force
is determined by your push.default
Git config settings:
git push --force
As of Git 2.0, the default setting, simple
, will basically just push your current branch to its upstream remote counter-part. The remote is determined by the branch's branch.<remote>.remote
setting, and defaults to the origin repo otherwise.
Before Git version 2.0, the default setting, matching
, basically just pushes all of your local branches to branches with the same name on the remote (which defaults to origin).
You can read more push.default
settings by reading git help config
or an online version of the git-config(1) Manual Page.
--force-with-lease
Force pushing with a "lease" allows the force push to fail if there are new commits on the remote that you didn't expect (technically, if you haven't fetched them into your remote-tracking branch yet), which is useful if you don't want to accidentally overwrite someone else's commits that you didn't even know about yet, and you just want to overwrite your own:
git push <remote> <branch> --force-with-lease
You can learn more details about how to use --force-with-lease
by reading any of the following:
quick note for those recently upgrading to "modern" ssh version [OpenSSH_8.1p1, OpenSSL 1.1.1d FIPS 10 Sep 2019] - supplied with fedora 31, seems not to be anymore accepting old DSA SHA256 keys (mine are dated 2006!) - created a new rsa key, public added to authorized, private on client, and everything works perfectly.
thanks for previous suggestions, especially the ssh -v has been very useful
You can create a DIV
component using the <h:panelGroup/>
.
By default, the <h:panelGroup/>
will generate a SPAN in the HTML code.
However, if you specify layout="block"
, then the component will be a DIV
in the generated HTML code.
<h:panelGroup layout="block"/>
Well, you could swap your 0
's for NA
and then use one of those solutions, but for sake of a difference, you could notice that a number will only have a finite logarithm if it is greater than 0
, so that rowSums
of the log
will only be finite if there are no zeros in a row.
dfr[is.finite(rowSums(log(dfr[-1]))),]
It's stored in the process (shell) and since you've exported it, any processes that process spawns.
Doing the above doesn't store it anywhere in the filesystem like /etc/profile. You have to put it there explicitly for that to happen.
The object of synchronization Semaphore implements a classical traffic light. A traffic light controls access to a resource shared by a counter. If the counter is greater than zero, access is granted; If it is zero, access is denied. The counter counts the permissions that allow access to the shared resource. Then, to access the resource, a thread must receive permission from the traffic light. In general, to use a traffic light, the thread that wants to access the shared resource tries to acquire a permit. If the traffic light count is greater than zero, the thread acquires a permit, and the traffic light count is decremented. Otherwise the thread is locked until it can get a permission. When the thread no longer needs to access the shared resource, it releases the permission, so the traffic light count is increased. If there is another thread waiting for a permit, it acquires a permit at that time. The Semaphore class of Java implements this mechanism.
Semaphore has two builders:
Semaphore(int num)
Semaphore(int num, boolean come)
num specifies the initial count of the permit. Then num specifies the number of threads that can access a shared resource at a given time. If num is one, it can access the resource one thread at a time. By setting come as true, you can guarantee that the threads you are waiting for are granted permission in the order they requested.
I've found the easiest way to centre and left-align text inside a container is the following:
HTML:
<div>
<p>Some interesting text.</p>
</div>
CSS:
P {
width: 50%; //or whatever looks best
margin: auto; //top and bottom margin can be added for aesthetic effect
}
Hope this is what you were looking for as it took me quite a bit of searching just to figure out this pretty basic solution.
This is how I add to a string when needed:
string[] myList;
myList = new string[100];
for (int i = 0; i < 100; i++)
{
myList[i] = string.Format("List string : {0}", i);
}
I had a similar problem. Just to help out someone with the same issue:
My error was the user file attribute for the files in /var/www. After changing them back to the user "www-data", the problem was gone.
SortedList decorator from Java Happy Libraries can be used to decorate TreeList from Apache Collections. That would produce a new list which performance is compareable to TreeSet. https://sourceforge.net/p/happy-guys/wiki/Sorted%20List/
php test.php
should do it, or
php -f test.php
to be explicit.
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'name_of_your_table'
I had the same issue, but it was resolved by going to gmail's security settings and Allowing Less Secure apps. The Code from Domenic & Donny works, but only if you enabled that setting
If you are signed in (to Google) you can follow this link and toggle "Turn on" for "Access for less secure apps"
set global max_allowed_packet=10000000000;
Another option is to repeat the rules in two prefix locations using an included file. Since prefix locations are position independent in the configuration, using them can save some confusion as you add other regex locations later on. Avoiding regex locations when you can will help your configuration scale smoothly.
server {
location /first/location/ {
include shared.conf;
}
location /second/location/ {
include shared.conf;
}
}
Here's a sample shared.conf:
default_type text/plain;
return 200 "http_user_agent: $http_user_agent
remote_addr: $remote_addr
remote_port: $remote_port
scheme: $scheme
nginx_version: $nginx_version
";
You have a date with a known timezone (Here Europe/Madrid
), and a target timezone (UTC
)
You just need two SimpleDateFormats:
long ts = System.currentTimeMillis(); Date localTime = new Date(ts); SimpleDateFormat sdfLocal = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss"); sdfLocal.setTimeZone(TimeZone.getTimeZone("Europe/Madrid")); SimpleDateFormat sdfUTC = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss"); sdfUTC.setTimeZone(TimeZone.getTimeZone("UTC")); // Convert Local Time to UTC Date utcTime = sdfLocal.parse(sdfUTC.format(localTime)); System.out.println("Local:" + localTime.toString() + "," + localTime.getTime() + " --> UTC time:" + utcTime.toString() + "-" + utcTime.getTime()); // Reverse Convert UTC Time to Locale time localTime = sdfUTC.parse(sdfLocal.format(utcTime)); System.out.println("UTC:" + utcTime.toString() + "," + utcTime.getTime() + " --> Local time:" + localTime.toString() + "-" + localTime.getTime());
So after see it working you can add this method to your utils:
public Date convertDate(Date dateFrom, String fromTimeZone, String toTimeZone) throws ParseException { String pattern = "yyyy/MM/dd HH:mm:ss"; SimpleDateFormat sdfFrom = new SimpleDateFormat (pattern); sdfFrom.setTimeZone(TimeZone.getTimeZone(fromTimeZone)); SimpleDateFormat sdfTo = new SimpleDateFormat (pattern); sdfTo.setTimeZone(TimeZone.getTimeZone(toTimeZone)); Date dateTo = sdfFrom.parse(sdfTo.format(dateFrom)); return dateTo; }
for (int i=0; i<dt_pattern.Rows.Count; i++)
{
DataRow dr = dt_pattern.Rows[i];
}
In the loop, you can now reference row i+1 (assuming there is an i+1)
This is the job for style
property:
document.getElementById("remember").style.visibility = "visible";
This answer solves the problem by creating a duplicate annotated tag — including all tag info such as tagger, message, and tag date — by using the tag info from the existing tag.
SOURCE_TAG=old NEW_TAG=new; deref() { git for-each-ref \
"refs/tags/$SOURCE_TAG" --format="%($1)" ; }; \
GIT_COMMITTER_NAME="$(deref taggername)" \
GIT_COMMITTER_EMAIL="$(deref taggeremail)" \
GIT_COMMITTER_DATE="$(deref taggerdate)" git tag "$NEW_TAG" \
"$(deref "*objectname")" -a -m "$(deref contents)"
git tag -d old
git push origin new :old
Update the SOURCE_TAG
and NEW_TAG
values to match your old and new tag names.
From what I can tell, all the other answers have subtle gotchas, or don't fully duplicate everything about the tag (e.g. they use a new tag date, or the current user's info as the tagger). Many of them call out the re-tagging warning, despite that not applying to this scenario (it's for moving a tag name to a different commit, not for renaming to a differently named tag). I've done some digging, and I believe I've pieced together a solution that addresses these concerns.
The git-tag
documentation specifies the parts of an annotated tag. To truly be an indistinguishable rename, these elements should be the same in the new tag.
Tag objects (created with
-a
,-s
, or-u
) are called "annotated" tags; they contain a creation date, the tagger name and e-mail, a tagging message, and an optional GnuPG signature.
I'm only addressing unsigned tags in this answer, though it should be a simple matter to extend this solution to signed tags.
An annotated tag named old
is used in the example, and will be renamed to new
.
First, we need to get the information for the existing tag. This can be achieved using for-each-ref
:
Command:
git for-each-ref refs/tags --format="\
Tag name: %(refname:short)
Tag commit: %(objectname:short)
Tagger date: %(taggerdate)
Tagger name: %(taggername)
Tagger email: %(taggeremail)
Tagged commit: %(*objectname:short)
Tag message: %(contents)"
Output:
Tag commit: 88a6169
Tagger date: Mon Dec 14 12:44:52 2020 -0600
Tagger name: John Doe
Tagger email: <[email protected]>
Tagged commit: cda5b4d
Tag name: old
Tag message: Initial tag
Body line 1.
Body line 2.
Body line 3.
A duplicate tag with the new name can be created using the info gathered in step 1 from the existing tag.
The commit ID & commit message can be passed directly to git tag
.
The tagger information (name, email, and date) can be set using the git environment variables GIT_COMMITTER_NAME
, GIT_COMMITTER_EMAIL
, GIT_COMMITTER_DATE
. The date usage in this context is described in the On Backdating Tags documentation for git tag
; the other two I figured out through experimentation.
GIT_COMMITTER_NAME="John Doe" GIT_COMMITTER_EMAIL="[email protected]" \
GIT_COMMITTER_DATE="Mon Dec 14 12:44:52 2020 -0600" git tag new cda5b4d -a -m "Initial tag
Body line 1.
Body line 2.
Body line 3."
A side-by-side comparison of the two tags shows they're identical in all the ways that matter. The only thing that's differing here is the commit reference of the tag itself, which is expected since they're two different tags.
Command:
git for-each-ref refs/tags --format="\
Tag commit: %(objectname:short)
Tagger date: %(taggerdate)
Tagger name: %(taggername)
Tagger email: %(taggeremail)
Tagged commit: %(*objectname:short)
Tag name: %(refname:short)
Tag message: %(contents)"
Output:
Tag commit: 580f817
Tagger date: Mon Dec 14 12:44:52 2020 -0600
Tagger name: John Doe
Tagger email: <[email protected]>
Tagged commit: cda5b4d
Tag name: new
Tag message: Initial tag
Body line 1.
Body line 2.
Body line 3.
Tag commit: 30ddd25
Tagger date: Mon Dec 14 12:44:52 2020 -0600
Tagger name: John Doe
Tagger email: <[email protected]>
Tagged commit: cda5b4d
Tag name: old
Tag message: Initial tag
Body line 1.
Body line 2.
Body line 3.
As a single command, including retrieving the current tag data:
SOURCE_TAG=old NEW_TAG=new; deref() { git for-each-ref "refs/tags/$SOURCE_TAG" --format="%($1)" ; }; GIT_COMMITTER_NAME="$(deref taggername)" GIT_COMMITTER_EMAIL="$(deref taggeremail)" GIT_COMMITTER_DATE="$(deref taggerdate)" git tag "$NEW_TAG" "$(deref "*objectname")" -a -m "$(deref contents)"
Next, the existing tag should be deleted locally. This step can be skipped if you wish to keep the old tag along with the new one (i.e. duplicate the tag rather than rename it).
git tag -d old
Assuming you're working from a remote repository, the changes can now be pushed using git push
:
git push origin new :old
This pushes the new
tag, and deletes the old
tag.
Sometimes it's just better to use an iterator.
(Allegedly, "85%" of the requests for an index in the posh for loop is for implementing a String
join method (which you can easily do without).)
Heap pollution is a technical term. It refers to references which have a type that is not a supertype of the object they point to.
List<A> listOfAs = new ArrayList<>();
List<B> listOfBs = (List<B>)(Object)listOfAs; // points to a list of As
This can lead to "unexplainable" ClassCastException
s.
// if the heap never gets polluted, this should never throw a CCE
B b = listOfBs.get(0);
@SafeVarargs
does not prevent this at all. However, there are methods which provably will not pollute the heap, the compiler just can't prove it. Previously, callers of such APIs would get annoying warnings that were completely pointless but had to be suppressed at every call site. Now the API author can suppress it once at the declaration site.
However, if the method actually is not safe, users will no longer be warned.
I created a new performance test for unset
and =null
, because as mentioned in the comments the here written has an error (the recreating of the elements).
I used arrays, as you see it didn't matter now.
<?php
$arr1 = array();
$arr2 = array();
for ($i = 0; $i < 10000000; $i++) {
$arr1[$i] = 'a';
$arr2[$i] = 'a';
}
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$arr1[$i] = null;
}
$elapsed = microtime(true) - $start;
echo 'took '. $elapsed .'seconds<br>';
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
unset($arr2[$i]);
}
$elapsed = microtime(true) - $start;
echo 'took '. $elapsed .'seconds<br>';
But i can only test it on an PHP 5.5.9 server, here the results: - took 4.4571571350098 seconds - took 4.4425978660583 seconds
I prefer unset
for readability reasons.
Just throw everything you read into a MemoryStream
and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
var buffer = new byte[512];
var bytesRead = default(int);
while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
memstream.Write(buffer, 0, bytesRead);
bytes = memstream.ToArray();
}
Or if you don't want to manage the buffers:
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
reader.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
Simple Override onBackPressed Method:
@Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
The compiler needs to know the size of the second dimension in your two dimensional array. For example:
void print_graph(g_node graph_node[], double weight[][5], int nodes);
will I get the same results?
Not really. I don't know of a workaround for PHP 5.2, though.
What is the difference between
new self
andnew static
?
self
refers to the same class in which the new
keyword is actually written.
static
, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.
In the following example, B
inherits both methods from A
. The self
invocation is bound to A
because it's defined in A
's implementation of the first method, whereas static
is bound to the called class (also see get_called_class()
).
class A {
public static function get_self() {
return new self();
}
public static function get_static() {
return new static();
}
}
class B extends A {}
echo get_class(B::get_self()); // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A
Forever takes command line options for output:
-l LOGFILE Logs the forever output to LOGFILE
-o OUTFILE Logs stdout from child script to OUTFILE
-e ERRFILE Logs stderr from child script to ERRFILE
For example:
forever start -o out.log -e err.log my-script.js
See here for more info
xargs on MacOS doesn't have -d option, so this solution uses -0 instead.
Get ls to output one file per line, then translate newlines into nulls and tell xargs to use nulls as the delimiter:
ls -1 *mp3 | tr "\n" "\0" | xargs -0 mplayer
If your branch is behind by master then do:
git checkout master (you are switching your branch to master)
git pull
git checkout yourBranch (switch back to your branch)
git merge master
After merging it, check if there is a conflict or not.
If there is NO CONFLICT then:
git push
If there is a conflict then fix your file(s), then:
git add yourFile(s)
git commit -m 'updating my branch'
git push
OK, figured it out now - thanks to Jobi whose answer was close, but not quite.
From a WPF application, here's my code that works:
First a helper class:
private class OldWindow : System.Windows.Forms.IWin32Window
{
IntPtr _handle;
public OldWindow(IntPtr handle)
{
_handle = handle;
}
#region IWin32Window Members
IntPtr System.Windows.Forms.IWin32Window.Handle
{
get { return _handle; }
}
#endregion
}
Then, to use this:
System.Windows.Forms.FolderBrowserDialog dlg = new FolderBrowserDialog();
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle);
System.Windows.Forms.DialogResult result = dlg.ShowDialog(win);
I'm sure I can wrap this up better, but basically it works. Yay! :-)
You can use placement-new like this:
class Car
{
int _no;
public:
Car(int no) : _no(no)
{
}
};
int main()
{
void *raw_memory = operator new[](NUM_CARS * sizeof(Car));
Car *ptr = static_cast<Car *>(raw_memory);
for (int i = 0; i < NUM_CARS; ++i) {
new(&ptr[i]) Car(i);
}
// destruct in inverse order
for (int i = NUM_CARS - 1; i >= 0; --i) {
ptr[i].~Car();
}
operator delete[](raw_memory);
return 0;
}
Reference from More Effective C++ - Scott Meyers:
Item 4 - Avoid gratuitous default constructors
Update: As of jQuery 1.4 you can use the .delay( n )
method. http://api.jquery.com/delay/
$('.notice').fadeIn().delay(2000).fadeOut('slow');
Note: $.show()
and $.hide()
by default are not queued, so if you want to use $.delay()
with them, you need to configure them that way:
$('.notice')
.show({duration: 0, queue: true})
.delay(2000)
.hide({duration: 0, queue: true});
You could possibly use the Queue syntax, this might work:
jQuery(function($){
var e = $('.notice');
e.fadeIn();
e.queue(function(){
setTimeout(function(){
e.dequeue();
}, 2000 );
});
e.fadeOut('fast');
});
or you could be really ingenious and make a jQuery function to do it.
(function($){
jQuery.fn.idle = function(time)
{
var o = $(this);
o.queue(function()
{
setTimeout(function()
{
o.dequeue();
}, time);
});
};
})(jQuery);
which would ( in theory , working on memory here ) permit you do to this:
$('.notice').fadeIn().idle(2000).fadeOut('slow');
Html.DisplayFor()
will render the DisplayTemplate that matches the property's type.
If it can't find any, I suppose it invokes .ToString()
.
If you don't know about display templates, they're partial views that can be put in a DisplayTemplates
folder inside the view folder associated to a controller.
Example:
If you create a view named String.cshtml
inside the DisplayTemplates
folder of your views folder (e.g Home
, or Shared
) with the following code:
@model string
@if (string.IsNullOrEmpty(Model)) {
<strong>Null string</strong>
}
else {
@Model
}
Then @Html.DisplayFor(model => model.Title)
(assuming that Title
is a string) will use the template and display <strong>Null string</strong>
if the string is null, or empty.
Previously it used to say that an app with different signature is found on device. When installing from IDE it would also ask do you want to uninstall it?
But I think from Android 5.0 they have changed the reason for uninstallation. It does not happen if you are installing app with the same signature
On Windows 10 Pro, the batch file can be registered; the workaround of registering cmd.exe and specifying the bat file as a param isn't needed. I just did this, registering both a shutdown script and a startup (boot) script, and it worked.
You can use any selector with not
p:not(:first-child){}
p:not(:first-of-type){}
p:not(:checked){}
p:not(:last-child){}
p:not(:last-of-type){}
p:not(:first-of-type){}
p:not(:nth-last-of-type(2)){}
p:not(nth-last-child(2)){}
p:not(:nth-child(2)){}
on sql 2008 this is valid
DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable
on sql server 2005, you need to do this
DECLARE @myVariable nvarchar(Max)
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class UserController extends CI_Controller {
public function verifyUser() {
$userName = $_POST['userName'];
$userPassword = $_POST['userPassword'];
$status = array("STATUS"=>"false");
if($userName=='admin' && $userPassword=='admin'){
$status = array("STATUS"=>"true");
}
echo json_encode ($status) ;
}
}
function makeAjaxCall(){
$.ajax({
type: "post",
url: "http://localhost/CodeIgnitorTutorial/index.php/usercontroller/verifyUser",
cache: false,
data: $('#userForm').serialize(),
success: function(json){
try{
var obj = jQuery.parseJSON(json);
alert( obj['STATUS']);
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}
There are two related concepts, both called "keyword arguments".
On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default values for any parameters which were not mentioned at all.
The other concept is on the function definition side: you can define a function that takes parameters by name -- and you don't even have to specify what those names are. These are pure keyword arguments, and can't be passed positionally. The syntax is
def my_function(arg1, arg2, **kwargs)
Any keyword arguments you pass into this function will be placed into a dictionary named kwargs
. You can examine the keys of this dictionary at run-time, like this:
def my_function(**kwargs):
print str(kwargs)
my_function(a=12, b="abc")
{'a': 12, 'b': 'abc'}
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
I ran a test that just added 1 to the number instead of rand(). Results (on an x86-64) were:
Your class doesn't have a __init__()
, so by the time it's instantiated, the attribute atoms
is not present. You'd have to do C.setdata('something')
so C.atoms
becomes available.
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'
>>> C.setdata('something')
>>> C.atoms.append('thing') # now it works
>>>
Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.
To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms
list you could add a constructor:
def __init__(self):
self.atoms = []
This is the best video I have found that fully explains recursion and the Fibonacci sequence in Java.
http://www.youtube.com/watch?v=dsmBRUCzS7k
This is his code for the sequence and his explanation is better than I could ever do trying to type it out.
public static void main(String[] args)
{
int index = 0;
while (true)
{
System.out.println(fibonacci(index));
index++;
}
}
public static long fibonacci (int i)
{
if (i == 0) return 0;
if (i<= 2) return 1;
long fibTerm = fibonacci(i - 1) + fibonacci(i - 2);
return fibTerm;
}
You're not working with strings. You're working with pointers.
var1
is a char pointer (const char*
). It is not a string. If it is null-terminated, then certain C functions will treat it as a string, but it is fundamentally just a pointer.
So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*)
.
Such an operator does exist. It takes two pointers and returns true
if they point to the same address. So the compiler invokes that, and your code breaks.
IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.
The C way of doing this is to use the strcmp
function:
strcmp(var1, "dev");
This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)
So to compare for equality you need to do one of these:
if (!strcmp(var1, "dev")){...}
if (strcmp(var1, "dev") == 0) {...}
However, C++ has a very useful string
class. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:
std::string var1 = getenv("myEnvVar");
if(var1 == "dev")
{
// do stuff
}
Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.
Try this:
$("span").css("pointer-events", "none");
you can enabled those back by
$("span").css("pointer-events", "auto");
You need to define height of ul or your div and set overflow equals to auto as below:
<ul style="width: 300px; height: 200px; overflow: auto">
<li>text</li>
<li>text</li>
You can use chars as is as single byte integers.
Here is a simplistic example of streaming a file:
using System.IO;
using Microsoft.AspNetCore.Mvc;
[HttpGet("{id}")]
public async Task<FileStreamResult> Download(int id)
{
var path = "<Get the file path using the ID>";
var stream = File.OpenRead(path);
return new FileStreamResult(stream, "application/octet-stream");
}
Note:
Be sure to use FileStreamResult
from Microsoft.AspNetCore.Mvc
and not from System.Web.Mvc
.
You could use GSON, using Gradle Build.gradle :
implementation 'com.google.code.gson:gson:2.8.0'
Then in your code, for example pairs of string/boolean with Kotlin :
val nestedData = HashMap<String,Boolean>()
for (i in 0..29) {
nestedData.put(i.toString(), true)
}
val gson = Gson()
val jsonFromMap = gson.toJson(nestedData)
Adding to SharedPrefs :
val sharedPrefEditor = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE).edit()
sharedPrefEditor.putString("sig_types", jsonFromMap)
sharedPrefEditor.apply()
Now to retrieve data :
val gson = Gson()
val sharedPref: SharedPreferences = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE)
val json = sharedPref.getString("sig_types", "false")
val type = object : TypeToken<Map<String, Boolean>>() {}.type
val map = gson.fromJson(json, type) as LinkedTreeMap<String,Boolean>
for (key in map.keys) {
Log.i("myvalues", key.toString() + map.get(key).toString())
}
Another option would be to use a symbolic link. ie:
ln -s ~/Files/Scripts/Main ~/myFold
After that you can perform operations to ~/myFold
, such as:
cp some_file.txt ~/myFold
which will put the file in ~/Files/Scripts/Main
. You can remove the symbolic link at any time with rm ~/myFold
, which will keep the original directory.
How you test depends on the Property's DataType:
| Type | Test | Test2 | Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then | | Boolen (True/False) | If Not obj.Property Then | If obj.Property = False Then | Object | If obj.Property Is Nothing Then | | String | If obj.Property = "" Then | If LenB(obj.Property) = 0 Then | Variant | If obj.Property = Empty Then |
You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)
This doesn't work for me, I want to to like jquery slideUp / slideDown function, I tried this code, but it only move the content wich stay at the same place after animation end, the view should have a 0dp height at start of slideDown and the view height (with wrap_content) after the end of the animation.
Serialization provides default functionality to store and later recreate the object. It uses verbose format to define the whole graph of objects to be stored e.g. suppose you have a linkedList and you code like below, then the default serialization will discover all the objects which are linked and will serialize. In default serialization the object is constructed entirely from its stored bits, with no constructor calls.
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("/Users/Desktop/files/temp.txt"));
oos.writeObject(linkedListHead); //writing head of linked list
oos.close();
But if you want restricted serialization or don't want some portion of your object to be serialized then use Externalizable. The Externalizable interface extends the Serializable interface and adds two methods, writeExternal() and readExternal(). These are automatically called while serialization or deserialization. While working with Externalizable we should remember that the default constructer should be public else the code will throw exception. Please follow the below code:
public class MyExternalizable implements Externalizable
{
private String userName;
private String passWord;
private Integer roll;
public MyExternalizable()
{
}
public MyExternalizable(String userName, String passWord, Integer roll)
{
this.userName = userName;
this.passWord = passWord;
this.roll = roll;
}
@Override
public void writeExternal(ObjectOutput oo) throws IOException
{
oo.writeObject(userName);
oo.writeObject(roll);
}
@Override
public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException
{
userName = (String)oi.readObject();
roll = (Integer)oi.readObject();
}
public String toString()
{
StringBuilder b = new StringBuilder();
b.append("userName: ");
b.append(userName);
b.append(" passWord: ");
b.append(passWord);
b.append(" roll: ");
b.append(roll);
return b.toString();
}
public static void main(String[] args)
{
try
{
MyExternalizable m = new MyExternalizable("nikki", "student001", 20);
System.out.println(m.toString());
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/Desktop/files/temp1.txt"));
oos.writeObject(m);
oos.close();
System.out.println("***********************************************************************");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/Desktop/files/temp1.txt"));
MyExternalizable mm = (MyExternalizable)ois.readObject();
mm.toString();
System.out.println(mm.toString());
}
catch (ClassNotFoundException ex)
{
Logger.getLogger(MyExternalizable.class.getName()).log(Level.SEVERE, null, ex);
}
catch(IOException ex)
{
Logger.getLogger(MyExternalizable.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Here if you comment the default constructer then the code will throw below exception:
java.io.InvalidClassException: javaserialization.MyExternalizable;
javaserialization.MyExternalizable; no valid constructor.
We can observe that as password is sensitive information, so i am not serializing it in writeExternal(ObjectOutput oo) method and not setting the value of same in readExternal(ObjectInput oi). That's the flexibility that is provided by Externalizable.
The output of the above code is as per below:
userName: nikki passWord: student001 roll: 20
***********************************************************************
userName: nikki passWord: null roll: 20
We can observe as we are not setting the value of passWord so it's null.
The same can also be achieved by declaring the password field as transient.
private transient String passWord;
Hope it helps. I apologize if i made any mistakes. Thanks.
SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.
As it happens, you are close. Just need leading+trailing wildcards and move the NOT
WHERE whatever NOT LIKE '%[a-z0-9]%'
The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.
According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:
git tag <tagname>
, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).git tag -a <tagname>
, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.git tag -a -m <msg> <tagname>
, Git will tag the commit and annotate it with the provided message.git tag -m <msg> <tagname>
, Git will behave as if you passed the -a flag for annotation and use the provided message.Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.
For us, the key difference is in overall perf...
Have a look at Logger.IsDebugEnabled
in NLog versus Log4Net, from our tests, NLog has less overhead and that's what we are after (low-latency stuff).
Cheers, Florian
I use Eclipse Java EE edition
Create a "Dynamic Web Project"
Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.
When I deploy I export the project to a war file.
T = map(lambda i: L[i], Idx)
You can make your pattern case insensitive by doing:
Pattern p = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);
Check your WEB-INF/web.xml file for the servlet Mapping.
$(window).load()
will work only the first time the page is loaded. If you are doing dynamic stuff (example: click button, wait for some new images to load), this won't work. To achieve that, you can use my plugin:
/**
* Plugin which is applied on a list of img objects and calls
* the specified callback function, only when all of them are loaded (or errored).
* @author: H. Yankov (hristo.yankov at gmail dot com)
* @version: 1.0.0 (Feb/22/2010)
* http://yankov.us
*/
(function($) {
$.fn.batchImageLoad = function(options) {
var images = $(this);
var originalTotalImagesCount = images.size();
var totalImagesCount = originalTotalImagesCount;
var elementsLoaded = 0;
// Init
$.fn.batchImageLoad.defaults = {
loadingCompleteCallback: null,
imageLoadedCallback: null
}
var opts = $.extend({}, $.fn.batchImageLoad.defaults, options);
// Start
images.each(function() {
// The image has already been loaded (cached)
if ($(this)[0].complete) {
totalImagesCount--;
if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
// The image is loading, so attach the listener
} else {
$(this).load(function() {
elementsLoaded++;
if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
// An image has been loaded
if (elementsLoaded >= totalImagesCount)
if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
});
$(this).error(function() {
elementsLoaded++;
if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
// The image has errored
if (elementsLoaded >= totalImagesCount)
if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
});
}
});
// There are no unloaded images
if (totalImagesCount <= 0)
if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
};
})(jQuery);
Just listen to what the warning is telling you:
Reshape your data either X.reshape(-1, 1) if your data has a single feature/column and X.reshape(1, -1) if it contains a single sample.
For your example type(if you have more than one feature/column):
temp = temp.reshape(1,-1)
For one feature/column:
temp = temp.reshape(-1,1)
Building on Amine's answer, create a helper like:
public static class HtmlHelperExtensions
{
public static MvcHtmlString CurrencyFormat(this HtmlHelper helper, string value)
{
var result = string.Format("{0:C2}", value);
return new MvcHtmlString(result);
}
}
in your view: use @Html.CurrencyFormat(model.value)
If you are doing simple formating like Standard Numeric Formats, then simple use string.Format() in your view like in the helper example above:
@string.Format("{0:C2}", model.value)