If you can restrict it to just (Open Office XML format) *.xlsx files, then probably the most popular library would be EPPLus.
Bonus is, there are no other dependencies. Just install using nuget:
Install-Package EPPlus
Using ClosedXML library( there is no need to install MS Excel
I just write a simple example to show you how you can name the file, the worksheet and select cells:
var workbook = new XLWorkbook();
workbook.AddWorksheet("sheetName");
var ws = workbook.Worksheet("sheetName");
int row = 1;
foreach (object item in itemList)
{
ws.Cell("A" + row.ToString()).Value = item.ToString();
row++;
}
workbook.SaveAs("yourExcel.xlsx");
If you prefer you can create a System.Data.DataSet or a System.Data.DataTable with all data and then just add it as a workseet with workbook.AddWorksheet(yourDataset)
or workbook.AddWorksheet(yourDataTable)
;
wb.Close();
app.Quit();
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process p in process)
{
if (!string.IsNullOrEmpty(p.ProcessName) && p.StartTime.AddSeconds(+10) > DateTime.Now)
{
try
{
p.Kill();
}
catch { }
}
}
It Closes last 10 sec process with name "Excel"
Add this at your TODO point:
aRange.Columns.AutoFit();
Test like this.Sometimes, permission problem.
cmd => dcomcnfg
Click
Component services >Computes >My Computer>Dcom config> and select micro soft Excel Application
Right Click on microsoft Excel Application
Properties>Give Asp.net Permissions
Select Identity table >Select interactive user >select ok
This will work, independent of Excel version (2003, 2007, 2010). The first has 65536 rows in a sheet, while the latter two have a million rows or so. Sheet1.Rows.Count
returns this number dependent on the version.
numofrows = Sheet1.Range("A1").Offset(Sheet1.Rows.Count - 1, 0).End(xlUp).Row
or the equivalent but shorter
numofrows = Sheet1.Cells(Sheet1.Rows.Count,1).End(xlUp)
This searches up from the bottom of column A for the first non-empty cell, and gets its row number.
This also works if you have data that go further down in other columns. So for instance, if you take your example data and also write something in cell FY4763, the above will still correctly return 9 (not 4763, which any method involving the UsedRange
property would incorrectly return).
Note that really, if you want the cell reference, you should just use the following. You don't have to first get the row number, and then build the cell reference.
Set rngLastCell = Sheet1.Range("A1").Offset(Sheet1.Rows.Count - 1, 0).End(xlUp)
Note that this method fails in certain edge cases:
So watch out if you're planning to use row 1,048,576 for these things!
It 'a permission problem when IIS is running I had this problem and I solved it in this way
I went on folders
C:\Windows\ System32\config\SystemProfile
and
C:\Windows\SysWOW64\config\SystemProfile
are protected system folders, they usually have the lock.
Right-click-> Card security-> Click on Edit-> Add untente "Autenticadet User" and assign permissions.
At this point everything is solved, if you still have problems try to give all permissions to "Everyone"
I had the same error code when executing the following statement:
sheet.QueryTables.Add("TEXT" & Path.GetFullPath(fileName), "1:1", Type.Missing)
The reason was the missing semicolon (;) after "TEXT".
Here is the correct one:
sheet.QueryTables.Add("TEXT;" & Path.GetFullPath(fileName), "1:1", Type.Missing)
Years after everyone's answer, I too want to present how I did it for my project
/// <summary>
/// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
/// </summary>
/// <param name="filename"></param>
/// <param name="headers">If set to true the first row will be considered as headers</param>
/// <returns></returns>
public DataSet Import(string filename, bool headers = true)
{
var _xl = new Excel.Application();
var wb = _xl.Workbooks.Open(filename);
var sheets = wb.Sheets;
DataSet dataSet = null;
if (sheets != null && sheets.Count != 0)
{
dataSet = new DataSet();
foreach (var item in sheets)
{
var sheet = (Excel.Worksheet)item;
DataTable dt = null;
if (sheet != null)
{
dt = new DataTable();
var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[1, j + 1];
var column = new DataColumn(headers ? cell.Value : string.Empty);
dt.Columns.Add(column);
}
for (int i = 0; i < rowCount; i++)
{
var r = dt.NewRow();
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
r[j] = cell.Value;
}
dt.Rows.Add(r);
}
}
dataSet.Tables.Add(dt);
}
}
_xl.Quit();
return dataSet;
}
How about Arrays.toString(byteArray)
?
Here's some compilable code:
byte[] byteArray = new byte[] { -1, -128, 1, 127 };
System.out.println(Arrays.toString(byteArray));
Output:
[-1, -128, 1, 127]
Why re-invent the wheel...
@RequestMapping(value="/") public String home(HttpServletRequest request){
System.out.println("My Attribute :: "+request.getAttribute("YourAttributeName"));
return "home";
}
You might have them turned off in your gmail settings, heres the link to change them https://support.google.com/mail/answer/145919?hl=en
Also gmail may be blocking the images thinking they are suspicious.
from the link above.
How Gmail makes images safe
Some senders try to use externally linked images in harmful ways, but Gmail takes action to ensure that images are loaded safely. Gmail serves all images through Google’s image proxy servers and transcodes them before delivery to protect you in the following ways:
Senders can’t use image loading to get information like your IP address or location. Senders can’t set or read cookies in your browser. Gmail checks your images for known viruses or malware. In some cases, senders may be able to know whether an individual has opened a message with unique image links. As always, Gmail scans every message for suspicious content and if Gmail considers a sender or message potentially suspicious, images won’t be displayed and you’ll be asked whether you want to see the images.
Following may come in handy:
⏩
⏪
⓫
⏬
⏭
⏮
⏯
⏴
⏵
⏶
⏷
⏸
⏹
⏺
NOTE: apparently, these characters aren't very well supported in popular fonts, so if you plan to use it on the web, be sure to pick a webfont that supports these.
The C5 Generic Collections Library classes all support the AddRange
method. C5 has a much more robust interface that actually exposes all of the features of its underlying implementations and is interface-compatible with the System.Collections.Generic
ICollection
and IList
interfaces, meaning that C5
's collections can be easily substituted as the underlying implementation.
I solved this problem by using the the data-cache="false" attribute in the page div on the pages I wanted refreshed.
<div data-role="page" data-cache="false">
/*content goes here*/
</div>
In my case it was my shopping cart. If a customer added an item to their cart and then continued shopping and then added another item to their cart the cart page would not show the new item. Unless they refreshed the page. Setting data-cache to false instructs JQM not to cache that page as far as I understand.
Hope this helps others in the future.
How to delete only the content of file in python
There is several ways of set the logical size of a file to 0, depending how you access that file:
To empty an open file:
def deleteContent(pfile):
pfile.seek(0)
pfile.truncate()
To empty a open file whose file descriptor is known:
def deleteContent(fd):
os.ftruncate(fd, 0)
os.lseek(fd, 0, os.SEEK_SET)
To empty a closed file (whose name is known)
def deleteContent(fName):
with open(fName, "w"):
pass
I have a temporary file with some content [...] I need to reuse that file
That being said, in the general case it is probably not efficient nor desirable to reuse a temporary file. Unless you have very specific needs, you should think about using tempfile.TemporaryFile
and a context manager to almost transparently create/use/delete your temporary files:
import tempfile
with tempfile.TemporaryFile() as temp:
# do whatever you want with `temp`
# <- `tempfile` guarantees the file being both closed *and* deleted
# on exit of the context manager
Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/
HTML
<h2>TableHeadFixer Fix Left Column</h2>
<div id="parent">
<table id="fixTable" class="table">
<thead>
<tr>
<th>Ano</th>
<th>Jan</th>
<th>Fev</th>
<th>Mar</th>
<th>Abr</th>
<th>Maio</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
</tbody>
</table>
</div>
JS
$(document).ready(function() {
$("#fixTable").tableHeadFixer({"head" : false, "right" : 1});
});
CSS
#parent {
height: 300px;
}
#fixTable {
width: 1800px !important;
}
You can also use:
Collections.sort(list, new Comparator<CustomObject>() {
public int compare(CustomObject obj1, CustomObject obj2) {
return obj1.id - obj2.id;
}
});
System.out.println(list);
The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.
function getUrlParameter(name) {
var urlOld = window.location.href.split('?');
urlOld[1] = urlOld[1] || '';
var urlBase = urlOld[0];
var urlQuery = urlOld[1].split('#');
urlQuery[1] = urlQuery[1] || '';
var parametersString = urlQuery[0].split('&');
if (parametersString.length === 1 && parametersString[0] === '') {
parametersString = [];
}
// console.log(parametersString);
var anchor = urlQuery[1] || '';
var urlParameters = {};
jQuery.each(parametersString, function (idx, parameterString) {
paramName = parameterString.split('=')[0];
paramValue = parameterString.split('=')[1];
urlParameters[paramName] = paramValue;
});
return urlParameters[name];
}
You can change the value in the XML like this:
<Button
android:background="#FFFFFF"
../>
Here, you can add any other color, from the resources or hex.
Similarly, you can also change these values form the code like this:
demoButton.setBackgroundColor(Color.WHITE);
Another easy way is to make a drawable, customize the corners and shape according to your preference and set the background color and stroke of the drawable. For eg.
button_background.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dp" android:color="#ff207d94" />
<corners android:radius="5dp" />
<solid android:color="#FFFFFF" />
</shape>
And then set this shape as the background of your button.
<Button
android:background="@drawable/button_background.xml"
../>
Hope this helps, good luck!
$scope.$watch('myVar', function (newValue, oldValue) {
if (typeof (newValue) !== 'undefined') {
$scope.someothervar= newValue;
//or get some data
getData();
}
}, true);
Variable initializes after controller so you need to watch over it and when it't initialized the use it.
It is also worth mentioning that localStorage
cannot be used when users browse in "private" mode in some versions of mobile Safari.
Quoted from MDN (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage):
Note: Starting with iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short. Safari Mobile's Private Browsing mode also prevents writing to localStorage entirely.
The way this effect works is very simple. The element is given a background which is the gradient. It goes from one color to another depending on the colors and color-stop percentages given for it.
For example, in rainbow text sample (note that I've converted the gradient into the standard syntax):
#f22
at 0%
(that is the left edge of the element). First color is always assumed to start at 0%
even though the percentage is not mentioned explicitly.0%
to 14.25%
, the color changes from #f22
to #f2f
gradually. The percenatge is set at 14.25
because there are seven color changes and we are looking for equal splits.14.25%
(of the container's size), the color will exactly be #f2f
as per the gradient specified.14.25%
.So, we end up getting a gradient like in the below snippet. Now this alone would mean the background applies to the entire element and not just the text.
.rainbow {_x000D_
background-image: linear-gradient(to right, #f22, #f2f 14.25%, #22f 28.5%, #2ff 42.75%, #2f2 57%, #2f2 71.25%, #ff2 85.5%, #f22);_x000D_
color: transparent;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>
_x000D_
Since, the gradient needs to be applied only to the text and not to the element on the whole, we need to instruct the browser to clip the background from the areas outside the text. This is done by setting background-clip: text
.
(Note that the background-clip: text
is an experimental property and is not supported widely.)
Now if you want the text to have a simple 3 color gradient (that is, say from red - orange - brown), we just need to change the linear-gradient specification as follows:
to right
. If it should be red at right and brown at left then give the direction as to left
.red
as the first color (percentage is assumed to be 0%).50%
the color should be orange
and then the final color would be brown
. The position of the final color is always assumed to be at 100%.Thus the gradient's specification should read as follows:
background-image: linear-gradient(to right, red, orange 50%, brown).
If we form the gradients using the above mentioned method and apply them to the element, we can get the required effect.
.red-orange-brown {_x000D_
background-image: linear-gradient(to right, red, orange 50%, brown);_x000D_
color: transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}_x000D_
.green-yellowgreen-yellow-gold {_x000D_
background-image: linear-gradient(to right, green, yellowgreen 33%, yellow 66%, gold);_x000D_
color: transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}
_x000D_
<span class="red-orange-brown">Red to Orange to Brown</span>_x000D_
_x000D_
<br>_x000D_
_x000D_
<span class="green-yellowgreen-yellow-gold">Green to Yellow-green to Yellow to Gold</span>
_x000D_
Splitting the data frame seems counter-productive. Instead, use the split-apply-combine paradigm, e.g., generate some data
df = data.frame(grp=sample(letters, 100, TRUE), x=rnorm(100))
then split only the relevant columns and apply the scale()
function to x in each group, and combine the results (using split<-
or ave
)
df$z = 0
split(df$z, df$grp) = lapply(split(df$x, df$grp), scale)
## alternative: df$z = ave(df$x, df$grp, FUN=scale)
This will be very fast compared to splitting data.frames, and the result remains usable in downstream analysis without iteration. I think the dplyr syntax is
library(dplyr)
df %>% group_by(grp) %>% mutate(z=scale(x))
In general this dplyr solution is faster than splitting data frames but not as fast as split-apply-combine.
You can cast the the json as follows:
Given your class:
export class Employee{
firstname: string= '';
}
and the json:
let jsonObj = {
"firstname": "Hesham"
};
You can cast it as follows:
let e: Employee = jsonObj as Employee;
And the output of console.log(e);
is:
{ firstname: 'Hesham' }
Panagiotis Kanavos is right, sometimes copy and paste T-SQL can make appear unwanted characters...
I finally found a simple and fast way (only Notepad++ needed) to detect which character is wrong, without having to manually rewrite the whole statement: there is no need to save any file to disk.
It's pretty quick, in Notepad++:
You should easily find the wrong character(s)
The simplest way is the platform-specific solution:
#!/usr/bin/env ruby
`wget http://somedomain.net/flv/sample/sample.flv`
Probably you are searching for:
require 'net/http'
# Must be somedomain.net instead of somedomain.net/, otherwise, it will throw exception.
Net::HTTP.start("somedomain.net") do |http|
resp = http.get("/flv/sample/sample.flv")
open("sample.flv", "wb") do |file|
file.write(resp.body)
end
end
puts "Done."
Edit: Changed. Thank You.
Edit2: The solution which saves part of a file while downloading:
# instead of http.get
f = open('sample.flv')
begin
http.request_get('/sample.flv') do |resp|
resp.read_body do |segment|
f.write(segment)
end
end
ensure
f.close()
end
By default, the classes in the csv
module use Windows-style line terminators (\r\n
) rather than Unix-style (\n
). Could this be what’s causing the apparent double line breaks?
If so, you can override it in the DictWriter
constructor:
output = csv.DictWriter(open('file3.csv','w'), delimiter=',', lineterminator='\n', fieldnames=headers)
Try This,
private void button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("[email protected]");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Just try:
if let url = NSURL(string: "tel://\(busPhone)") where UIApplication.sharedApplication().canOpenURL(url) {
UIApplication.sharedApplication().openURL(url)
}
assuming that the phone number is in busPhone
.
NSURL
's init(string:)
returns an Optional, so by using if let
we make sure that url
is a NSURL
(and not a NSURL?
as returned by the init
).
For Swift 3:
if let url = URL(string: "tel://\(busPhone)"), UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
We need to check whether we're on iOS 10 or later because:
'openURL' was deprecated in iOS 10.0
I don't think any of the current answers really do what you said you want. (Correction: I now see that @Gareth Latty / @Lattyware has incorporated my answer into his own as an "Edit" near the end.)
Anyway, here's my take:
Say these are the tab-separated values in your input file:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
then this:
with open("tab-separated-values.txt") as inp:
print( list(zip(*(line.strip().split('\t') for line in inp))) )
would produce the following:
[('1', '6', '11', '16'),
('2', '7', '12', '17'),
('3', '8', '13', '18'),
('4', '9', '14', '19'),
('5', '10', '15', '20')]
As you can see, it put the k-th element of each row into the k-th array.
in Vue 2.5.1 for button works
<button @click="firstFunction(); secondFunction();">Ok</button>
W3Schools is your friend: http://www.w3schools.com/php/func_filesystem_fgets.asp
And here: http://php.net/manual/en/function.fopen.php has more info on fopen including what the modes are.
What W3Schools says:
<?php
$file = fopen("test.txt","r");
while(! feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
fopen opens the file (in this case test.txt with mode 'r' which means read-only and places the pointer at the beginning of the file)
The while loop tests to check if it's at the end of file (feof) and while it isn't it calls fgets which gets the current line where the pointer is.
Continues doing this until it is the end of file, and then closes the file.
I prefer onKeyUp
since it only fires when the key is released. onKeyDown
, on the other hand, will fire multiple times if for some reason the user presses and holds the key. For example, when listening for "pressing" the Enter
key to make a network request, you don't want that to fire multiple times since it can be expensive.
// handler could be passed as a prop
<input type="text" onKeyUp={handleKeyPress} />
handleKeyPress(e) {
if (e.key === 'Enter') {
// do whatever
}
}
Also, stay away from keyCode
since it will be deprecated some time.
Before looking at the difference between java.lang.RuntimeException
and java.lang.Exception
classes, you must know the Exception
hierarchy. Both Exception
and Error
classes are derived from class Throwable
(which derives from the class Object
). And the class RuntimeException
is derived from class Exception
.
All the exceptions are derived either from Exception
or RuntimeException
.
All the exceptions which derive from RuntimeException
are referred to as unchecked exceptions. And all the other exceptions are checked exceptions. A checked exception must be caught somewhere in your code, otherwise, it will not compile. That is why they are called checked exceptions. On the other hand, with unchecked exceptions, the calling method is under no obligation to handle or declare it.
Therefore all the exceptions which compiler forces you to handle are directly derived from java.lang.Exception
and all the other which compiler does not force you to handle are derived from java.lang.RuntimeException
.
Following are some of the direct known subclasses of RuntimeException.
AnnotationTypeMismatchException,
ArithmeticException,
ArrayStoreException,
BufferOverflowException,
BufferUnderflowException,
CannotRedoException,
CannotUndoException,
ClassCastException,
CMMException,
ConcurrentModificationException,
DataBindingException,
DOMException,
EmptyStackException,
EnumConstantNotPresentException,
EventException,
IllegalArgumentException,
IllegalMonitorStateException,
IllegalPathStateException,
IllegalStateException,
ImagingOpException,
IncompleteAnnotationException,
IndexOutOfBoundsException,
JMRuntimeException,
LSException,
MalformedParameterizedTypeException,
MirroredTypeException,
MirroredTypesException,
MissingResourceException,
NegativeArraySizeException,
NoSuchElementException,
NoSuchMechanismException,
NullPointerException,
ProfileDataException,
ProviderException,
RasterFormatException,
RejectedExecutionException,
SecurityException,
SystemException,
TypeConstraintException,
TypeNotPresentException,
UndeclaredThrowableException,
UnknownAnnotationValueException,
UnknownElementException,
UnknownTypeException,
UnmodifiableSetException,
UnsupportedOperationException,
WebServiceException
If your array of objects is items
, you can do:
var items = [{_x000D_
id: 1,_x000D_
name: 'john'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'jane'_x000D_
}, {_x000D_
id: 2000,_x000D_
name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
Documentation: map()
The generic Returns<T>
method can handle this situation nicely.
_mock.Setup(x => x.DoSomething(It.IsAny<string>())).Returns<string>(x => x);
Or if the method requires multiple inputs, specify them like so:
_mock.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<int>())).Returns((string x, int y) => x);
enums are classes in Java. They have an implicit ordinal value, starting at 0. If you want to store an additional field, then you do it like for any other class:
public enum MyEnum {
ONE(1),
TWO(2);
private final int value;
private MyEnum(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
Well, TMK may be right in the Microsoft world, but in world of all software including Java/Python/etc, I believe that there is no difference. They're the same thing.
Once you're logged in as postgres
, you should be able to write:
psql -t -d database_name -c $'SELECT c_defaults FROM user_info WHERE c_uid = \'testuser\';'
to print out just the value of that field, which means that you can capture it to (for example) save in a Bash variable:
testuser_defaults="$(psql -t -d database_name -c $'SELECT c_defaults FROM user_info WHERE c_uid = \'testuser\';')"
To handle the logging in as postgres
, I recommend using sudo
. You can give a specific user the permission to run
sudo -u postgres /path/to/this/script.sh
so that they can run just the one script as postgres
.
double randDouble()
{
double out;
out = (double)rand()/(RAND_MAX + 1); //each iteration produces a number in [0, 1)
out = (rand() + out)/RAND_MAX;
out = (rand() + out)/RAND_MAX;
out = (rand() + out)/RAND_MAX;
out = (rand() + out)/RAND_MAX;
out = (rand() + out)/RAND_MAX;
return out;
}
Not quite as fast as double X=((double)rand()/(double)RAND_MAX);
, but with better distribution. That algorithm gives only RAND_MAX evenly spaced choice of return values; this one gives RANDMAX^6, so its distribution is limited only by the precision of double.
If you want a long double just add a few iterations. If you want a number in [0, 1] rather than [0, 1) just make line 4 read out = (double)rand()/(RAND_MAX);
.
I spent a day messing with CSS before I found anataliocs tip. Add wmode=transparent
as a parameter to the YouTube URL:
<iframe title=<your frame title goes here>
src="http://www.youtube.com/embed/K3j9taoTd0E?wmode=transparent"
scrolling="no"
frameborder="0"
width="640"
height="390"
style="border:none;">
</iframe>
This allows the iframe to inherit the z-index of its container so your opaque <div>
would be in front of the iframe.
You used data-datepicker="datepicker"
It must be date-provide="datepicker"
Also, you included 2 bootstrap stylesheets bootstrap.css
and bootstrap.min.css
I also prefer to use bootstrap-datepicker3.min.css
than datepicker.less
Full Html:
<html>
<head>
<title>DatePicker Demo</title>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="css/bootstrap-datepicker3.min.css">
<script src="js/jquery-1.7.1.js"></script>
<script src="js/bootstrap-datepicker.js"></script>
</head>
<body>
<form>
<div class="input">
<input data-provide="datepicker" class="small" type="text" value="01/05/2011">
</div>
</form>
</body>
</html>
you can get the product name like this
foreach ( $cart_object->cart_contents as $value ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $value['data'] );
if ( ! $_product->is_visible() ) {
echo $_product->get_title();
} else {
echo $_product->get_title();
}
}
import 'rxjs/add/operator/map';
&
npm install rxjs@6 rxjs-compat@6 --save
worked for me
This might not work for everyone, but I updated node and it fixed the issue for me when none of the above did
Square version of the toggle can be added by modifying the border radius
.switch {
position: relative;
display: inline-block;
width: 90px;
height: 36px;
}
.switch input {display:none;}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ca2222;
-webkit-transition: .4s;
transition: .4s;
border-radius: 6px;
}
.slider:before {
position: absolute;
content: "";
height: 34px;
width: 32px;
top: 1px;
left: 1px;
right: 1px;
bottom: 1px;
background-color: white;
transition: 0.4s;
border-radius: 6px;
}
input:checked + .slider {
background-color: #2ab934;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(55px);
}
.slider:after {
content:'OFF';
color: white;
display: block;
position: absolute;
transform: translate(-50%,-50%);
top: 50%;
left: 50%;
font-size: 10px;
font-family: Verdana, sans-serif;
}
input:checked + .slider:after {
content:'ON';
}
_x000D_
<label class="switch">
<input type="checkbox" id="togBtn">
<div class="slider"></div>
</label>
_x000D_
if it helps someone else, I had an activity with 2 layouts that I toggled on and off for visibilty, trying to emulate a kind of page1 > page2 structure. if they were on page 2 and pressed the back button I wanted them to go back to page 1, if they pressed the back button on page 1 it should still work as normal. Its pretty basic but it works
@Override
public void onBackPressed() {
// check if page 2 is open
RelativeLayout page2layout = (RelativeLayout)findViewById(R.id.page2layout);
if(page2layout.getVisibility() == View.VISIBLE){
togglePageLayout(); // my method to toggle the views
return;
}else{
super.onBackPressed(); // allows standard use of backbutton for page 1
}
}
hope it helps someone, cheers
That should be:
java -Dtest="true" -jar myApplication.jar
Then the following will return the value:
System.getProperty("test");
The value could be null
, though, so guard against an exception using a Boolean
:
boolean b = Boolean.parseBoolean( System.getProperty( "test" ) );
Note that the getBoolean
method delegates the system property value, simplifying the code to:
if( Boolean.getBoolean( "test" ) ) {
// ...
}
use DateTime.Now
try this:
DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
Reading the docs I find the section Passing Variables On The Command Line, that gives this example:
ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"
Others examples demonstrate how to load from JSON string (=1.2
) or file (=1.3
)
Normally the ON clause comes from the mapping's join columns, but the JPA 2.1 draft allows for additional conditions in a new ON clause.
See,
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#ON
If you hate numpy, get out RPy and your local copy of R, and use it instead.
(I would also echo to make you you really need to invert the matrix. In R, for example, linalg.solve and the solve() function don't actually do a full inversion, since it is unnecessary.)
SELECT * FROM big_table ORDER BY A DESC LIMIT 10
One cannot disable the browser back button functionality. The only thing that can be done is prevent them.
The below JavaScript code needs to be placed in the head section of the page where you don’t want the user to revisit using the back button:
<script>
function preventBack() {
window.history.forward();
}
setTimeout("preventBack()", 0);
window.onunload = function() {
null
};
</script>
Suppose there are two pages Page1.php
and Page2.php
and Page1.php
redirects to Page2.php
.
Hence to prevent user from visiting Page1.php
using the back button you will need to place the above script in the head section of Page1.php
.
For more information: Reference
"origin/master" refers to the reference poiting to the HEAD commit of branch "origin/master".
A reference is a human-friendly alias name to a Git object, typically a commit object.
"origin/master" reference only gets updated when you git push
to your remote (http://git-scm.com/book/en/v2/Git-Internals-Git-References#Remotes).
From within the root of your project, run:
cat .git/refs/remotes/origin/master
Compare the displayed commit ID with:
cat .git/refs/heads/master
They should be the same, and that's why Git says master
is up-to-date with origin/master
.
When you run
git fetch origin master
That retrieves new Git objects locally under .git/objects folder. And Git updates .git/FETCH_HEAD so that now, it points to the latest commit of the fetched branch.
So to see the differences between your current local branch, and the branch fetched from upstream, you can run
git diff HEAD FETCH_HEAD
awk '{print ""}{for(i=3;i<=NF;++i)printf $i" "}'
I would like to add to mentioned in the other answers the difference between volatile
, Interlocked
, and lock
:
The volatile keyword can be applied to fields of these types:
sbyte
, byte
, short
, ushort
, int
, uint
, char
, float
, and bool
.byte
, sbyte
, short
, ushort, int
, or uint
.IntPtr
and UIntPtr
.Other types, including double
and long
, cannot be marked "volatile"
because reads and writes to fields of those types cannot be guaranteed
to be atomic. To protect multi-threaded access to those types of
fields, use the Interlocked
class members or protect access using the
lock
statement.
I used JSONObject as shown below in Servlet.
JSONObject jsonReturn = new JSONObject();
NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);
map = new HashMap<String, String>();
map.put("Status", "Success");
map.put("FailureReason", "None");
map.put("DataElements", "2");
jsonReturn = new JSONObject();
jsonReturn.accumulate("Header", map);
List<String> list = new ArrayList<String>();
list.add(NhAdminTree);
list.add(userName);
jsonReturn.accumulate("Elements", list);
The Servlet returns this JSON object as shown below:
response.setContentType("application/json");
response.getWriter().write(jsonReturn.toString());
This Servlet is called from Browser using AngularJs as below
$scope.GetNeighborhoodTreeUsingPost = function(){
alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );
$http({
method: 'POST',
url : 'http://localhost:8080/EPortal/xlEPortalService',
headers: {
'Content-Type': 'application/json'
},
data : {
'action': 64,
'userName' : $scope.userName
}
}).success(function(data, status, headers, config){
alert("DATA.header.status : " + data.Header.Status);
alert("DATA.header.FailureReason : " + data.Header.FailureReason);
alert("DATA.header.DataElements : " + data.Header.DataElements);
alert("DATA.elements : " + data.Elements);
}).error(function(data, status, headers, config) {
alert(data + " : " + status + " : " + headers + " : " + config);
});
};
This code worked and it is showing correct data in alert dialog box:
Data.header.status : Success
Data.header.FailureReason : None
Data.header.DetailElements : 2
Data.Elements : Coma seperated string values i.e. NhAdminTree, userName
Mention that it is checked only in Windows
but i think it works perfect on other Operating Systems [Linux,MacOs,Solaris
] :).
I had 2 .jar
files in the same directory . I wanted from the one .jar
file to start the other .jar
file which is in the same directory.
The problem is that when you start it from the cmd
the current directory is system32
.
Warnings!
;][[;'57f2g34g87-8+9-09!2#@!$%^^&()
or ()%&$%^@#
it works well.ProcessBuilder
with the below as following:..
//The class from which i called this was the class `Main`
String path = getBasePathForClass(Main.class);
String applicationPath= new File(path + "application.jar").getAbsolutePath();
System.out.println("Directory Path is : "+applicationPath);
//Your know try catch here
//Mention that sometimes it doesn't work for example with folder `;][[;'57f2g34g87-8+9-09!2#@!$%^^&()`
ProcessBuilder builder = new ProcessBuilder("java", "-jar", applicationPath);
builder.redirectErrorStream(true);
Process process = builder.start();
//...code
getBasePathForClass(Class<?> classs)
:
/**
* Returns the absolute path of the current directory in which the given
* class
* file is.
*
* @param classs
* @return The absolute path of the current directory in which the class
* file is.
* @author GOXR3PLUS[StackOverFlow user] + bachden [StackOverFlow user]
*/
public static final String getBasePathForClass(Class<?> classs) {
// Local variables
File file;
String basePath = "";
boolean failed = false;
// Let's give a first try
try {
file = new File(classs.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
basePath = file.getParent();
} else {
basePath = file.getPath();
}
} catch (URISyntaxException ex) {
failed = true;
Logger.getLogger(classs.getName()).log(Level.WARNING,
"Cannot firgue out base path for class with way (1): ", ex);
}
// The above failed?
if (failed) {
try {
file = new File(classs.getClassLoader().getResource("").toURI().getPath());
basePath = file.getAbsolutePath();
// the below is for testing purposes...
// starts with File.separator?
// String l = local.replaceFirst("[" + File.separator +
// "/\\\\]", "")
} catch (URISyntaxException ex) {
Logger.getLogger(classs.getName()).log(Level.WARNING,
"Cannot firgue out base path for class with way (2): ", ex);
}
}
// fix to run inside eclipse
if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
|| basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
basePath = basePath.substring(0, basePath.length() - 4);
}
// fix to run inside netbeans
if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
basePath = basePath.substring(0, basePath.length() - 14);
}
// end fix
if (!basePath.endsWith(File.separator)) {
basePath = basePath + File.separator;
}
return basePath;
}
This is almost like the other answer but you don't need a scatter
plot at all, you can simply specify a scatter-plot-like format (fmt
-parameter) for errorbar
:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()
Result:
A list of the avaiable fmt
parameters can be found for example in the plot
documentation:
character description
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
's' square marker
'p' pentagon marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'_' hline marker
According to this bug, the issue was fixed in Workbench 5.2.38 for some people and perhaps 5.2.39 for others—can you upgrade to the latest version (5.2.40)?
Alternatively, it is possible to workaround with:
SELECT *,'' FROM my_table
Yes, ArrayList is an ordered collection and it maintains the insertion order.
Check the code below and run it:
public class ListExample {
public static void main(String[] args) {
List<String> myList = new ArrayList<String>();
myList.add("one");
myList.add("two");
myList.add("three");
myList.add("four");
myList.add("five");
System.out.println("Inserted in 'order': ");
printList(myList);
System.out.println("\n");
System.out.println("Inserted out of 'order': ");
// Clear the list
myList.clear();
myList.add("four");
myList.add("five");
myList.add("one");
myList.add("two");
myList.add("three");
printList(myList);
}
private static void printList(List<String> myList) {
for (String string : myList) {
System.out.println(string);
}
}
}
Produces the following output:
Inserted in 'order':
one
two
three
four
five
Inserted out of 'order':
four
five
one
two
three
For detailed information, please refer to documentation: List (Java Platform SE7)
Here is the code from MSDN and the link - Article Link, which you should check out for more detail.
<ComboBox Text="Is not open">
<ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>
You can specify the type of a variable before it to force its type. It's called (dynamic) casting (more information is here):
$string = "1654"
$integer = [int]$string
$string + 1
# Outputs 16541
$integer + 1
# Outputs 1655
As an example, the following snippet adds, to each object in $fileList
, an IntVal
property with the integer value of the Name
property, then sorts $fileList
on this new property (the default is ascending), takes the last (highest IntVal
) object's IntVal
value, increments it and finally creates a folder named after it:
# For testing purposes
#$fileList = @([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })
# OR
#$fileList = New-Object -TypeName System.Collections.ArrayList
#$fileList.AddRange(@([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })) | Out-Null
$highest = $fileList |
Select-Object *, @{ n = "IntVal"; e = { [int]($_.Name) } } |
Sort-Object IntVal |
Select-Object -Last 1
$newName = $highest.IntVal + 1
New-Item $newName -ItemType Directory
Sort-Object IntVal
is not needed so you can remove it if you prefer.
[int]::MaxValue = 2147483647
so you need to use the [long]
type beyond this value ([long]::MaxValue = 9223372036854775807
).
Preamble
below may work or may not, this is all given as-is, you and only you are responsible person in case of some damage, data loss and so on. But I hope things go smooth!
To undo make install
I would do (and I did) this:
Idea: check whatever script installs and undo this with simple bash script.
--prefix=$PWD/install
. For CMake, you can go to your build dir, open CMakeCache.txt, and fix CMAKE_INSTALL_PREFIX value.make install
again).make install
script installs into custom dir just same contents you want to remove from somewhere else (usually /usr/local
). So, we need a script.
3.1. Script should compare custom dir, with dir you want clean. I use this:anti-install.sh
RM_DIR=$1
PRESENT_DIR=$2
echo "Remove files from $RM_DIR, which are present in $PRESENT_DIR"
pushd $RM_DIR
for fn in `find . -iname '*'`; do
# echo "Checking $PRESENT_DIR/$fn..."
if test -f "$PRESENT_DIR/$fn"; then
# First try this, and check whether things go plain
echo "rm $RM_DIR/$fn"
# Then uncomment this, (but, check twice it works good to you).
# rm $RM_DIR/$fn
fi
done
popd
3.2. Now just run this script (it will go dry-run)
bash anti-install.sh <dir you want to clean> <custom installation dir>
E.g. You wan't to clean /usr/local, and your custom installation dir is /user/me/llvm.build/install, then it would be
bash anti-install.sh /usr/local /user/me/llvm.build/install
3.3. Check log carefully, if commands are good to you, uncomment rm $RM_DIR/$fn
and run it again. But stop! Did you really check carefully? May be check again?
Source to instructions: https://dyatkovskiy.com/2019/11/26/anti-make-install/
Good luck!
'sprintf' will work fine, if your first argument is a pointer to a character (a pointer to a character is an array in 'c'), you'll have to make sure you have enough space for all the digits and a terminating '\0'. For example, If an integer uses 32 bits, it has up to 10 decimal digits. So your code should look like:
int i;
char s[11];
...
sprintf(s,"%ld", i);
Please check to see if you are connected to the network if this is a domain member PC. Also, make sure you are not on a dual home PC as your routes may be incorrect due to network metrics. I had this issue when I could not connect to the domain the SQL windows authentication switched to the local PC account but registered it as a SQL authentication. Once I disabled my wireless adapter and rebooted, the Windows integration switched back to the domain account and authenticated fine. I had already set up Mixed mode as you had already done as well so the previous posts do not apply.
@ingsaurabh's answer is the way to go if you are using an onClick even. However, if you are using an onTouch event, you can select the different backgrounds (still the same as @ingsaurabh's example) by using view.setPressed()
.
See the following for more details: "Press and hold" button on Android needs to change states (custom XML selector) using onTouchListener
https://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html also has charts for locating methods and constructors.
The answer below is taken from Reading from Console: JAVA Scanner vs BufferedReader
When read an input from console, there are two options exists to achieve that. First using Scanner
, another using BufferedReader
. Both of them have different characteristics. It means differences how to use it.
Scanner treated given input as token. BufferedReader just read line by line given input as string. Scanner it self provide parsing capabilities just like nextInt(), nextFloat().
But, what is others differences between?
Scanner come with since JDK version 1.5 higher.
When should use Scanner, or Buffered Reader?
Look at the main differences between both of them, one using tokenized, others using stream line. When you need parsing capabilities, use Scanner instead. But, i am more comfortable with BufferedReader. When you need to read from a File, use BufferedReader, because it’s use buffer when read a file. Or you can use BufferedReader as input to Scanner.
Additionally, you can add with method function:
In HTML
<div [ngClass]="setClasses()">...</div>
In component.ts
// Set Dynamic Classes
setClasses() {
let classes = {
constantClass: true,
'conditional-class': this.item.id === 1
}
return classes;
}
Open (and close!) your PHP tags right after, and before, your textarea
tags:
<textarea style="width:350px; height:80px;" cols="42" rows="5" name="sitelink"><?php
if($siteLink_val) echo $siteLink_val;
?></textarea>
You can export the date using this command.
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
First you must load the data from the mysql server in to a array
Try winhttpjs.bat. It uses a winhttp request object that should be faster than
Msxml2.XMLHTTP as there isn't any DOM parsing of the response. It is capable to do requests with body and all HTTP methods.
call winhttpjs.bat http://somelink.com/something.html -saveTo c:\something.html
Instead of writing it in your code directly I suggest you make use of the dedicated <connectionStrings>
element in the .config file and retrieve it from there.
Also make use of the using
statement so that after usage your connection automatically gets closed and disposed of.
A great reference for finding connection strings: connectionstrings.com/sql-server-2008.
For Ubuntu xampp,
Go to /opt/lampp/etc/extra/
and open httpd-xampp.conf file and add below lines to get remote access,
Order allow,deny
Require all granted
Allow from all
in /opt/lampp/phpmyadmin section.
And restart lampp using, /opt/lampp/lampp restart
Follow the directions here, under "Setting up your project file."
Setting up your project file
You need to add libxml2.dylib to your project (don't put it in the Frameworks section). On the Mac, you'll find it at
/usr/lib/libxml2.dylib
and for the iPhone, you'll want the/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.0.sdk/usr/lib/libxml2.dylib
version.Since libxml2 is a .dylib (not a nice friendly .framework) we still have one more thing to do. Go to the Project build settings (Project->Edit Project Settings->Build) and find the "Search Paths". In "Header Search Paths" add the following path:
$(SDKROOT)/usr/include/libxml2
Also see the OP's answer.
Niko Lay: How about this simple solution? :)
`<input style="background-color:white; border:1px white solid;" onclick="this.select();" id="selectable" value="http://example.com/page.htm">`
.....
Code before:
<textarea rows="20" class="codearea" style="padding:5px;" readonly="readonly">
Code after:
<textarea rows="20" class="codearea" style="padding:5px;" readonly="readonly" onclick="this.select();" id="selectable">
Just this part onclick="this.select();" id="selectable" in my code worked fine. Selects all in my code box with one mouse click.
Thanks for help Niko Lay!
I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.
**Note have used Python 2.7 so some minor modification might be required for Python 3+
class a:
global d
d={}
def get_config(self,x):
if x=='GENESYS':
d['host'] = 'host name'
d['port'] = '15222'
return d
Calling get_config method using class instance in a separate python file:
from constant import a
class b:
a().get_config('GENESYS')
print a().get_config('GENESYS').get('host')
print a().get_config('GENESYS').get('port')
No, you still can't style the checkbox itself, but I (finally) figured out how to style an illusion while keeping the functionality of clicking a checkbox. It means that you can toggle it even if the cursor isn't perfectly still without risking selecting text or triggering drag-and-drop!
The example is using a span "button" as well as some text in a label, but it gives you the idea of how you can make the checkbox invisible and draw anything behind it.
This solution probably also fits radio buttons.
The following works in IE9, FF30.0 and Chrome 40.0.2214.91 and is just a basic example. You can still use it in combination with background images and pseudo-elements.
http://jsfiddle.net/o0xo13yL/1/
label {
display: inline-block;
position: relative; /* needed for checkbox absolute positioning */
background-color: #eee;
padding: .5rem;
border: 1px solid #000;
border-radius: .375rem;
font-family: "Courier New";
font-size: 1rem;
line-height: 1rem;
}
label > input[type="checkbox"] {
display: block;
position: absolute; /* remove it from the flow */
width: 100%;
height: 100%;
margin: -.5rem; /* negative the padding of label to cover the "button" */
cursor: pointer;
opacity: 0; /* make it transparent */
z-index: 666; /* place it on top of everything else */
}
label > input[type="checkbox"] + span {
display: inline-block;
width: 1rem;
height: 1rem;
border: 1px solid #000;
margin-right: .5rem;
}
label > input[type="checkbox"]:checked + span {
background-color: #666;
}
_x000D_
<label>
<input type="checkbox" />
<span> </span>Label text
</label>
_x000D_
It seems you don't want to keep the whole DataTable as a copy, because you only need some rows, right? If you got a creteria you can specify with a select on the table, you could copy just those rows to an extra backup array of DataRow like
DataRow[] rows = sourceTable.Select("searchColumn = value");
The .Select() function got several options and this one e.g. can be read as a SQL
SELECT * FROM sourceTable WHERE searchColumn = value;
Then you can import the rows you want as described above.
targetTable.ImportRows(rows[n])
...for any valid n you like, but the columns need to be the same in each table.
Some things you should know about ImportRow is that there will be errors during runtime when using primary keys!
First I wanted to check whether a row already existed which also failed due to a missing primary key, but then the check always failed. In the end I decided to clear the existing rows completely and import the rows I wanted again.
The second issue did help to understand what happens. The way I'm using the import function is to duplicate rows with an exchanged entry in one column. I realized that it always changed and it still was a reference to the row in the array. I first had to import the original and then change the entry I wanted.
The reference also explains the primary key errors that appeared when I first tried to import the row as it really was doubled up.
If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.
If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.
First install nodemon to your working folder by
npm install nodemon
Add the path of nodemon to the path variable of Environment Variable of System environment. In my case the path of nodemon was.
C:\Users\Dell\Desktop\Internship Project\schema\node_modules\.bin
It worked for me.
adding this line to the beginning of the file s worked for me:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
modifying the css to set the proper border properties did not work until i added the above line
You will have to set environmental variables properly for each compiler. There are commands on your Program menu for each compiler that does that, while opening a command prompt.
Another option is of course to use the IDE for building your application.
Interfaces and abstracted classes seem very similar, however, there are important differences between them.
Abstraction is based on a good "is-a" relationship. Meaning that you would say that a car is a Honda, and a Honda is a car. Using abstraction on a class means you can also have abstract methods. This would require any subclass extended from it to obtain the abstract methods and override them. Using the example below, we can create an abstract howToStart(); method that will require each class to implement it.
Through abstraction, we can provide similarities between code so we would still have a base class. Using an example of the Car class idea we could create:
public abstract class Car{
private String make;
private String model
protected Car() { } // Default constructor
protect Car(String make, String model){
//Assign values to
}
public abstract void howToStart();
}
Then with the Honda class we would have:
public class Honda extends implements Engine {
public Honda() { } // Default constructor
public Honda(String make, String model){
//Assign values
}
@Override
public static void howToStart(){
// Code on how to start
}
}
Interfaces are based on the "has-a" relationship. This would mean you could say a car has-a engine, but an engine is not a car. In the above example, Honda has implements Engine
.
For the engine interface we could create:
public interface Engine {
public void startup();
}
The interface will provide a many-to-one instance. So we could apply the Engine interface to any type of car. We can also extend it to other object. Like if we were to make a boat class, and have sub classes of boat types, we could extend Engine and have the sub classes of boat require the startup();
method. Interfaces are good for creating framework to various classes that have some similarities. We can also implement multiple instances in one class, such as:
public class Honda extends implements Engine, Transmission, List<Parts>
Hopefully this helps.
You can upload those .py files to Google drive and allow Colab to use to them:
!mkdir -p drive
!google-drive-ocamlfuse drive
All your files and folders in root folder will be in drive
.
changed from your code :
private String toDate(long timestamp) {
Date date = new Date (timestamp * 1000 - 24 * 60 * 60 * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date).toString();
}
but you do better using calendar.
This question has so many answers, rather using it in info.plist
you can set it in AppDelegate
like this:
#if compiler(>=5.1)
if #available(iOS 13.0, *) {
self.window?.overrideUserInterfaceStyle = .light
}
#endif
Test on Xcode 11.3, iOS 13.3
To get the directory, you can use the code below:
File cacheDir = new File(Environment.getExternalStorageDirectory() + File.separator + "");
It looks like Java is trying to convert an empty string into a number. Do you have an empty line at the end of the series of numbers?
You could probably fix the code like this
String s = in.readLine();
int i = 0;
while (s != null) {
// Skip empty lines.
s = s.trim();
if (s.length() == 0) {
continue;
}
tall[i] = Integer.parseInt(s); // This is line 19.
System.out.println(tall[i]);
s = in.readLine();
i++;
}
in.close();
If you are storing the type in your text
(as you should be in this scenario), you can use the JsonSerializerSettings
.
See: how to deserialize JSON into IEnumerable<BaseType> with Newtonsoft JSON.NET
Be careful, though. Using anything other than TypeNameHandling = TypeNameHandling.None
could open yourself up to a security vulnerability.
"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)
So you can't do anything about it, it is the issue of the server.
But you could use try .. except
block to handle that exception:
from socket import error as SocketError
import errno
try:
response = urllib2.urlopen(request).read()
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise # Not error we are looking for
pass # Handle error here.
Copy paste: •. I've done it with other weird characters, such as ? and ?.
Edit: here's an example. The two Button
s at the bottom have android:text="?"
and "?"
.
Unless you're talking about base 16 numbers (for which there's a method to parse as Hex), you need to explicitly separate out the part that you are interested in, and then convert it. After all, what would be the semantics of something like 23e44e11d in base 10?
Regular expressions could do the trick if you know for sure that you only have one number. Java has a built in regular expression parser.
If, on the other hands, your goal is to concatenate all the digits and dump the alphas, then that is fairly straightforward to do by iterating character by character to build a string with StringBuilder, and then parsing that one.
As you read through the examples below, just keep in mind this difference
true === true // true
"string" === true // false
1 === true // false
{} === true // false
But
Boolean("string") === true // true
Boolean(1) === true // true
Boolean({}) === true // true
Assertion passes when the statement passed to expect()
evaluates to true
expect(true).toBe(true) // pass
expect("123" === "123").toBe(true) // pass
In all other cases cases it would fail
expect("string").toBe(true) // fail
expect(1).toBe(true); // fail
expect({}).toBe(true) // fail
Even though all of these statements would evaluate to true
when doing Boolean()
:
So you can think of it as 'strict' comparison
This one does exactly the same type of comparison as .toBe(true)
, but was introduced in Jasmine recently in version 3.5.0
on Sep 20, 2019
toBeTruthy
on the other hand, evaluates the output of the statement into boolean first and then does comparison
expect(false).toBeTruthy() // fail
expect(null).toBeTruthy() // fail
expect(undefined).toBeTruthy() // fail
expect(NaN).toBeTruthy() // fail
expect("").toBeTruthy() // fail
expect(0).toBeTruthy() // fail
And IN ALL OTHER CASES it would pass, for example
expect("string").toBeTruthy() // pass
expect(1).toBeTruthy() // pass
expect({}).toBeTruthy() // pass
Apart from the fact that you do not need to throw from the constructor in your specific case because pthread_mutex_lock
actually returns an EINVAL if your mutex has not been initialized and you can throw after the call to lock
as is done in std::mutex
:
void
lock()
{
int __e = __gthread_mutex_lock(&_M_mutex);
// EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
if (__e)
__throw_system_error(__e);
}
then in general throwing from constructors is ok for acquisition errors during construction, and in compliance with RAII ( Resource-acquisition-is-Initialization ) programming paradigm.
Check this example on RAII
void write_to_file (const std::string & message) {
// mutex to protect file access (shared across threads)
static std::mutex mutex;
// lock mutex before accessing file
std::lock_guard<std::mutex> lock(mutex);
// try to open file
std::ofstream file("example.txt");
if (!file.is_open())
throw std::runtime_error("unable to open file");
// write message to file
file << message << std::endl;
// file will be closed 1st when leaving scope (regardless of exception)
// mutex will be unlocked 2nd (from lock destructor) when leaving
// scope (regardless of exception)
}
Focus on these statements:
static std::mutex mutex
std::lock_guard<std::mutex> lock(mutex);
std::ofstream file("example.txt");
The first statement is RAII and noexcept
. In (2) it is clear that RAII is applied on lock_guard
and it actually can throw
, whereas in (3) ofstream
seems not to be RAII , since the objects state has to be checked by calling is_open()
that checks the failbit
flag.
At first glance it seems that it is undecided on what it the standard way and in the first case std::mutex
does not throw in initialization , *in contrast to OP implementation * . In the second case it will throw whatever is thrown from std::mutex::lock
, and in the third there is no throw at all.
Notice the differences:
(1) Can be declared static, and will actually be declared as a member variable (2) Will never actually be expected to be declared as a member variable (3) Is expected to be declared as a member variable, and the underlying resource may not always be available.
All these forms are RAII; to resolve this, one must analyse RAII.
This does not require you to initialize and connect everything on construction. For example when you would create a network client object you would not actually connect it to the server upon creation, since it is a slow operation with failures. You would instead write a connect
function to do just that. On the other hand you could create the buffers or just set its state.
Therefore, your issue boils down to defining your initial state. If in your case your initial state is mutex must be initialized then you should throw from the constructor. In contrast it is just fine not to initialize then ( as is done in std::mutex
), and define your invariant state as mutex is created . At any rate the invariant is not compromized necessarily by the state of its member object, since the mutex_
object mutates between locked
and unlocked
through the Mutex
public methods Mutex::lock()
and Mutex::unlock()
.
class Mutex {
private:
int e;
pthread_mutex_t mutex_;
public:
Mutex(): e(0) {
e = pthread_mutex_init(&mutex_);
}
void lock() {
e = pthread_mutex_lock(&mutex_);
if( e == EINVAL )
{
throw MutexInitException();
}
else (e ) {
throw MutexLockException();
}
}
// ... the rest of your class
};
You'll have to use an HttpServletRequestWrapper:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
@Override
public String getHeader(String name) {
final String value = request.getParameter(name);
if (value != null) {
return value;
}
return super.getHeader(name);
}
};
chain.doFilter(wrapper, response);
}
Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames
for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.
add
compile 'com.mcxiaoke.volley:library:1.0.19'
compile project('volley')
in the dependencies, under build.gradle file of your app
DO NOT DISTURB THE build.gradle FILE OF YOUR LIBRARY. IT'S YOUR APP'S GRADLE FILE ONLY YOU NEED TO ALTER
This code is to solve our problem to set unique key for existing table
alter ignore table ioni_groups add unique (group_name);
I use this...but have never done any metro app development, so I don't know of any restrictions on libraries available to you. (note, you'll need to mark your classes as with DataContract and DataMember attributes)
public static class JSONSerializer<TType> where TType : class
{
/// <summary>
/// Serializes an object to JSON
/// </summary>
public static string Serialize(TType instance)
{
var serializer = new DataContractJsonSerializer(typeof(TType));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, instance);
return Encoding.Default.GetString(stream.ToArray());
}
}
/// <summary>
/// DeSerializes an object from JSON
/// </summary>
public static TType DeSerialize(string json)
{
using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(typeof(TType));
return serializer.ReadObject(stream) as TType;
}
}
}
So, if you had a class like this...
[DataContract]
public class MusicInfo
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Artist { get; set; }
[DataMember]
public string Genre { get; set; }
[DataMember]
public string Album { get; set; }
[DataMember]
public string AlbumImage { get; set; }
[DataMember]
public string Link { get; set; }
}
Then you would use it like this...
var musicInfo = new MusicInfo
{
Name = "Prince Charming",
Artist = "Metallica",
Genre = "Rock and Metal",
Album = "Reload",
AlbumImage = "http://up203.siz.co.il/up2/u2zzzw4mjayz.png",
Link = "http://f2h.co.il/7779182246886"
};
// This will produce a JSON String
var serialized = JSONSerializer<MusicInfo>.Serialize(musicInfo);
// This will produce a copy of the instance you created earlier
var deserialized = JSONSerializer<MusicInfo>.DeSerialize(serialized);
You can use tuples like this: SELECT * FROM table WHERE (Col, 1) IN ((123,1),(123,1),(222,1),....)
There are no restrictions on number of these. It compares pairs.
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
Had the same issue installing angular material CDK:
npm install --save @angular/material @angular/cdk @angular/animations
Adding -dev
like below worked for me:
npm install --save-dev @angular/material @angular/cdk @angular/animations
try this :
string getValue = Convert.ToString(cmd.ExecuteScalar());
In my case I used Framework64 like below
cd\
cd "C:\Windows\Microsoft.NET\Framework64\v4.0.30319"
installutil.exe "C:\XXX\Bin\ABC.exe"
pause
Using a jquery plugin I have adapted it to my needs adding customized options and creating a new plugin. You can find it here: https://github.com/david-dlc-cerezo/jquery-clearField
An example of a simple usage:
<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script src='http://code.jquery.com/ui/1.10.3/jquery-ui.js'></script>
<script src='src/jquery.clearField.js'></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="css/jquery.clearField.css">
<table>
<tr>
<td><input name="test1" id="test1" clas="test" type='text'></td>
<td>Empty</td>
</tr>
<tr>
<td><input name="test2" id="test2" clas="test" type='text' value='abc'></td>
<td>Not empty</td>
</tr>
</table>
<script>
$('.test').clearField();
</script>
Obtaining something like this:
Generally, no, do not define functions inside functions.
Unless you have a really good reason. Which you don't.
Why not?
lambda
expression instead.What is a really good reason to define functions inside functions?
When what you actually want is a dingdang closure.
M-x replace-string
RET ;
RET C-q C-j.
C-q for quoted-insert
,
C-j is a newline.
Cheers!
$("input[name='mygroup'][value='5']").attr("checked", true);
Instead of installing a library inside Jupyter, I would recommend you use the 'Dark Reader' extension in Chrome (you can find 'Dark Reader' extension in other browsers, e.g. Firefox). You can play with it; filter the URL(s) you want to have dark theme, or even how define the Dark theme for yourself. Below are couple of examples:
I hope it helps.
If your interested , then go with directive property . Code might looks bit tough , but itshows all the property of Angular 6 . Here am adding a sample code
import { Directive, OnInit, ElementRef, Renderer2 ,HostListener,HostBinding,Input} from '@angular/core';
import { MockNgModuleResolver } from '@angular/compiler/testing';
//import { Event } from '@angular/router';
@Directive({
selector: '[appBetterHighlight]'
})
export class BetterHighlightDirective implements OnInit {
defaultcolor :string = 'black'
Highlightedcolor : string = 'red'
@HostBinding('style.color') color : string = this.defaultcolor;
constructor(private elm : ElementRef , private render:Renderer2) { }
ngOnInit()
{}
@HostListener('mouseenter') mouseover(event :Event)
{
this.color= this.Highlightedcolor ;
}
@HostListener('mouseleave') mouseleave(event: Event)
{
this.color = this.defaultcolor;
}
}
Just use the selector name 'appBetterHighlight' anywhere in the template to access this property .
Goto
Another option is
if (myString?.trim()) {
...
}
PostgreSQL understands the
select column_name from information_schema.columns where table_name = 'myTable'
syntax. If you're working in the psql shell, you can also use
\d myTable
for a description (columns, and their datatypes and constraints)
Random r = new Random();
int i1 = r.nextInt(45 - 28) + 28;
This gives a random integer between 28 (inclusive) and 45 (exclusive), one of 28,29,...,43,44.
The above method for Visual Studio didn't seem to apply to Visual Studio 2013, but I was able to find the described checkbox using the Project Menu and selecting my project (probably the last item on the submenu) to get to the dialog with the checkbox (on the Build tab).
My personal preference is not to save the images to a database as such. Save the image somewhere in the file system and save a reference in the database.
if ( 100 < 500 ) {
//any action
}
else if ( 100 > 500 ){
//any another action
}
Easy, use space
If (theChar >= '0' && theChar <='9')
it's a digit. You get the idea.
I think the problem is the way you call your javascript function. Your code is like so:
<input type="button" onclick="javascript: myFunc(myID)" value="button"/>
myID should be wrapped in quotes.
CREATE TRIGGER sampleTrigger
ON database1.dbo.table1
FOR DELETE
AS
DELETE FROM database2.dbo.table2
WHERE bar = 4 AND ID IN(SELECT deleted.id FROM deleted)
GO
"user.dir" is the current working directory, not the home directory It is all described here.
http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
Also, by using \\
instead of File.separator, you will lose portability with *nix system which uses /
for file separator.
I suggest using Object.prototype.constructor.name
:
Object.defineProperty(Object.prototype, "getClass", {
value: function() {
return this.constructor.name;
}
});
var x = new DOMParser();
console.log(x.getClass()); // `DOMParser'
var y = new Error("");
console.log(y.getClass()); // `Error'
The MyKey class must implement Serializable
if you are using @IdClass
You just need to correct the format of your html
<form>
<li>Number 1: <input type="text" ng-model="one"/> </li>
<li>Number 2: <input type="text" ng-model="two"/> </li>
<li>Total <input type="text" value="{{total()}}"/> </li>
{{total()}}
</form>
if you have any problem with the library you can use Microsoft.Data.Sqlite;
public static DataTable GetData(string connectionString, string query)
{
DataTable dt = new DataTable();
Microsoft.Data.Sqlite.SqliteConnection connection;
Microsoft.Data.Sqlite.SqliteCommand command;
connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source= YOU_PATH_BD.sqlite");
try
{
connection.Open();
command = new Microsoft.Data.Sqlite.SqliteCommand(query, connection);
dt.Load(command.ExecuteReader());
connection.Close();
}
catch
{
}
return dt;
}
you can add NuGet Package Microsoft.Data.Sqlite
The error MethodNotAllowedHttpException means the route exists, but the HTTP method (GET) is wrong. You have to change it to POST:
Route::post('test/register', array('uses'=>'TestController@create'));
Also, you need to hash your passwords:
public function create()
{
$user = new User;
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::back();
}
And I removed the line:
$user= Input::all();
Because in the next command you replace its contents with
$user = new User;
To debug your Input, you can, in the first line of your controller:
dd( Input::all() );
It will display all fields in the input.
You were just adding the html string. Not the element you created with a click event listener.
Try This:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
<table id="addNodeTable">
<tr>
<td>
Row 1
</td>
</tr>
<tr >
<td>
Row 2
</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
var test = $('<button>Test</button>').click(function () {
alert('hi');
});
$("#addNodeTable tr:last").append('<tr><td></td></tr>').find("td:last").append(test);
});
</script>
You should use django methods, like exists. Its there for you to use it.
if qs.exists():
return qs[0]
return None
I don't think min/max validations attribute exist. I would use something like
[Range(1, Int32.MaxValue)]
for minimum value 1 and
[Range(Int32.MinValue, 10)]
for maximum value 10
While working with selected cells as shown by @tbur can be useful, it's also not the only option available.
You can use Range() like so:
If Worksheets("Sheet1").Range("A1").MergeCells Then
Do something
Else
Do something else
End If
Or:
If Worksheets("Sheet1").Range("A1:C1").MergeCells Then
Do something
Else
Do something else
End If
Alternately, you can use Cells():
If Worksheets("Sheet1").Cells(1, 1).MergeCells Then
Do something
Else
Do something else
End If
Here's the code I put together based on example from this blog: LINK and this source: LINK.
import com.sun.jndi.ldap.LdapCtxFactory;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.AuthenticationException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import static javax.naming.directory.SearchControls.SUBTREE_SCOPE;
class App2 {
public static void main(String[] args) {
if (args.length != 4 && args.length != 2) {
System.out.println("Purpose: authenticate user against Active Directory and list group membership.");
System.out.println("Usage: App2 <username> <password> <domain> <server>");
System.out.println("Short usage: App2 <username> <password>");
System.out.println("(short usage assumes 'xyz.tld' as domain and 'abc' as server)");
System.exit(1);
}
String domainName;
String serverName;
if (args.length == 4) {
domainName = args[2];
serverName = args[3];
} else {
domainName = "xyz.tld";
serverName = "abc";
}
String username = args[0];
String password = args[1];
System.out
.println("Authenticating " + username + "@" + domainName + " through " + serverName + "." + domainName);
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + "@" + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS, password);
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance("ldap://" + serverName + "." + domainName + '/', props);
System.out.println("Authentication succeeded!");
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),
"(& (userPrincipalName=" + principalName + ")(objectClass=user))", controls);
if (!renum.hasMore()) {
System.out.println("Cannot locate user information for " + username);
System.exit(1);
}
SearchResult result = renum.next();
List<String> groups = new ArrayList<String>();
Attribute memberOf = result.getAttributes().get("memberOf");
if (memberOf != null) {// null if this user belongs to no group at all
for (int i = 0; i < memberOf.size(); i++) {
Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" });
Attribute att = atts.get("CN");
groups.add(att.get().toString());
}
}
context.close();
System.out.println();
System.out.println("User belongs to: ");
Iterator ig = groups.iterator();
while (ig.hasNext()) {
System.out.println(" " + ig.next());
}
} catch (AuthenticationException a) {
System.out.println("Authentication failed: " + a);
System.exit(1);
} catch (NamingException e) {
System.out.println("Failed to bind to LDAP / get account information: " + e);
System.exit(1);
}
}
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if (token.length() == 0)
continue; // defensive check
if (buf.length() > 0)
buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
}
There are several ways to prevent line breaks in content. Using
is one way, and works fine between words, but using it between an empty element and some text does not have a well-defined effect. The same would apply to the more logical and more accessible approach where you use an image for an icon.
The most robust alternative is to use nobr
markup, which is nonstandard but universally supported and works even when CSS is disabled:
<td><nobr><i class="flag-bfh-ES"></i> +34 666 66 66 66</nobr></td>
(You can, but need not, use
instead of spaces in this case.)
Another way is the nowrap
attribute (deprecated/obsolete, but still working fine, except for some rare quirks):
<td nowrap><i class="flag-bfh-ES"></i> +34 666 66 66 66</td>
Then there’s the CSS way, which works in CSS enabled browsers and needs a bit more code:
<style>
.nobr { white-space: nowrap }
</style>
...
<td class=nobr><i class="flag-bfh-ES"></i> +34 666 66 66 66</td>
If you want to pull a particular file from another branch just do
git checkout branch1 -- filenamefoo.txt
This will pull a version of the file from one branch into the current tree
If you want to save the image and you know its URL you can do this:
try(InputStream in = new URL("http://example.com/image.jpg").openStream()){
Files.copy(in, Paths.get("C:/File/To/Save/To/image.jpg"));
}
You will also need to handle the IOException
s which may be thrown.
This is minor usage is tilde...
def split_train_test_by_id(data, test_ratio, id_column):
ids = data[id_column]
in_test_set = ids.apply(lambda id_: test_set_check(id_, test_ratio))
return data.loc[~in_test_set], data.loc[in_test_set]
the code above is from "Hands On Machine Learning"
you use tilde (~ sign) as alternative to - sign index marker
just like you use minus - is for integer index
ex)
array = [1,2,3,4,5,6]
print(array[-1])
is the samething as
print(array[~1])
TypeScript 0.9+ has a specification for enums:
enum AnimationType {
BOUNCE,
DROP,
}
The final comma is optional.
To emphasize a point made by @MatteoItalia, the efficiency difference is where the data is stored. Heap memory (required with vector
) requires a call to the system to allocate memory and this can be expensive if you are counting cycles. Stack memory (possible for array
) is virtually "zero-overhead" in terms of time, because the memory is allocated by just adjusting the stack pointer and it is done just once on entry to a function. The stack also avoids memory fragmentation. To be sure, std::array
won't always be on the stack; it depends on where you allocate it, but it will still involve one less memory allocation from the heap compared to vector. If you have a
definitely use a std::array
over a vector. If any of those requirements is not true, then use a std::vector
.
$variable[0] != "_"
In PHP you can get particular character of a string with array index notation. $variable[0]
is the first character of a string (if $variable is a string).
I think you're looking for the ndenumerate.
>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
... print x,y
...
0 0
0 1
1 0
1 1
2 0
2 1
Regarding the performance. It is a bit slower than a list comprehension.
X = np.zeros((100, 100, 100))
%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop
%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop
If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate
, which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords
attribute of the flat iterator.
a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop
What worked for me :
spyder
ex : /home/you/anaconda3/envs/your_env/bin/pythonWorked on ubuntu 16, spyder3, python3.6.
Aggregation of all postgres sessions per their status (how many are idle, how many doing something...)
select state, count(*) from pg_stat_activity where pid <> pg_backend_pid() group by 1 order by 1;
Please take a look here
HH is hour in a day (starting from 0 to 23)
hh are hours in am/pm format
kk is hour in day (starting from 1 to 24)
mm is minute in hour
ss are the seconds in a minute
Edit: Hash versus Array
As cincodenada correctly pointed out in the comment, ysth gave a better answer: I should have answered your question with another question: "Do you really want to use a Perl array? A hash may be more appropriate."
An array allocates memory for all possible indices up to the largest used so-far. In your example, you allocate 24 cells (but use only 3). By contrast, a hash only allocates space for those fields that are actually used.
Array solution: scalar grep
Here are two possible solutions (see below for explanation):
print scalar(grep {defined $_} @a), "\n"; # prints 3
print scalar(grep $_, @a), "\n"; # prints 3
Explanation: After adding $a[23]
, your array really contains 24 elements --- but most of them are undefined (which also evaluates as false). You can count the number of defined elements (as done in the first solution) or the number of true elements (second solution).
What is the difference? If you set $a[10]=0
, then the first solution will count it, but the second solution won't (because 0 is false but defined). If you set $a[3]=undef
, none of the solutions will count it.
Hash solution (by yst)
As suggested by another solution, you can work with a hash and avoid all the problems:
$a{0} = 1;
$a{5} = 2;
$a{23} = 3;
print scalar(keys %a), "\n"; # prints 3
This solution counts zeros and undef values.
With 500k documents, there is no reason to scale whatsoever. A typical laptop with an SSD and 8GB of ram can easily do 10s of millions of records, so if you are trying to pick because of scaling your choice doesn't really matter. I would suggest you pick what you like the most, and perhaps where you can find the most online support with.
I came across this myself. I used .on
so it looks a bit different but I did this:
$('#element').on('keypress', function() {
//code to be executed
}).on('keydown', function(e) {
if (e.keyCode==8)
$('element').trigger('keypress');
});
Adding my Work Around here. I needed to delete ssn typed by user so i did this in jQuery
$(this).bind("keydown", function (event) {
// Allow: backspace, delete
if (event.keyCode == 46 || event.keyCode == 8)
{
var tempField = $(this).attr('name');
var hiddenID = tempField.substr(tempField.indexOf('_') + 1);
$('#' + hiddenID).val('');
$(this).val('')
return;
} // Allow: tab, escape, and enter
else if (event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else
{
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))
{
event.preventDefault();
}
}
});
as of the django development, there exists bulk_create
as an object manager method which takes as input an array of objects created using the class constructor. check out django docs
var appBanners = document.getElementsByClassName('appBanner');
for (var i = 0; i < appBanners.length; i ++) {
appBanners[i].style.display = 'none';
}
It looks like there's something else called Afisho_rankimin
in your DB so the function is not being created. Try calling your function something else. E.g.
CREATE FUNCTION dbo.Afisho_rankimin1(@emri_rest int)
RETURNS int
AS
BEGIN
Declare @rankimi int
Select @rankimi=dbo.RESTORANTET.Rankimi
From RESTORANTET
Where dbo.RESTORANTET.ID_Rest=@emri_rest
RETURN @rankimi
END
GO
Note that you need to call this only once, not every time you call the function. After that try calling
SELECT dbo.Afisho_rankimin1(5) AS Rankimi
Note: This code was originally included in the question above. In the interests of keeping the question short and focused, I've moved it to this Community Wiki answer.
I found this code kicking around and it appears to work fine for getting a random number and then using the seed afterward but I'm not quite sure how the logic works (e.g. where the 2345678901, 48271 & 2147483647 numbers came from).
function nextRandomNumber(){
var hi = this.seed / this.Q;
var lo = this.seed % this.Q;
var test = this.A * lo - this.R * hi;
if(test > 0){
this.seed = test;
} else {
this.seed = test + this.M;
}
return (this.seed * this.oneOverM);
}
function RandomNumberGenerator(){
var d = new Date();
this.seed = 2345678901 + (d.getSeconds() * 0xFFFFFF) + (d.getMinutes() * 0xFFFF);
this.A = 48271;
this.M = 2147483647;
this.Q = this.M / this.A;
this.R = this.M % this.A;
this.oneOverM = 1.0 / this.M;
this.next = nextRandomNumber;
return this;
}
function createRandomNumber(Min, Max){
var rand = new RandomNumberGenerator();
return Math.round((Max-Min) * rand.next() + Min);
}
//Thus I can now do:
var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var numbers = ['1','2','3','4','5','6','7','8','9','10'];
var colors = ['red','orange','yellow','green','blue','indigo','violet'];
var first = letters[createRandomNumber(0, letters.length)];
var second = numbers[createRandomNumber(0, numbers.length)];
var third = colors[createRandomNumber(0, colors.length)];
alert("Today's show was brought to you by the letter: " + first + ", the number " + second + ", and the color " + third + "!");
/*
If I could pass my own seed into the createRandomNumber(min, max, seed);
function then I could reproduce a random output later if desired.
*/
I had the same problem. Here's what I figured out:
=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")
A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.
The issue HttpServletRequest.login does not set authentication state in session has been fixed in 3.0.1. Update glassfish to the latest version and you're done.
Updating is quite straightforward:
glassfishv3/bin/pkg set-authority -P dev.glassfish.org
glassfishv3/bin/pkg image-update
This is how you can dynamically create a class named Child
in your code, assuming Parent
already exists... even if you don't have an explicit Parent
class, you could use object
...
The code below defines __init__()
and then associates it with the class.
>>> child_name = "Child"
>>> child_parents = (Parent,)
>>> child body = """
def __init__(self, arg1):
# Initialization for the Child class
self.foo = do_something(arg1)
"""
>>> child_dict = {}
>>> exec(child_body, globals(), child_dict)
>>> childobj = type(child_name, child_parents, child_dict)
>>> childobj.__name__
'Child'
>>> childobj.__bases__
(<type 'object'>,)
>>> # Instantiating the new Child object...
>>> childinst = childobj()
>>> childinst
<__main__.Child object at 0x1c91710>
>>>
You don't need to convert it at all:
% perl -e 'print "5.45" + 0.1;'
5.55
This is a comprehensive answer to this question. I have done this because this page is high on the Google search results and the answer does not go into enough detail. This post assumes that you are competent at using Visual Studio C# forms. This is based on VS2012.
Start by simply dragging a ContextMenuStrip onto the form. It will just put it into the top left corner where you can add your menu items and rename it as you see fit.
You will have to view code and enter in an event yourself on the form. Create a mouse down event for the item in question and then assign a right click event for it like so (I have called the ContextMenuStrip "rightClickMenuStrip"):
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
switch (e.Button)
{
case MouseButtons.Right:
{
rightClickMenuStrip.Show(this, new Point(e.X, e.Y));//places the menu at the pointer position
}
break;
}
}
Assign the event handler manually to the form.designer (you may need to add a "using" for System.Windows.Forms; You can just resolve it):
this.pictureBox1.MouseDown += new MouseEventHandler(this.pictureBox1_MouseDown);
All that is needed at this point is to simply double click each menu item and do the desired operations for each click event in the same way you would for any other button.
This is the basic code for this operation. You can obviously modify it to fit in with your coding practices.
You can use this code for number validation:
if (!preg_match("/^[0-9]+$/i", $phone)) {
$errorMSG = 'Invalid Number!';
$error = 1;
}
For people who have no experience in building websites (like me) I tried a lot, only to find out that I hadn't used the .php
extension, but the .html
extension.
Not sure about List<T> but Arrays are certainly do-able. And a little bit of magic makes it really easy to get to a List again.
public class UserHolder {
[XmlElement("list")]
public User[] Users { get; set; }
[XmlIgnore]
public List<User> UserList { get { return new List<User>(Users); } }
}
First You have to inject HttpClient
and Not HttpClientModule
,
second thing you have to remove .map((res:any) => res.json())
you won't need it any more because the new HttpClient
will give you the body of the response by default , finally make sure that you import HttpClientModule
in your AppModule
:
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AppSettingsService {
constructor(private http: HttpClient) {
this.getJSON().subscribe(data => {
console.log(data);
});
}
public getJSON(): Observable<any> {
return this.http.get("./assets/mydata.json");
}
}
to add this to your Component:
@Component({
selector: 'mycmp',
templateUrl: 'my.component.html',
styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
constructor(
private appSettingsService : AppSettingsService
) { }
ngOnInit(){
this.appSettingsService.getJSON().subscribe(data => {
console.log(data);
});
}
}
If you cannot see the "Scripts" tab, make sure you are launching Chrome with the right arguments. I had this problem when I launched Chrome for debugging server-side JavaScript with the argument --remote-shell-port=9222
. I have no problem if I launch Chrome with no argument.
Add a common class to all the div. For example add foo to all the divs.
$('.foo').each(function () {
$(this).dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
});
in swift ;)
UPDATE SWIFT 3.0 :D
func sFunc_imageFixOrientation(img:UIImage) -> UIImage {
// No-op if the orientation is already correct
if (img.imageOrientation == UIImageOrientation.up) {
return img;
}
// We need to calculate the proper transformation to make the image upright.
// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
var transform:CGAffineTransform = CGAffineTransform.identity
if (img.imageOrientation == UIImageOrientation.down
|| img.imageOrientation == UIImageOrientation.downMirrored) {
transform = transform.translatedBy(x: img.size.width, y: img.size.height)
transform = transform.rotated(by: CGFloat(M_PI))
}
if (img.imageOrientation == UIImageOrientation.left
|| img.imageOrientation == UIImageOrientation.leftMirrored) {
transform = transform.translatedBy(x: img.size.width, y: 0)
transform = transform.rotated(by: CGFloat(M_PI_2))
}
if (img.imageOrientation == UIImageOrientation.right
|| img.imageOrientation == UIImageOrientation.rightMirrored) {
transform = transform.translatedBy(x: 0, y: img.size.height);
transform = transform.rotated(by: CGFloat(-M_PI_2));
}
if (img.imageOrientation == UIImageOrientation.upMirrored
|| img.imageOrientation == UIImageOrientation.downMirrored) {
transform = transform.translatedBy(x: img.size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
}
if (img.imageOrientation == UIImageOrientation.leftMirrored
|| img.imageOrientation == UIImageOrientation.rightMirrored) {
transform = transform.translatedBy(x: img.size.height, y: 0);
transform = transform.scaledBy(x: -1, y: 1);
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx:CGContext = CGContext(data: nil, width: Int(img.size.width), height: Int(img.size.height),
bitsPerComponent: img.cgImage!.bitsPerComponent, bytesPerRow: 0,
space: img.cgImage!.colorSpace!,
bitmapInfo: img.cgImage!.bitmapInfo.rawValue)!
ctx.concatenate(transform)
if (img.imageOrientation == UIImageOrientation.left
|| img.imageOrientation == UIImageOrientation.leftMirrored
|| img.imageOrientation == UIImageOrientation.right
|| img.imageOrientation == UIImageOrientation.rightMirrored
) {
ctx.draw(img.cgImage!, in: CGRect(x:0,y:0,width:img.size.height,height:img.size.width))
} else {
ctx.draw(img.cgImage!, in: CGRect(x:0,y:0,width:img.size.width,height:img.size.height))
}
// And now we just create a new UIImage from the drawing context
let cgimg:CGImage = ctx.makeImage()!
let imgEnd:UIImage = UIImage(cgImage: cgimg)
return imgEnd
}
First argument in update
method is SyntheticEvent
object that contains common properties and methods to any event
, it is not reference to React component where there is property props
.
if you need pass argument to update method you can do it like this
onClick={ (e) => this.props.onClick(e, 'home', 'Home') }
and get these arguments inside update
method
update(e, space, txt){
console.log(e.target, space, txt);
}
event.target
gives you the native DOMNode
, then you need to use the regular DOM APIs to access attributes. For instance getAttribute
or dataset
<button
data-space="home"
className="home"
data-txt="Home"
onClick={ this.props.onClick }
/>
Button
</button>
onClick(e) {
console.log(e.target.dataset.txt, e.target.dataset.space);
}
For me on CentOS 6.x:
sudo chown -R mongodb:mongodb <db-path>
sudo service mongod restart
And I have set a custom db-path
in /etc/mongod.conf
.
>>> print 5.0 / 2
2.5
>>> print 5.0 // 2
2.0
The problem is that you have a date formatted like this:
Thu Jun 18 20:56:02 EDT 2009
But are using a SimpleDateFormat
that is:
yyyy-MM-dd
The two formats don't agree. You need to construct a SimpleDateFormat
that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat
like this:
EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009
Check the JavaDoc page I linked to and see how the characters are used.
Use the backslash before db on the header and you can use it then typically as you wrote it before.
Here is the example:
Use \DB;
Then inside your controller class you can use as you did before, like that ie :
$item = DB::table('items')->get();
var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element
finally solved my problem.
I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.
A more generic solution for might be the following.
extendDf <- function (df, n) {
withFactors <- sum(sapply (df, function(X) (is.factor(X)) )) > 0
nr <- nrow (df)
colNames <- names(df)
for (c in 1:length(colNames)) {
if (is.factor(df[,c])) {
col <- vector (mode='character', length = nr+n)
col[1:nr] <- as.character(df[,c])
col[(nr+1):(n+nr)]<- rep(col[1], n) # to avoid extra levels
col <- as.factor(col)
} else {
col <- vector (mode=mode(df[1,c]), length = nr+n)
class(col) <- class (df[1,c])
col[1:nr] <- df[,c]
}
if (c==1) {
newDf <- data.frame (col ,stringsAsFactors=withFactors)
} else {
newDf[,c] <- col
}
}
names(newDf) <- colNames
newDf
}
The function extendDf() extends a data frame with n rows.
As an example:
aDf <- data.frame (l=TRUE, i=1L, n=1, c='a', t=Sys.time(), stringsAsFactors = TRUE)
extendDf (aDf, 2)
# l i n c t
# 1 TRUE 1 1 a 2016-07-06 17:12:30
# 2 FALSE 0 0 a 1970-01-01 01:00:00
# 3 FALSE 0 0 a 1970-01-01 01:00:00
system.time (eDf <- extendDf (aDf, 100000))
# user system elapsed
# 0.009 0.002 0.010
system.time (eDf <- extendDf (eDf, 100000))
# user system elapsed
# 0.068 0.002 0.070
You aren't trying to save unicode strings, you're trying to save bytestrings in the UTF-8 encoding. Make them actual unicode string literals:
user.last_name = u'Slatkevicius'
or (when you don't have string literals) decode them using the utf-8 encoding:
user.last_name = lastname.decode('utf-8')
I found the most easiest way to find sum of all the elements of a vector
#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<int>v(10,1);
int sum=0;
for(int i=0;i<v.size();i++)
{
sum+=v[i];
}
cout<<sum<<endl;
}
In this program, I have a vector of size 10 and are initialized by 1. I have calculated the sum by a simple loop like in array.
.newLine() is the best if your system property line.separator is proper . and sometime you don't want to change the property runtime . So alternative solution is appending \n
Try this:
function getYesterdaysDate() {
var date = new Date();
date.setDate(date.getDate()-1);
return date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
}
Get comfortable with zip
. It comes in handy when dealing with column data.
df['new_col'] = list(zip(df.lat, df.long))
It's less complicated and faster than using apply
or map
. Something like np.dstack
is twice as fast as zip
, but wouldn't give you tuples.
Swift 4 & 4.2 version:
self.navigationController.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.green]
I changed a few lines of the source of stat_smooth
and related functions to make a new function that adds the fit equation and R squared value. This will work on facet plots too!
library(devtools)
source_gist("524eade46135f6348140")
df = data.frame(x = c(1:100))
df$y = 2 + 5 * df$x + rnorm(100, sd = 40)
df$class = rep(1:2,50)
ggplot(data = df, aes(x = x, y = y, label=y)) +
stat_smooth_func(geom="text",method="lm",hjust=0,parse=TRUE) +
geom_smooth(method="lm",se=FALSE) +
geom_point() + facet_wrap(~class)
I used the code in @Ramnath's answer to format the equation. The stat_smooth_func
function isn't very robust, but it shouldn't be hard to play around with it.
https://gist.github.com/kdauria/524eade46135f6348140. Try updating ggplot2
if you get an error.
First of all svn status has the revision number, you can read it from there.
Also, each file that you store in SVN can store the revision number in itself -- add the $Rev$
keyword to your file and run propset: svn propset svn:keywords "Revision" file
Finally, the revision number is also in .svn/entries
file, fourth line
Now each time you checkout that file, it will have the revision in itself.
CSS:
table {
table-layout:fixed;
}
Update with CSS from the comments:
td {
overflow: hidden;
text-overflow: ellipsis;
word-wrap: break-word;
}
For mobile phones I leave the table width but assign an additional CSS class to the table to enable horizontal scrolling (table will not go over the mobile screen anymore):
@media only screen and (max-width: 480px) {
/* horizontal scrollbar for tables if mobile screen */
.tablemobile {
overflow-x: auto;
display: block;
}
}
Sufficient enough.
If you want to see the full paths, I would recommend to cd
to the top directory (of your drive if using windows)
cd C:\
grep -r somethingtosearch C:\Users\Ozzesh\temp
Or on Linux:
cd /
grep -r somethingtosearch ~/temp
if you really resist on your file name filtering (*.log) AND you want recursive
(files are not all in the same directory), combining find
and grep
is the most flexible way:
cd /
find ~/temp -iname '*.log' -type f -exec grep somethingtosearch '{}' \;
Yes, there is a command to find the size of a database in Postgres. It's the following:
SELECT pg_database.datname as "database_name", pg_size_pretty(pg_database_size(pg_database.datname)) AS size_in_mb FROM pg_database ORDER by size_in_mb DESC;
$.each
is slower than a for
loop$("#mySelect").append();
So the best solution is the following
If JSON data resp
is
[
{"id":"0001", "name":"Mr. P"},
{"id":"0003", "name":"Mr. Q"},
{"id":"0054", "name":"Mr. R"},
{"id":"0061", "name":"Mr. S"}
]
use it as
var option = "";
for (i=0; i<resp.length; i++) {
option += "<option value='" + resp[i].id + "'>" + resp[i].name + "</option>";
}
$('#mySelect').html(option);
SELECT
student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student
ON student.studentId = grade.fk_studentId
INNER JOIN exam
ON exam.examId = grade.fk_examId
GROUP BY grade.gradeId
ORDER BY exam.date
com.fasterxml.jackson.databind.type.TypeFactory._hashMapSuperInterfaceChain(HierarchicType)
com.fasterxml.jackson.databind.type.TypeFactory._findSuperInterfaceChain(Type, Class)
com.fasterxml.jackson.databind.type.TypeFactory._findSuperTypeChain(Class, Class)
com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(Class, Class, TypeBindings)
com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(JavaType, Class)
com.fasterxml.jackson.databind.type.TypeFactory._fromParamType(ParameterizedType, TypeBindings)
com.fasterxml.jackson.databind.type.TypeFactory._constructType(Type, TypeBindings)
com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeReference)
com.fasterxml.jackson.databind.ObjectMapper.convertValue(Object, TypeReference)
The method _hashMapSuperInterfaceChain in class com.fasterxml.jackson.databind.type.TypeFactory is synchronized. Am seeing contention on the same at high loads.
May be another reason to avoid a static ObjectMapper
Both certificates should exist prior to the connection. They're usually created by Certification Authorities (not necessarily the same). (There are alternative cases where verification can be done differently, but some verification will need to be made.)
The server certificate should be created by a CA that the client trusts (and following the naming conventions defined in RFC 6125).
The client certificate should be created by a CA that the server trusts.
It's up to each party to choose what it trusts.
There are online CA tools that will allow you to apply for a certificate within your browser and get it installed there once the CA has issued it. They need not be on the server that requests client-certificate authentication.
The certificate distribution and trust management is the role of the Public Key Infrastructure (PKI), implemented via the CAs. The SSL/TLS client and servers and then merely users of that PKI.
When the client connects to a server that requests client-certificate authentication, the server sends a list of CAs it's willing to accept as part of the client-certificate request. The client is then able to send its client certificate, if it wishes to and a suitable one is available.
The main advantages of client-certificate authentication are:
You may be interested in Advantages of client certificates for client authentication? (on Security.SE).
The short answer is "no, it is not possible to do that in a principled way that works even remotely well". It is an unsolved problem in natural language processing research and also happens to be the subject of my doctoral work. I'll very briefly summarize where we are and point you to a few publications:
Meaning of words
The most important assumption here is that it is possible to obtain a vector that represents each word in the sentence in quesion. This vector is usually chosen to capture the contexts the word can appear in. For example, if we only consider the three contexts "eat", "red" and "fluffy", the word "cat" might be represented as [98, 1, 87], because if you were to read a very very long piece of text (a few billion words is not uncommon by today's standard), the word "cat" would appear very often in the context of "fluffy" and "eat", but not that often in the context of "red". In the same way, "dog" might be represented as [87,2,34] and "umbrella" might be [1,13,0]. Imagening these vectors as points in 3D space, "cat" is clearly closer to "dog" than it is to "umbrella", therefore "cat" also means something more similar to "dog" than to an "umbrella".
This line of work has been investigated since the early 90s (e.g. this work by Greffenstette) and has yielded some surprisingly good results. For example, here is a few random entries in a thesaurus I built recently by having my computer read wikipedia:
theory -> analysis, concept, approach, idea, method
voice -> vocal, tone, sound, melody, singing
james -> william, john, thomas, robert, george, charles
These lists of similar words were obtained entirely without human intervention- you feed text in and come back a few hours later.
The problem with phrases
You might ask why we are not doing the same thing for longer phrases, such as "ginger foxes love fruit". It's because we do not have enough text. In order for us to reliably establish what X is similar to, we need to see many examples of X being used in context. When X is a single word like "voice", this is not too hard. However, as X gets longer, the chances of finding natural occurrences of X get exponentially slower. For comparison, Google has about 1B pages containing the word "fox" and not a single page containing "ginger foxes love fruit", despite the fact that it is a perfectly valid English sentence and we all understand what it means.
Composition
To tackle the problem of data sparsity, we want to perform composition, i.e. to take vectors for words, which are easy to obtain from real text, and to put the together in a way that captures their meaning. The bad news is nobody has been able to do that well so far.
The simplest and most obvious way is to add or multiply the individual word vectors together. This leads to undesirable side effect that "cats chase dogs" and "dogs chase cats" would mean the same to your system. Also, if you are multiplying, you have to be extra careful or every sentences will end up represented by [0,0,0,...,0], which defeats the point.
Further reading
I will not discuss the more sophisticated methods for composition that have been proposed so far. I suggest you read Katrin Erk's "Vector space models of word meaning and phrase meaning: a survey". This is a very good high-level survey to get you started. Unfortunately, is not freely available on the publisher's website, email the author directly to get a copy. In that paper you will find references to many more concrete methods. The more comprehensible ones are by Mitchel and Lapata (2008) and Baroni and Zamparelli (2010).
Edit after comment by @vpekar: The bottom line of this answer is to stress the fact that while naive methods do exist (e.g. addition, multiplication, surface similarity, etc), these are fundamentally flawed and in general one should not expect great performance from them.
As of HttpComponents 4.2+
there is a new class URIBuilder, which provides convenient way for generating URIs.
You can use either create URI directly from String URL:
List<NameValuePair> listOfParameters = ...;
URI uri = new URIBuilder("http://example.com:8080/path/to/resource?mandatoryParam=someValue")
.addParameter("firstParam", firstVal)
.addParameter("secondParam", secondVal)
.addParameters(listOfParameters)
.build();
Otherwise, you can specify all parameters explicitly:
URI uri = new URIBuilder()
.setScheme("http")
.setHost("example.com")
.setPort(8080)
.setPath("/path/to/resource")
.addParameter("mandatoryParam", "someValue")
.addParameter("firstParam", firstVal)
.addParameter("secondParam", secondVal)
.addParameters(listOfParameters)
.build();
Once you have created URI
object, then you just simply need to create HttpGet
object and perform it:
//create GET request
HttpGet httpGet = new HttpGet(uri);
//perform request
httpClient.execute(httpGet ...//additional parameters, handle response etc.
Run server.js from a different command line and client.js from a different command line
as long as it's a variable and not a second class, this here works for me:
def print_var_name(variable):
for name in globals():
if eval(name) == variable:
print name
foo = 123
print_var_name(foo)
>>>foo
this happens for class members:
class xyz:
def __init__(self):
pass
member = xyz()
print_var_name(member)
>>>member
ans this for classes (as example):
abc = xyz
print_var_name(abc)
>>>abc
>>>xyz
So for classes it gives you the name AND the properteries
split with the + sign like this way
String a = tv.getText().toString();
String aa[];
if(a.contains("+"))
aa = a.split("+");
now convert the array
Integer.parseInt(aa[0]); // and so on
I Created this module to help make this process piece of cake
You can do things like:
$routeProvider
.state('secret',
{
...
permissions: {
only: ['admin', 'god']
}
});
Or also
$routeProvider
.state('userpanel',
{
...
permissions: {
except: ['not-logged-in']
}
});
It's brand new but worth checking out!
This line
mnuActionLanguage.ComboBox.DisplayMember = "Lang.Language";
is wrong. Change it to
mnuActionLanguage.ComboBox.DisplayMember = "Language";
and it will work (even without DataBind()).
Anyway, you probably need something like this:
var val = $('#c_b :checkbox').is(':checked').val();
$('#t').val( val );
This will get the value of the first checked checkbox on the page and insert that in the textarea with id='textarea'
.
Note that in your example code you should put the checkboxes in a form.
Windows 7 64-bit, with both Python3.4 and Python2.7 installed at some point :)
I'm using Py.exe to route to Py2 or Py3 depending on the script's needs - but I previously improperly uninstalled Python27 before.
Py27 was removed manually from C:\python\Python27 (the folder Python27 was deleted by me previously)
Upon re-installing Python27, it gave the above error you specify.
It would always back out while trying to 'remove shortcuts' during the installation process.
I placed a copy of Python27 back in that original folder, at C:\Python\Python27, and re-ran the same failing Python27 installer. It was happy locating those items and removing them, and proceeded with the install.
This is not the answer that addresses registry key issues (others mention that) but it is somewhat of a workaround if you know of previous installations that were improperly removed.
You could have some insight to this by opening "regedit" and searching for "Python27" - a registry key appeared in my command-shell Cache pointing at c:\python\python27\ (which had been removed and was not present when searching in the registry upon finding it).
That may help point to previously improperly removed installations.
Good luck!
In JBoss EAP 6.4, right click on the server and open launch configuration under VM argument you will find
{-Dprogram.name=JBossTools: jboss-eap" -server -Xms1024m -Xmx1024m -XX:MaxPermSize=256m}
update it to
{-Dprogram.name=JBossTools: JBoss 6.4" -server -Xms512m -Xmx512m}
this will solve your problem.
Here is an example if multiple tables don't have common Id, you can create yourself, I use 1 as commonId
to create common id so that I can inner join them:
Insert Into #TempResult
select CountA, CountB, CountC from
(
select Count(A_Id) as CountA, 1 as commonId from tableA
where ....
and ...
and ...
) as tempA
inner join
(
select Count(B_Id) as CountB, 1 as commonId from tableB
where ...
and ...
and ...
) as tempB
on tempA.commonId = tempB.commonId
inner join
(
select Count(C_ID) as CountC, 1 as commonId from tableC
where ...
and ...
) as tempC
on tmepB.commonId = tempC.commonId
--view insert result
select * from #TempResult
Make sure your code is in DOM Ready as pointed by rocket-hazmat
$('#RootNode').click(function(){
//do something
});
document.getElementById("RootNode").onclick = function(){//do something}
$(document).on("click", "#RootNode", function(){
//do something
});
Wrap Code in Dom Ready
$(document).ready(function(){
$('#RootNode').click(function(){
//do something
});
});
Solution(s) for this, found in the official wampserver.com forums:
This problem is caused by Windows (7) in combination with any software that also uses port 80 (like Skype or IIS (which is installed on most developer machines)). A video solution can be found here (34.500+ views, damn, this seems to be a big thing ! EDIT: The video now has ~60.000 views ;) )
To make it short: open command line tool, type "netstat -aon" and look for any lines that end of ":80"
. Note thatPID
on the right side. This is the process id of the software which currently usesport 80
. Press AltGr + Ctrl + Del to get into the Taskmanager. Switch to the tab where you can see all services currently running, ordered by PID. Search for that PID
you just notices and stop that thing (right click). To prevent this in future, you should config the software's port settings (skype can do that).
left click the wamp icon in the taskbar, go to apache > httpd.conf and edit this file: change "listen to port .... 80"
to 8080
. Restart. Done !
Port 80 blocked by "Microsoft Web Deployment Service", simply deinstall this, more info here
By the way, it's not Microsoft's fault, it's a stupid usage of ports by most WAMP stacks.
IMPORTANT: you have to use localhost
or 127.0.0.1
now with port 8080
, this means 127.0.0.1:8080
or localhost:8080
.
As others have suggested, you could use nested for-loops or redeclare your multidimensional array as a jagged one.
However, I think it's worth pointing out that multidimensional arrays are enumerable, just not in the way that you want. For example:
string[,] table = {
{ "aa", "aaa" },
{ "bb", "bbb" }
};
foreach (string s in table)
{
Console.WriteLine(s);
}
/* Output is:
aa
aaa
bb
bbb
*/
I tried
kill -9 $(ps -A -ostat,ppid | grep -e '[zZ]'| awk '{ print $2 }')
and it works for me.
After some trial and tribulation, I was able to find all .msi files in a given directory and install them.
foreach($_msiFiles in
($_msiFiles = Get-ChildItem $_Source -Recurse | Where{$_.Extension -eq ".msi"} |
Where-Object {!($_.psiscontainter)} | Select-Object -ExpandProperty FullName))
{
msiexec /i $_msiFiles /passive
}
I just add an answear because I spent hours trying to solve the same symptoms (but different issue):
A possible cause is a x86 dll in a 64 bits app pool, the solution is to enable 32 bits apps in the application pool settings.
It seems that, according to the HTML5 spec, the value property of the textarea element should return '\r\n' for a newline:
The element's value is defined to be the element's raw value with the following transformation applied:
Replace every occurrence of a "CR" (U+000D) character not followed by a "LF" (U+000A) character, and every occurrence of a "LF" (U+000A) character not preceded by a "CR" (U+000D) character, by a two-character string consisting of a U+000D CARRIAGE RETURN "CRLF" (U+000A) character pair.
Following the link to 'value' makes it clear that it refers to the value property accessed in javascript:
Form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.
However, in all five major browsers (using Windows, 11/27/2015), if '\r\n' is written to a textarea, the '\r' is stripped. (To test: var e=document.createElement('textarea'); e.value='\r\n'; alert(e.value=='\n');) This is true of IE since v9. Before that, IE was returning '\r\n' and converting both '\r' and '\n' to '\r\n' (which is the HTML5 spec). So... I'm confused.
To be safe, it's usually enough to use '\r?\n' in regular expressions instead of just '\n', but if the newline sequence must be known, a test like the above can be performed in the app.
You don't need to override onBackPressed()
- it's already defined as the action that your activity will do by default when the user pressed the back button. So just call onBackPressed()
whenever you want to "programatically press" the back button.
That would only result to finish()
being called, though ;)
I think you're confused with what the back button does. By default, it's just a call to finish()
, so it just exits the current activity. If you have something behind that activity, that screen will show.
What you can do is when launching your activity from the Login, add a CLEAR_TOP flag so the login activity won't be there when you exit yours.
import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
print 'matched'