you can do it using eloquent easily like this
$sum = Model::sum('sum_field');
its will return a sum of fields, if apply condition on it that is also simple
$sum = Model::where('status', 'paid')->sum('sum_field');
Cascade will work when you delete something on table Courses
. Any record on table BookCourses
that has reference to table Courses
will be deleted automatically.
But when you try to delete on table BookCourses
only the table itself is affected and not on the Courses
follow-up question: why do you have CourseID
on table Category?
Maybe you should restructure your schema into this,
CREATE TABLE Categories
(
Code CHAR(4) NOT NULL PRIMARY KEY,
CategoryName VARCHAR(63) NOT NULL UNIQUE
);
CREATE TABLE Courses
(
CourseID INT NOT NULL PRIMARY KEY,
BookID INT NOT NULL,
CatCode CHAR(4) NOT NULL,
CourseNum CHAR(3) NOT NULL,
CourseSec CHAR(1) NOT NULL,
);
ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;
As this is the closest I found to the issue I had, it's the first result that comes up and I didn't find an appropriate answer, I'll post the solution here for any future poor souls:
any()
doesn't work where mocked class method uses a primitive parameter.
public Boolean getResult(String identifier, boolean switch)
The above will produce the same exact issue as OP.
Solution, just wrap it:
public Boolean getResult(String identifier, Boolean switch)
The latter solves the NPE.
I couldn't find an off-the-shelf module that added this function, so I wrote one:
In Access, go to the Database Tools ribbon, in the Macro area click into Visual Basic. In the top left Project area, right click the name of your file and select Insert -> Module. In the module paste this:
Public Function Substring_Index(strWord As String, strDelim As String, intCount As Integer) As String
Substring_Index = delims
start = 0
test = ""
For i = 1 To intCount
oldstart = start + 1
start = InStr(oldstart, strWord, strDelim)
Substring_Index = Mid(strWord, oldstart, start - oldstart)
Next i
End Function
Save the module as module1 (the default). You can now use statements like:
SELECT Substring_Index([fieldname],",",2) FROM table
An empty catch block is essentially saying "I don't want to know what errors are thrown, I'm just going to ignore them."
It's similar to VB6's On Error Resume Next
, except that anything in the try block after the exception is thrown will be skipped.
Which doesn't help when something then breaks.
You will need to know if the REST API you are calling supports GET
or POST
, or both methods. The code below is something that works for me, I'm calling my own web service API, so I already know what the API takes and what it will return. It supports both GET
and POST
methods, so the less sensitive info goes into the URL (GET)
, and the info like username and password is submitted as POST
variables. Also, everything goes over the HTTPS
connection.
Inside the API code, I encode an array I want to return into json format, then simply use PHP command echo $my_json_variable
to make that json string availabe to the client.
So as you can see, my API returns json data, but you need to know (or look at the returned data to find out) what format the response from the API is in.
This is how I connect to the API from the client side:
$processed = FALSE;
$ERROR_MESSAGE = '';
// ************* Call API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myapi.com/api.php?format=json&action=subscribe&email=" . $email_to_subscribe);
curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=myname&password=mypass"); // post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close ($ch);
// returned json string will look like this: {"code":1,"data":"OK"}
// "code" may contain an error code and "data" may contain error string instead of "OK"
$obj = json_decode($json);
if ($obj->{'code'} == '1')
{
$processed = TRUE;
}else{
$ERROR_MESSAGE = $obj->{'data'};
}
...
if (!$processed && $ERROR_MESSAGE != '') {
echo $ERROR_MESSAGE;
}
BTW, I also tried to use file_get_contents()
method as some of the users here suggested, but that din't work well for me. I found out the curl
method to be faster and more reliable.
Alternative solution to the updated question using Java 8:
Bar[] result = foos.stream()
.map(x -> new Bar(x))
.toArray(size -> new Bar[size]);
The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.
Color.parseColor("#rrggbb")
instead of #rrggbb
you should be using hex values 0 to F for rr, gg and bb:
e.g. Color.parseColor("#000000")
or Color.parseColor("#FFFFFF")
From documentation:
public static int parseColor (String colorString):
Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuschia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'
So I believe that if you are using #rrggbb
you are getting IllegalArgumentException in your logcat
Alternative:
Color mColor = new Color();
mColor.red(redvalue);
mColor.green(greenvalue);
mColor.blue(bluevalue);
li.setBackgroundColor(mColor);
The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:
execl("/bin/ls", "ls", "-la", NULL);
The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:
execlp("ls", "ls", "-la", NULL);
\d
means 'digit'. +
means, '1 or more times'. So \d+
means one or more digit. It will match 12
and 1
.
Option 1:
Use pandas
dataframe plot (built on top of matplotlib
):
import pandas as pd
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
pd.DataFrame(data).plot(kind='density') # or pd.Series()
Option 2:
Use distplot
of seaborn
:
import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.distplot(data, hist=False)
A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib
to include all the .jar files in that directory, it won't. You have to name them explicitly.
Use Convert.TryFromBase64String from C# 7.2
public static bool IsBase64String(string base64)
{
Span<byte> buffer = new Span<byte>(new byte[base64.Length]);
return Convert.TryFromBase64String(base64, buffer , out int bytesParsed);
}
There is another difference to keep in mind between the two. With CSS, the :hover
state is always deactivated when the mouse moves off an element. However, with JavaScript, the onmouseout
event is not fired when the mouse moves off the element onto browser chrome rather than onto the rest of the page.
This happens more often than you might think, especially when you're making a navbar at the top of your page with custom hover states.
Personally, I generally dislike return parameters for a number of reasons:
I also have some reservations about the pair/tuple technique. Mainly, there is often no natural order to the return values. How is the reader of the code to know whether result.first is the quotient or the remainder? And the implementer could change the order, which would break existing code. This is especially insidious if the values are the same type so that no compiler error or warning would be generated. Actually, these arguments apply to return parameters as well.
Here's another code example, this one a bit less trivial:
pair<double,double> calculateResultingVelocity(double windSpeed, double windAzimuth,
double planeAirspeed, double planeCourse);
pair<double,double> result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.first << endl;
cout << result.second << endl;
Does this print groundspeed and course, or course and groundspeed? It's not obvious.
Compare to this:
struct Velocity {
double speed;
double azimuth;
};
Velocity calculateResultingVelocity(double windSpeed, double windAzimuth,
double planeAirspeed, double planeCourse);
Velocity result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.speed << endl;
cout << result.azimuth << endl;
I think this is clearer.
So I think my first choice in general is the struct technique. The pair/tuple idea is likely a great solution in certain cases. I'd like to avoid the return parameters when possible.
I have the problem anyway with -lm added
gcc -Wall -lm mtest.c -o mtest.o
mtest.c: In function 'f1':
mtest.c:6:12: warning: unused variable 'res' [-Wunused-variable]
/tmp/cc925Nmf.o: In function `f1':
mtest.c:(.text+0x19): undefined reference to `sin'
collect2: ld returned 1 exit status
I discovered recently that it does not work if you first specify -lm. The order matters:
gcc mtest.c -o mtest.o -lm
Just link without problems
So you must specify the libraries after.
I think I will go for the duck typing approach - "if it walks like a duck, it quacks like a duck, its a duck". This way you will need not worry about if the string is a unicode or ascii.
Here is what I will do:
In [53]: s='somestring'
In [54]: u=u'someunicodestring'
In [55]: d={}
In [56]: for each in s,u,d:
if hasattr(each, 'keys'):
print list(set(each.values()))
elif hasattr(each, 'lower'):
print [each]
else:
print "error"
....:
....:
['somestring']
[u'someunicodestring']
[]
The experts here are welcome to comment on this type of usage of ducktyping, I have been using it but got introduced to the exact concept behind it lately and am very excited about it. So I would like to know if thats an overkill to do.
In Windows, you will have to set the path to the location where you installed Anaconda3 to.
For me, I installed anaconda3 into C:\Anaconda3
. Therefore you need to add C:\Anaconda3
as well as C:\Anaconda3\Scripts\
to your path variable, e.g. set PATH=%PATH%;C:\Anaconda3;C:\Anaconda3\Scripts\
.
You can do this via powershell (see above, https://msdn.microsoft.com/en-us/library/windows/desktop/bb776899(v=vs.85).aspx ), or hit the windows
key ? enter environment
? choose from settings
? edit environment variables for your account
? select Path
variable ? Edit
? New
.
To test it, open a new dos shell, and you should be able to use conda commands now. E.g., try conda --version
.
DAO is native to Access and by far the best for general use. ADO has its place, but it is unlikely that this is it.
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL as String
Set db=CurrentDB
strSQL = "select * from table where some condition"
Set rs = db.OpenRecordset(strSQL)
Do While Not rs.EOF
rs.Edit
rs!SomeField = "Abc"
rs!OtherField = 2
rs!ADate = Date()
rs.Update
rs.MoveNext
Loop
sys.argv
is the list of command line arguments passed to a Python script, where sys.argv[0]
is the script name itself.
It is erroring out because you are not passing any commandline argument, and thus sys.argv
has length 1 and so sys.argv[1]
is out of bounds.
To "fix", just make sure to pass a commandline argument when you run the script, e.g.
python ConcatenateFiles.py /the/path/to/the/directory
However, you likely wanted to use some default directory so it will still work when you don't pass in a directory:
cur_dir = sys.argv[1] if len(sys.argv) > 1 else '.'
with open(cur_dir + '/Concatenated.csv', 'w+') as outfile:
try:
with open(cur_dir + '/MatrixHeader.csv') as headerfile:
for line in headerfile:
outfile.write(line + '\n')
except:
print 'No Header File'
The modern approach uses the java.time classes.
YearMonth.from(
ZonedDateTime.parse(
"Mon Mar 14 16:02:37 GMT 2011" ,
DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" )
)
).toString()
2011-03
The modern way is with java.time classes. The old date-time classes such as Calendar
have proven to be poorly-designed, confusing, and troublesome.
Define a custom formatter to match your string input.
String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
Parse as a ZonedDateTime
.
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
You are interested in the year and month. The java.time classes include YearMonth
class for that purpose.
YearMonth ym = YearMonth.from( zdt );
You can interrogate for the year and month numbers if needed.
int year = ym.getYear();
int month = ym.getMonthValue();
But the toString
method generates a string in standard ISO 8601 format.
String output = ym.toString();
Put this all together.
String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
YearMonth ym = YearMonth.from( zdt );
int year = ym.getYear();
int month = ym.getMonthValue();
Dump to console.
System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ym: " + ym );
input: Mon Mar 14 16:02:37 GMT 2011
zdt: 2011-03-14T16:02:37Z[GMT]
ym: 2011-03
See this code running in IdeOne.com.
If you must have a Calendar
object, you can convert to a GregorianCalendar
using new methods added to the old classes.
GregorianCalendar gc = GregorianCalendar.from( zdt );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
I already answered similar question on here Here is the Link
No both are different.
@Service annotation have use for other purpose and @Controller use for other. Actually Spring @Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework, but it doesn't ,mean that all functionalities are same. @Service: It indicates annotated class is a Service component in the business layer.
@Controller: Annotated class indicates that it is a controller components, and mainly used at presentation layer.
There are two problems in your code:
visibility
and not visiblity
..style
property.It's easy to fix. Simple replace this:
document.getElementById("remember").visiblity
with this:
document.getElementById("remember").style.visibility
Update The currently suggested way to start a Task is simply using Task.Run()
Task.Run(() => foo());
Note that this method is described as the best way to start a task see here
Previous answer
I like the Task Factory from System.Threading.Tasks. You can do something like this:
Task.Factory.StartNew(() =>
{
// Whatever code you want in your thread
});
Note that the task factory gives you additional convenience options like ContinueWith:
Task.Factory.StartNew(() => {}).ContinueWith((result) =>
{
// Whatever code should be executed after the newly started thread.
});
Also note that a task is a slightly different concept than threads. They nicely fit with the async/await keywords, see here.
Try this:
$(this).hide("slide", { direction: "left" }, 1000);
$(this).show("slide", { direction: "left" }, 1000);
Check this How to view contents of NSDictionary variable in Xcode debugger?
I also use
po variableName
print variableName
in Console.
In your case it is possible to execute
print [myData objectAtIndex:indexPath.row]
or
po [myData objectAtIndex:indexPath.row]
You almost had it. If you want to pass the output of a command as parameters to another one, you'll need to use xargs. Adding -print0
makes sure the script can handle paths with whitespace:
find . -type d -name .svn -print0|xargs -0 rm -rf
When you want to increment or decrement, you typically want to do that on an integer. Like so:
b++
But in Python, integers are immutable. That is you can't change them. This is because the integer objects can be used under several names. Try this:
>>> b = 5
>>> a = 5
>>> id(a)
162334512
>>> id(b)
162334512
>>> a is b
True
a and b above are actually the same object. If you incremented a, you would also increment b. That's not what you want. So you have to reassign. Like this:
b = b + 1
Or simpler:
b += 1
Which will reassign b
to b+1
. That is not an increment operator, because it does not increment b
, it reassigns it.
In short: Python behaves differently here, because it is not C, and is not a low level wrapper around machine code, but a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop, for example.
This is what I did:
\begin{frame}{series of images}
\begin{center}
\begin{overprint}
\only<2>{\includegraphics[scale=0.40]{image1.pdf}}
\hspace{-0.17em}\only<3>{\includegraphics[scale=0.40]{image2.pdf}}
\hspace{-0.34em}\only<4>{\includegraphics[scale=0.40]{image3.pdf}}
\hspace{-0.17em}\only<5>{\includegraphics[scale=0.40]{image4.pdf}}
\only<2-5>{\mbox{\structure{Figure:} something}}
\end{overprint}
\end{center}
\end{frame}
Compare Names containing apostrophe in DB through Java code
String sql="select lastname from employee where FirstName like '%"+firstName.trim().toLowerCase().replaceAll("'", "''")+"%'"
statement = conn.createStatement();
rs=statement.executeQuery(Sql);
iterate the results.
Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// your function here
}
Swift 3
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
// your function here
}
Swift 2
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
// your function here
})
The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.
This is more or less what it should look like (no libcurl available here to test)
#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need
#include <curl/types.h>
#include <curl/easy.h>
*/
#include <string>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int main(void) {
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "http://localhost/aaa.txt";
char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
Updated: as suggested by @rsethc types.h
and easy.h
aren't present in current cURL versions anymore.
If you're not wanting to save changes set savechanges to false
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used
ActiveWorkbook.Close False
The logic is not flawed. The statement
if x is y then x==y is also True
should never be read to mean
if x==y then x is y
It is a logical error on the part of the reader to assume that the converse of a logic statement is true. See http://en.wikipedia.org/wiki/Converse_(logic)
Why make it so complicated? This worked.
SELECT m_id,v_id,MAX(TIMESTAMP) AS TIME
FROM table_name
GROUP BY m_id
code below allows user to input items until they press enter key to stop:
In [1]: items=[]
...: i=0
...: while 1:
...: i+=1
...: item=input('Enter item %d: '%i)
...: if item=='':
...: break
...: items.append(item)
...: print(items)
...:
Enter item 1: apple
Enter item 2: pear
Enter item 3: #press enter here
['apple', 'pear']
In [2]:
You can always add the "!" into your float-options. This way, latex tries really hard to place the figure where you want it (I mostly use [h!tb]), stretching the normal rules of type-setting.
I have found another solution:
Use the float-package. This way you can place the figures where you want them to be.
Try this one. It centers vertically and horizontally.
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: children,
),
)
I believe you are looking for DateTime.Today
. The documentation states:
An object that is set to today's date, with the time component set to 00:00:00.
http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx
Your code would be
DateTime _Begin = DateTime.Today;
The helpers are there mainly to help you display labels, form inputs, etc for the strongly typed properties of your model. By using the helpers and Visual Studio Intellisense, you can greatly reduce the number of typos that you could make when generating a web page.
With that said, you can continue to create your elements manually for both properties of your view model or items that you want to display that are not part of your view model.
Here is another way to solve this problem under windows, if you use Wampserver. Indeed at the level of wampserver, there are two php.ini files, that of PHP, which one can find in the location C: \ wamp64 \ bin \ php \ phpx.xx \ php.ini and that of Apache , which can be found at location C: \ wamp64 \ bin \ apache \ apachex.xx \ bin \ php.ini. Both of these files have the memory_limit parameter. So to be sure to solve this problem, it is better to set the memory_limit = -1 parameter in both files at once.
The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.
dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is
P(dBm) = 10 · log10( P(W) / 1mW )
where
P(dBm) = Power expressed in dBm P(W) = the absolute power measured in Watts mW = milliWatts log10 = log to base 10
From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.
There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.
Your actual question was "does the - sign count?"
The answer is yes, it does.
-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.
Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.
How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.
To answer your titular question, you use [0]
to access the first element, but as it stands mandrill_events
contains a string not an array, so mandrill_events[0]
will just get you the first character, '['.
So either correct your source to:
var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };
and then req.mandrill_events[0]
, or if you're stuck with it being a string, parse the JSON the string contains:
var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var mandrill_events = JSON.parse(req.mandrill_events);
var result = mandrill_events[0];
Looking forward to Web Animations in 2020.
async function moveToPosition(el, durationInMs) {
return new Promise((resolve) => {
const animation = el.animate([{
opacity: '0'
},
{
transform: `translateY(${el.getBoundingClientRect().top}px)`
},
], {
duration: durationInMs,
easing: 'ease-in',
iterations: 1,
direction: 'normal',
fill: 'forwards',
delay: 0,
endDelay: 0
});
animation.onfinish = () => resolve();
});
}
async function fadeIn(el, durationInMs) {
return new Promise((resolve) => {
const animation = el.animate([{
opacity: '0'
},
{
opacity: '0.5',
offset: 0.5
},
{
opacity: '1',
offset: 1
}
], {
duration: durationInMs,
easing: 'linear',
iterations: 1,
direction: 'normal',
fill: 'forwards',
delay: 0,
endDelay: 0
});
animation.onfinish = () => resolve();
});
}
async function fadeInSections() {
for (const section of document.getElementsByTagName('section')) {
await fadeIn(section, 200);
}
}
window.addEventListener('load', async() => {
await moveToPosition(document.getElementById('headerContent'), 500);
await fadeInSections();
await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
height: 100vh;
}
header {
height: 20%;
}
.text-center {
text-align: center;
}
.leading-none {
line-height: 1;
}
.leading-3 {
line-height: .75rem;
}
.leading-2 {
line-height: .25rem;
}
.bg-black {
background-color: rgba(0, 0, 0, 1);
}
.bg-gray-50 {
background-color: rgba(249, 250, 251, 1);
}
.pt-12 {
padding-top: 3rem;
}
.pt-2 {
padding-top: 0.5rem;
}
.text-lightGray {
color: lightGray;
}
.container {
display: flex;
/* or inline-flex */
justify-content: space-between;
}
.container section {
padding: 0.5rem;
}
.opacity-0 {
opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="Web site created using create-snowpack-app" />
<link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>
<body>
<header class="bg-gray-50">
<div id="headerContent">
<h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
<p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
</div>
</header>
<div class="container">
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 1</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 2</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 3</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
</div>
<footer class="opacity-0">
<h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
<p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
</footer>
</body>
</html>
_x000D_
My question is: Why is not calling
return
faster
It’s faster because return
is a (primitive) function in R, which means that using it in code incurs the cost of a function call. Compare this to most other programming languages, where return
is a keyword, but not a function call: it doesn’t translate to any runtime code execution.
That said, calling a primitive function in this way is pretty fast in R, and calling return
incurs a minuscule overhead. This isn’t the argument for omitting return
.
or better, and thus preferable?
Because there’s no reason to use it.
Because it’s redundant, and it doesn’t add useful redundancy.
To be clear: redundancy can sometimes be useful. But most redundancy isn’t of this kind. Instead, it’s of the kind that adds visual clutter without adding information: it’s the programming equivalent of a filler word or chartjunk).
Consider the following example of an explanatory comment, which is universally recognised as bad redundancy because the comment merely paraphrases what the code already expresses:
# Add one to the result
result = x + 1
Using return
in R falls in the same category, because R is a functional programming language, and in R every function call has a value. This is a fundamental property of R. And once you see R code from the perspective that every expression (including every function call) has a value, the question then becomes: “why should I use return
?” There needs to be a positive reason, since the default is not to use it.
One such positive reason is to signal early exit from a function, say in a guard clause:
f = function (a, b) {
if (! precondition(a)) return() # same as `return(NULL)`!
calculation(b)
}
This is a valid, non-redundant use of return
. However, such guard clauses are rare in R compared to other languages, and since every expression has a value, a regular if
does not require return
:
sign = function (num) {
if (num > 0) {
1
} else if (num < 0) {
-1
} else {
0
}
}
We can even rewrite f
like this:
f = function (a, b) {
if (precondition(a)) calculation(b)
}
… where if (cond) expr
is the same as if (cond) expr else NULL
.
Finally, I’d like to forestall three common objections:
Some people argue that using return
adds clarity, because it signals “this function returns a value”. But as explained above, every function returns something in R. Thinking of return
as a marker of returning a value isn’t just redundant, it’s actively misleading.
Relatedly, the Zen of Python has a marvellous guideline that should always be followed:
Explicit is better than implicit.
How does dropping redundant return
not violate this? Because the return value of a function in a functional language is always explicit: it’s its last expression. This is again the same argument about explicitness vs redundancy.
In fact, if you want explicitness, use it to highlight the exception to the rule: mark functions that don’t return a meaningful value, which are only called for their side-effects (such as cat
). Except R has a better marker than return
for this case: invisible
. For instance, I would write
save_results = function (results, file) {
# … code that writes the results to a file …
invisible()
}
But what about long functions? Won’t it be easy to lose track of what is being returned?
Two answers: first, not really. The rule is clear: the last expression of a function is its value. There’s nothing to keep track of.
But more importantly, the problem in long functions isn’t the lack of explicit return
markers. It’s the length of the function. Long functions almost (?) always violate the single responsibility principle and even when they don’t they will benefit from being broken apart for readability.
The difference between include()
and require()
arises when the file being included cannot be found: include()
will release a warning (E_WARNING) and the script will continue, whereas require()
will release a fatal error (E_COMPILE_ERROR) and terminate the script. If the file being included is critical to the rest of the script running correctly then you need to use require()
.
For more details : Difference between Include and Require in PHP
I think the easiest way is to add another div, in the same place as the iframe, then
make its z-index
bigger than the iframe container, so you can easly just style your own div. If you need to click on it, just use pointer-events:none
on your own div, so the iframe would be working in case you need to click on it ;)
I hope It will help someone ;)
I tried this commands in my PC.It is working fine....
To open notepad in minimized mode:
start /min "" "C:\Windows\notepad.exe"
To open MS word in minimized mode:
start /min "" "C:\Program Files\Microsoft Office\Office14\WINWORD.EXE"
Very popular topic and google finds this for "jquery dialog close which event was clicked" query. My solution handles YES,NO,ESC_KEY,X events properly. I want my callback function be called no matter how dialog was disposed.
function dialog_YES_NO(sTitle, txt, fn) {
$("#dialog-main").dialog({
title: sTitle,
resizable: true,
//height:140,
modal: true,
open: function() { $(this).data("retval", false); $(this).text(txt); },
close: function(evt) {
var arg1 = $(this).data("retval")==true;
setTimeout(function() { fn(arg1); }, 30);
},
buttons: {
"Yes": function() { $(this).data("retval", true); $(this).dialog("close"); },
"No": function() { $(this).data("retval", false); $(this).dialog("close"); }
}
});
}
- - - -
dialog_YES_NO("Confirm Delete", "Delete xyz item?", function(status) {
alert("Dialog retval is " + status);
});
It's easy to redirect browser to a new url or perform something else on function retval.
result = M.A1
https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.matrix.A1.html
matrix.A1
1-d base array
The order of execution is:
A
's constructorB
's constructorThe assignment occurs in B
's constructor after A
's constructor—_super
—has been called:
function B() {
_super.apply(this, arguments); // MyvirtualMethod called in here
this.testString = "Test String"; // testString assigned here
}
So the following happens:
var b = new B(); // undefined
b.MyvirtualMethod(); // "Test String"
You will need to change your code to deal with this. For example, by calling this.MyvirtualMethod()
in B
's constructor, by creating a factory method to create the object and then execute the function, or by passing the string into A
's constructor and working that out somehow... there's lots of possibilities.
Try this piece of code, it should work too
<%
//response.setContentType("Content-Type", "application/json"); // this will fail compilation
response.setContentType("application/json"); //fixed
%>
I did this in the web.config file. I added to Sobhan's answer, thanks btw.
<connectionStrings>
<add name="listdb" connectionString="Data Source=|DataDirectory|\db\listdb.sdf"/>
</connectionStrings>
Where "db" becomes my database directory instead of "App_Data" directory.
And opened normally with:
var db = Database.Open("listdb");
You could look into psh here: http://gnp.github.io/psh/
It's a full on shell (you can use it in replacement of bash for example), but uses perl syntax.. so you can create methods on the fly etc.
This will get you to an answer for your simple case, but can you expand on how you'll know which columns will need to be compared (B and C in this case) and what the initial range (A1:D5
in this case) will be? Then I can try to provide a more complete answer.
Sub setCondFormat()
Range("B3").Select
With Range("B3:H63")
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=IF($D3="""",FALSE,IF($F3>=$E3,TRUE,FALSE))"
With .FormatConditions(.FormatConditions.Count)
.SetFirstPriority
With .Interior
.PatternColorIndex = xlAutomatic
.Color = 5287936
.TintAndShade = 0
End With
End With
End With
End Sub
Note: this is tested in Excel 2010.
Edit: Updated code based on comments.
In our case it was Windows-integrated authentication specified in the app's web.config
BUT the windows-auth module was not installed on the IIS machine at all.
Just adding another possible reason.
This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!
On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:
<?php
session_start();
$timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.
On the same page, in the <head>
section, first of all you need to include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the <head>
section, paste this jQuery:
<script type="text/javascript">
$(document).ready(function() {
if("<?php echo $timezone; ?>".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
$.ajax({
type: "GET",
url: "http://example.com/timezone.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
You may or may not have noticed, but you need to change the url to your actual domain.
One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)
<?php
session_start();
$_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.
You can read more about this on my blog
Here's an example of using text-overflow:
.text {_x000D_
display: block;_x000D_
width: 100px;_x000D_
overflow: hidden;_x000D_
white-space: nowrap;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<span class="text">Hello world this is a long sentence</span>
_x000D_
For a general solution that works regardless of how many digits are in data$anim
, use the sprintf
function. It works like this:
sprintf("%04d", 1)
# [1] "0001"
sprintf("%04d", 104)
# [1] "0104"
sprintf("%010d", 104)
# [1] "0000000104"
In your case, you probably want: data$anim <- sprintf("%06d", data$anim)
I believe you simply call PrivateImpl
what it is: a non-public top-level class
. You can also declare non-public top-level interfaces
as well.
e.g., elsewhere on SO: Non-public top-level class vs static nested class
As for changes in behavior between versions, there was this discussion about something that "worked perfectly" in 1.2.2. but stopped working in 1.4 in sun's forum: Java Compiler - unable to declare a non public top level classes in a file.
In short, no, you can't.
Long answer, extension methods are just syntactic sugar. IE:
If you have an extension method on string let's say:
public static string SomeStringExtension(this string s)
{
//whatever..
}
When you then call it:
myString.SomeStringExtension();
The compiler just turns it into:
ExtensionClass.SomeStringExtension(myString);
So as you can see, there's no way to do that for static methods.
And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:
Bool.Parse(..)
vs.
Helper.ParseBool(..);
Doesn't really bring much to the table...
I know I'm a bit late, but was able to fix this issue by following the docs directly.
Add the meta-data tag to AndroidManifest.xml
(so the system knows)
<activity
android:name=".Sub"
android:label="Sub-Activity"
android:parentActivityName=".MainChooser"
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainChooser" />
</activity>
Next, enable the back (up) button in your MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_child);
// my_child_toolbar is defined in the layout file
Toolbar myChildToolbar =
(Toolbar) findViewById(R.id.my_child_toolbar);
setSupportActionBar(myChildToolbar);
// Get a support ActionBar corresponding to this toolbar
ActionBar ab = getSupportActionBar();
// Enable the Up button
ab.setDisplayHomeAsUpEnabled(true);
}
And, you will be all set up!
Source: Android Developer Documentation
Using =
causes the variable to be assigned a value. If the variable already had a value, it is replaced. This value will be expanded when it is used. For example:
HELLO = world
HELLO_WORLD = $(HELLO) world!
# This echoes "world world!"
echo $(HELLO_WORLD)
HELLO = hello
# This echoes "hello world!"
echo $(HELLO_WORLD)
Using :=
is similar to using =
. However, instead of the value being expanded when it is used, it is expanded during the assignment. For example:
HELLO = world
HELLO_WORLD := $(HELLO) world!
# This echoes "world world!"
echo $(HELLO_WORLD)
HELLO = hello
# Still echoes "world world!"
echo $(HELLO_WORLD)
HELLO_WORLD := $(HELLO) world!
# This echoes "hello world!"
echo $(HELLO_WORLD)
Using ?=
assigns the variable a value iff the variable was not previously assigned. If the variable was previously assigned a blank value (VAR=
), it is still considered set I think. Otherwise, functions exactly like =
.
Using +=
is like using =
, but instead of replacing the value, the value is appended to the current one, with a space in between. If the variable was previously set with :=
, it is expanded I think. The resulting value is expanded when it is used I think. For example:
HELLO_WORLD = hello
HELLO_WORLD += world!
# This echoes "hello world!"
echo $(HELLO_WORLD)
If something like HELLO_WORLD = $(HELLO_WORLD) world!
were used, recursion would result, which would most likely end the execution of your Makefile. If A := $(A) $(B)
were used, the result would not be the exact same as using +=
because B
is expanded with :=
whereas +=
would not cause B
to be expanded.
Consider .toFixed()
and .toPrecision()
:
df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
does already return a dataframe, so you cannot loop over the groups anymore.
In general:
df.groupby(...)
returns a GroupBy
object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:
grouped = df.groupby('A')
for name, group in grouped:
...
When you apply a function on the groupby, in your example df.groupby(...).agg(...)
(but this can also be transform
, apply
, mean
, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).
The solutions given here (renaming the branch in 'master') don't insist on the consequences for the remote (GitHub) repo:
-f --force
Usually, the command refuses to update a remote ref that is not an ancestor of the local ref used to overwrite it. This flag disables the check. This can cause the remote repository to lose commits; use it with care.
If others have already pulled your repo, they won't be able to pull that new master history without replacing their own master with that new GitHub master branch (or dealing with lots of merges).
There are alternatives to a git push --force for public repos.
Jefromi's answer (merging the right changes back to the original master) is one of them.
Issues were:
Here is how I fixed it:
IPV6 Disabling
su
and enter to log in as the super usercd /etc/modprobe.d/
to change directory to /etc/modprobe.d/
vi disableipv6.conf
to create a new file thereEsc + i
to insert data to fileinstall ipv6 /bin/true
on the file to avoid loading IPV6 related modulesEsc + :
and then wq
for save and exitreboot
to restart fedoralsmod | grep ipv6
Add Google DNS server
su
and enter to log in as the super usercat /etc/resolv.conf
to check what DNS server your Fedora using. Mostly this will be your Modem IP address.8.8.8.8
and 8.8.4.4
. But in future those may change.vi /etc/resolv.conf
to edit the resolv.conf
fileEsc + i
for insert data to fileType below two lines in the file
nameserver 8.8.8.8
nameserver 8.8.4.4
-Type Esc + :
and then wq
for save and exit
Here is my blog post about this: http://codeketchup.blogspot.sg/2014/07/how-to-fix-curl-6-could-not-resolve.html
There is a trick for this. All you have to do is to use RelativeLayout
instead of LinearLayout
as the main container. It's important to have android:layout_gravity="fill_horizontal"
set for it. That should do it.
Setting the 'Read Only' as 'True' is the easiest method.
Not sure why you specify that it has to be within Angular. It's easily accomplished through JavaScript. Look at the navigator
object.
Just open up your console and inspect navigator
. It seems what you're specifically looking for is .userAgent
or .appVersion
.
I don't have IE9 installed, but you could try this following code
//Detect if IE 9
if(navigator.appVersion.indexOf("MSIE 9.")!=-1)
firstOrCreate() checks for all the arguments to be present before it finds a match.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'abcd',
'lastName' => 'efgh',
'veristyName'=>'xyz',
]);
Then it check only the email
Sometimes, you may deal with an enumerated type with an underlying raw integer type that changes throughout the software development lifecycle. Here is an example that works well for that case:
public class MyClassThatLoadsTexturesEtc
{
//...
// Colors used for gems and sectors.
public enum Color: Int
{
// Colors arranged in order of the spectrum.
case First = 0
case Red, Orange, Yellow, Green, Blue, Purple, Pink
// --> Add more colors here, between the first and last markers.
case Last
}
//...
public func preloadGems()
{
// Preload all gems.
for i in (Color.First.toRaw() + 1) ..< (Color.Last.toRaw())
{
let color = Color.fromRaw(i)!
loadColoredTextures(forKey: color)
}
}
//...
}
Boolean types are defined in documentation:
http://docs.python.org/library/stdtypes.html#boolean-values
Quoted from doc:
Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to cast any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).
They are written as False and True, respectively.
So in java code remove braces, change true
to True
and you will be ok :)
You can always apply CCS class with rotate
property - http://css-tricks.com/snippets/css/text-rotation/
To keep rotated image within your div
dimensions you need to adjust CSS as well, there is no needs to use JavaScript except of adding class.
An alternative is to use the Alpine Linux containers, e.g. python:2.7-alpine
. They offer pip
out of the box (and have a smaller footprint which leads to faster builds etc).
Magic constants: Although these are not just symbols but important part of this token family. There are eight magical constants that change depending on where they are used.
__LINE__
: The current line number of the file.
__FILE__
: The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__
always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
__DIR__
: The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__)
. This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.)
__FUNCTION__
: The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__CLASS__
: The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. The class name includes the namespace it was declared in (e.g. Foo\Bar
). Note that as of PHP 5.4 __CLASS__
works also in traits. When used in a trait method, __CLASS__
is the name of the class the trait is used in.
__TRAIT__
: The trait name. (Added in PHP 5.4.0) As of PHP 5.4 this constant returns the trait as it was declared (case-sensitive). The trait name includes the namespace it was declared in (e.g. Foo\Bar
).
__METHOD__
: The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
__NAMESPACE__
: The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0).
What you need is:
if (!File.Exists(@"c:\test\Test\SomeFile.txt")) {
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
}
or
if (File.Exists(@"c:\test\Test\SomeFile.txt")) {
File.Delete(@"c:\test\Test\SomeFile.txt");
}
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
This will either:
Edit: I should clarify my answer, even though it's the most upvoted!
The second parameter of File.Move should be the destination file - not a folder. You are specifying the second parameter as the destination folder, not the destination filename - which is what File.Move requires.
So, your second parameter should be c:\test\Test\SomeFile.txt
.
You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts
and the second is named ProductsOverTenDollars
.
WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
SELECT
CategoryID,
CategoryName,
(SELECT COUNT(1) FROM Products p
WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
FROM Categories c
),
ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
SELECT
ProductID,
CategoryID,
ProductName,
UnitPrice
FROM Products p
WHERE UnitPrice > 10.0
)
SELECT c.CategoryName, c.NumberOfProducts,
p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
INNER JOIN CategoryAndNumberOfProducts c ON
p.CategoryID = c.CategoryID
ORDER BY ProductName
Now you want to do from binary string to Decimal but Afterword, You might be needed contrary method. It's down below.
public static String decimalToBinaryString(int value) {
String str = "";
while(value > 0) {
if(value % 2 == 1) {
str = "1"+str;
} else {
str = "0"+str;
}
value /= 2;
}
return str;
}
const download = (url, path) => new Promise((resolve, reject) => {
http.get(url, response => {
const statusCode = response.statusCode;
if (statusCode !== 200) {
return reject('Download error!');
}
const writeStream = fs.createWriteStream(path);
response.pipe(writeStream);
writeStream.on('error', () => reject('Error writing to file!'));
writeStream.on('finish', () => writeStream.close(resolve));
});}).catch(err => console.error(err));
Just one of the 10 sites configured on my Local IIS was giving this error, so I had a feeling that it wasn't anything from the other answers that were machine-wide things, like Turning Windows Features On or Off, or running VS2015 as admin (the other 9 sites worked ok, in the same VS).
The specific error for me was:
Unable to start debugging on the webserver. Operation not supported. Unknown error:0x80004005
The problem turned out to be the web config having a URL Rewrite rule to rewrite HTTP -> HTTPS. Commenting this out resolved the problem
TL;DR - try disabling all your web.config URL rewrite rules, if you have them (then add them back in gradually, if it helps)
Solved: The problem lies here:
I set POST
via both _CUSTOMREQUEST
and _POST
and the _CUSTOMREQUEST
persisted as POST
while _POST
switched to _HTTPGET
. The Server assumed the header from _CUSTOMREQUEST
to be the right one and came back with a 411.
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');
This is Very Good Example of minus Length of an array in java, i am giving here both examples
public static int linearSearchArray(){
int[] arrayOFInt = {1,7,5,55,89,1,214,78,2,0,8,2,3,4,7};
int key = 7;
int i = 0;
int count = 0;
for ( i = 0; i< arrayOFInt.length; i++){
if ( arrayOFInt[i] == key ){
System.out.println("Key Found in arrayOFInt = " + arrayOFInt[i] );
count ++;
}
}
System.out.println("this Element found the ("+ count +") number of Times");
return i;
}
this above i < arrayOFInt.length; not need to minus one by length of array; but if you i <= arrayOFInt.length -1; is necessary other wise arrayOutOfIndexException Occur, hope this will help you.
Using inputStream.available()
It is always acceptable for System.in.available() to return 0.
I've found the opposite - it always returns the best value for the number of bytes available. Javadoc for InputStream.available()
:
Returns an estimate of the number of bytes that can be read (or skipped over)
from this input stream without blocking by the next invocation of a method for
this input stream.
An estimate is unavoidable due to timing/staleness. The figure can be a one-off underestimate because new data are constantly arriving. However it always "catches up" on the next call - it should account for all arrived data, bar that arriving just at the moment of the new call. Permanently returning 0 when there are data fails the condition above.
First Caveat: Concrete subclasses of InputStream are responsible for available()
InputStream
is an abstract class. It has no data source. It's meaningless for it to have available data. Hence, javadoc for available()
also states:
The available method for class InputStream always returns 0.
This method should be overridden by subclasses.
And indeed, the concrete input stream classes do override available(), providing meaningful values, not constant 0s.
Second Caveat: Ensure you use carriage-return when typing input in Windows.
If using System.in
, your program only receives input when your command shell hands it over. If you're using file redirection/pipes (e.g. somefile > java myJavaApp or somecommand | java myJavaApp ), then input data are usually handed over immediately. However, if you manually type input, then data handover can be delayed. E.g. With windows cmd.exe shell, the data are buffered within cmd.exe shell. Data are only passed to the executing java program following carriage-return (control-m or <enter>
). That's a limitation of the execution environment. Of course, InputStream.available() will return 0 for as long as the shell buffers the data - that's correct behaviour; there are no available data at that point. As soon as the data are available from the shell, the method returns a value > 0. NB: Cygwin uses cmd.exe too.
Just use this:
byte[] inputData = new byte[1024];
int result = is.read(inputData, 0, is.available());
// result will indicate number of bytes read; -1 for EOF with no data read.
OR equivalently,
BufferedReader br = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")),1024);
// ...
// inside some iteration / processing logic:
if (br.ready()) {
int readCount = br.read(inputData, bufferOffset, inputData.length-bufferOffset);
}
Declare this:
public static int readInputStreamWithTimeout(InputStream is, byte[] b, int timeoutMillis)
throws IOException {
int bufferOffset = 0;
long maxTimeMillis = System.currentTimeMillis() + timeoutMillis;
while (System.currentTimeMillis() < maxTimeMillis && bufferOffset < b.length) {
int readLength = java.lang.Math.min(is.available(),b.length-bufferOffset);
// can alternatively use bufferedReader, guarded by isReady():
int readResult = is.read(b, bufferOffset, readLength);
if (readResult == -1) break;
bufferOffset += readResult;
}
return bufferOffset;
}
Then use this:
byte[] inputData = new byte[1024];
int readCount = readInputStreamWithTimeout(System.in, inputData, 6000); // 6 second timeout
// readCount will indicate number of bytes read; -1 for EOF with no data read.
In android it is called a Spinner you can take a look at the tutorial here.
And this is a very vague question, you should try to be more descriptive of your problem.
[I realize this question is a million years old, but there is a deeper question (or two) at its heart, about OP, the pedagogy of programming, and about assumption-making.]
A few people, including a mod, have suggested this is impossible. And, in some--including the most obvious--contexts, it is. But it's interesting to see that that wasn't immediately obvious to the OP.
The impossibility assumes that the contex is running an executable compiled from C on a line-oriented text console (e.g., console+sh or X-term+csh or Terminal+bash), which is a very reasonable assumption. But the fact that the "right" answer ("%8d
") wasn't good enough for OP while also being non-obvious suggests that there's a pretty big can of worms nearby...
Consider Curses (and its many variants). In it, you can navigate the "screen", and "move" the cursor around, and "repaint" portions (windows) of text-based output. In a Curses context, it absolutely would be possible to do; i.e., dynamically resize a "window" to accommodate a larger number. But even Curses is just a screen "painting" abstraction. No one suggested it, and probably rightfully so, because a Curses implementation in C doesn't mean it's "strictly C". Fine.
But what does this really mean? In order for the response: "it's impossible" to be correct, it would mean that we're saying something about the runtime system. In other words, this isn't theoretical, (as in, "How do I sort a statically-allocated array of int
s?"), which can be explained as a "closed system" that totally ignores any aspect of the runtime.
But, in this case, we have I/O: specifically, the implementation of printf()
. But that's where there's an opportunity to have said something more interesting in response (even though, admittedly, the asker was probably not digging quite this deep).
Suppose we use a different set of assumptions. Suppose OP is reasonably "clever" and understands that it would not be possible to to edit previous lines on a line-oriented stream (how would you correct the horizontal position of a character output by a line-printer??). Suppose also, that OP isn't just a kid working on a homework assignment and not realizing it was a "trick" question, intended to tease out an exploration of the meaning of "stream abstraction". Further, let's suppose OP was wondering: "Wait...If C's runtime environment supports the idea of STDOUT--and if STDOUT is just an abstraction--why isn't it just as reasonable to have a terminal abstraction that 1) can vertically scroll but 2) supports a positionable cursor? Both are moving text on a screen."
Because if that were the question we're trying to answer, then you'd only have to look as far as:
to see that:
Almost all manufacturers of video terminals added vendor-specific escape sequences to perform operations such as placing the cursor at arbitrary positions on the screen. One example is the VT52 terminal, which allowed the cursor to be placed at an x,y location on the screen by sending the ESC character, a Y character, and then two characters representing with numerical values equal to the x,y location plus 32 (thus starting at the ASCII space character and avoiding the control characters). The Hazeltine 1500 had a similar feature, invoked using ~, DC1 and then the X and Y positions separated with a comma. While the two terminals had identical functionality in this regard, different control sequences had to be used to invoke them.
The first popular video terminal to support these sequences was the Digital VT100, introduced in 1978. This model was very successful in the market, which sparked a variety of VT100 clones, among the earliest and most popular of which was the much more affordable Zenith Z-19 in 1979. Others included the Qume QVT-108, Televideo TVI-970, Wyse WY-99GT as well as optional "VT100" or "VT103" or "ANSI" modes with varying degrees of compatibility on many other brands. The popularity of these gradually led to more and more software (especially bulletin board systems and other online services) assuming the escape sequences worked, leading to almost all new terminals and emulator programs supporting them.
It has been possible, as early as 1978. C itself was "born" in 1972, and the K&R version was established in 1978. If "ANSI" escape sequences were around at that time, then there is an answer "in C" if we're willing to also stipulate: "Well, assuming your terminal is VT100-capable." Incidentally, the consoles which don't support ANSI escapes? You guessed it: Windows & DOS consoles. But on almost every other platform (Unices, Vaxen, Mac OS, Linux) you can expect to.
TL;DR - There is no reasonable answer that can be given without stating assumptions about the runtime environment. Since most runtimes (unless you're using desktop-computer-market-share-of-the-80's-and-90's to calculate 'most') would have, (since the time of the VT-52!), then I don't think it's entirely justified to say that it's impossible--just that in order for it to be possible, it's an entire different order of magnitude of work, and not as simple as %8d
...which it kinda seemed like the OP knew about.
We just have to clarify the assumptions.
And lest one thinks that I/O is exceptional, i.e., the only time we need to think about the runtime, (or even the hardware), just dig into IEEE 754 Floating Point exception handling. For those interested:
Intel Floating Point Case Study
According to Professor William Kahan, University of California at Berkeley, a classic case occurred in June 1996. A satellite-lifting rocket named Ariane 5 turned cartwheels shortly after launch and scattered itself and a payload worth over half a billion dollars over a marsh in French Guiana. Kahan found the disaster could be blamed upon a programming language that disregarded the default exception-handling specifications in IEEE 754. Upon launch, sensors reported acceleration so strong that it caused a conversion-to-integer overflow in software intended for recalibration of the rocket’s inertial guidance while on the launching pad.
Best as an out parameter:
void testfunc(char* outStr){
char str[10];
for(int i=0; i < 10; ++i){
outStr[i] = str[i];
}
}
Called with
int main(){
char myStr[10];
testfunc(myStr);
// myStr is now filled
}
I have a Windows service, and I added the following line to the constructor for my service:
using System.Diagnostics;
try {
Process p = Process.Start(@"C:\Windows\system32\calc.exe");
} catch {
Debugger.Break();
}
When I tried to run this, the Process.Start() call was made, and no exception occurred. However, the calc.exe application did not show up. In order to make it work, I had edit the properties for my service in the Service Control Manager to enable interaction with the desktop. After doing that, the Process.Start() opened calc.exe as expected.
But as others have said, interaction with the desktop is frowned upon by Microsoft and has essentially been disabled in Vista. So even if you can get it to work in XP, I don't know that you'll be able to make it work in Vista.
Emacs takes many launch options. The one that you are looking for is
emacs -nw
. This will open Emacs inside the terminal disregarding the DISPLAY environment variable even if it is set.
The long form of this flag is emacs --no-window-system
.
More information about Emacs launch options can be found in the manual.
Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.
If you're on GNU Make, use the :=
assignment instead of =
. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.
FILES := $(shell ...) # expand now; FILES is now the result of $(shell ...)
FILES = $(shell ...) # expand later: FILES holds the syntax $(shell ...)
If you use the =
assignment, it means that every single occurrence of $(FILES)
will be expanding the $(shell ...)
syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.
Traits are simply for code reuse.
Interface just provides the signature of the functions that is to be defined in the class where it can be used depending on the programmer's discretion. Thus giving us a prototype for a group of classes.
For reference- http://www.php.net/manual/en/language.oop5.traits.php
This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like
so_far = " " * len(word)
?
Edit:
try something like
print "%d / %d" % (new, so_far)
before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you're not actually using the instance you think.
I use the "an index points between elements" method of thinking about it myself, but one way of describing it which sometimes helps others get it is this:
mylist[X:Y]
X is the index of the first element you want.
Y is the index of the first element you don't want.
Operators.LikeString
public static bool LikeString(
string Source,
string Pattern,
CompareMethod CompareOption
)
In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel Text
that is bound to your TextBox and you would have an ICommand
property Apply
(or similar) that is bound to the button:
<Button Command="Apply">Apply</Button>
The ICommand
interface has a Method CanExecute
that is where you return true
if (!string.IsNullOrWhiteSpace(this.Text)
. The rest is done by WPF for you (enabling/disabling, executing the actual command on click).
The linked article explains it in detail.
My problem is multi modules project with base module, app module and feature module. Each module has AndroidManifest of its own, and I implemented build variant for debug and main. So we must sure that "android:name" just declared in Manifest of debug and main only, and do not set it in any of Manifest in child module. Ex: Manifest in main:
<application
android:name=".App"/>
Manifest in debug:
<application
tools:replace="android:name"
android:name=".DebugApp"
/>
Do not set "android:name" in other Manifest files like this:
<application android:name=".App">
Just define in feature module like this and it will merged fine
<application>
Guys regarding time taken for importing huge files most importantly it takes more time is because default setting of mysql is "autocommit = true", you must set that off before importing your file and then check how import works like a gem...
First open MySQL:
mysql -u root -p
Then, You just need to do following :
mysql>use your_db
mysql>SET autocommit=0 ; source the_sql_file.sql ; COMMIT ;
With the following you can insert multiple values and also have default values but you're creating a new dictionary.
d = {**{ key: value }, **default_values}
I've tested it with the most voted answer and on average this is faster as it can be seen in the following example, .
Speed test comparing a for loop based method with a dict comprehension with unpack operator method.
if no copy (d = default_vals.copy()
) is made on the first case then the most voted answer would be faster once we reach orders of magnitude of 10**5
and greater. Memory footprint of both methods are the same.
You can refer to following link for which features are supported in particular version of compiler. It has an exhaustive list of feature support in compiler. Looks GCC follows standard closely and implements before any other compiler.
Regarding your question you can compile using
g++ -std=c++11
for C++11 g++ -std=c++14
for C++14g++ -std=c++17
for C++17g++ -std=c++2a
for C++20, although all features of C++20 are not yet supported refer this link for feature support list in GCC.The list changes pretty fast, keep an eye on the list, if you are waiting for particular feature to be supported.
You can compile any java source using javac in command line ; eg, javac CopyFile.java. To run : java CopyFile. You can also compile all java files using javac *.java as long as they're in the same directory
If you're having an issue resulting with "could not find or load main class" you may not have jre in your path. Have a look at this question: Could not find or load main class
((frmMain)this.Owner).MyListControl.Items.Add("abc");
Make sure to provide access level you want at Modifiers properties other than Private for MyListControl
at frmMain
After speaking with my team-mates, Ricardo told us that the faster way is:
show table status like '<TABLE NAME>' \G
But you have to remember that the result may not be exact.
You can use it from command line too:
$ mysqlshow --status <DATABASE> <TABLE NAME>
More information: http://dev.mysql.com/doc/refman/5.7/en/show-table-status.html
And you can find a complete discussion at mysqlperformanceblog
Actually, I think this is the best way.
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
val = URLValidator(verify_exists=False)
try:
val('http://www.google.com')
except ValidationError, e:
print e
If you set verify_exists
to True
, it will actually verify that the URL exists, otherwise it will just check if it's formed correctly.
edit: ah yeah, this question is a duplicate of this: How can I check if a URL exists with Django’s validators?
preventDefault is what you're looking for. To just block the button from submitting
<Button onClick={this.onClickButton} ...
code
onClickButton (event) {
event.preventDefault();
}
If you have a form which you want to handle in a custom way you can capture a higher level event onSubmit which will also stop that button from submitting.
<form onSubmit={this.onSubmit}>
and above in code
onSubmit (event) {
event.preventDefault();
// custom form handling here
}
#import <MessageUI/MessageUI.h>
in your header fileMFMessageComposeViewControllerDelegate
& UINavigationControllerDelegate
IBAction
method declare instance of MFMessageComposeViewController
say messageInstance
[MFMessageComposeViewController canSendText]
in an if condition, it'll return Yes/No In the if
condition do these:
First set body for your messageInstance
as:
messageInstance.body = @"Hello from Shah";
Then decide the recipients for the message as:
messageInstance.recipients = [NSArray arrayWithObjects:@"12345678", @"87654321", nil];
Set a delegate to your messageInstance as:
messageInstance.messageComposeDelegate = self;
In the last line do this:
[self presentModalViewController:messageInstance animated:YES];
Have a look at Collections.sort()
and the Comparator
interface.
String comparison can be done with object1.getName().compareTo(object2.getName())
or object2.getName().compareTo(object1.getName())
(depending on the sort direction you desire).
If you want the sort to be case agnostic, do object1.getName().toUpperCase().compareTo(object2.getName().toUpperCase())
.
Seems almost pointless to add an answer, but I was fighting this for ages when I finally discovered it was Visual Studio Online that was suffering a sporadic outage. That became apparent when VS kept prompting for creds and the VSO website sometimes gave a 500.
Counting objects: 138816, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (38049/38049), done.
error: unable to rewind rpc post data - try increasing http.postBuffer
error: RPC failed; curl 56 SSL read: error:00000000:lib(0):func(0):reason(0), errno 10054
The remote end hung up unexpectedly/138816), 33.30 MiB | 3.00 KiB/s
Writing objects: 100% (138816/138816), 50.21 MiB | 3.00 KiB/s, done.
Total 138816 (delta 100197), reused 134574 (delta 96515)
fatal: The remote end hung up unexpectedly
Everything up-to-date
I set my HTTP post buffer back to 2 MB afterwards, since I actually think it works better with many smaller posts.
Another problem you are likely to face after setting up all your URLconf patterns is that the variable {{ MEDIA_URL }}
won't work in your templates. To fix this,in your settings.py, make sure you add
django.core.context_processors.media
in your TEMPLATE_CONTEXT_PROCESSORS
.
The ~
selector is in fact the General sibling combinator (renamed to Subsequent-sibling combinator in selectors Level 4):
The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.
Consider the following example:
.a ~ .b {_x000D_
background-color: powderblue;_x000D_
}
_x000D_
<ul>_x000D_
<li class="b">1st</li>_x000D_
<li class="a">2nd</li>_x000D_
<li>3rd</li>_x000D_
<li class="b">4th</li>_x000D_
<li class="b">5th</li>_x000D_
</ul>
_x000D_
.a ~ .b
matches the 4th and 5th list item because they:
.b
elements .a
.a
in HTML source order.Likewise, .check:checked ~ .content
matches all .content
elements that are siblings of .check:checked
and appear after it.
For Eloquent you can just do:
$result->getQuery()->toSql();
But you need to remove the "->get()" part from your query.
Angular 8 Radio Listing Example:
Source Link
JSON Response
[
{
"moduleId": 1,
"moduleName": "Employee",
"subModules":[
{
"subModuleId": 1,
"subModuleName": "Add Employee",
"selectedRightType": 1,
},{
"subModuleId": 2,
"subModuleName": "Update Employee",
"selectedRightType": 2,
},{
"subModuleId": 3,
"subModuleName": "Delete Employee",
"selectedRightType": 3,
}
]
},
{
"moduleId": 2,
"moduleName": "Company",
"subModules":[
{
"subModuleId": 4,
"subModuleName": "Add Company",
"selectedRightType": 1,
},{
"subModuleId": 5,
"subModuleName": "Update Company",
"selectedRightType": 2,
},{
"subModuleId": 6,
"subModuleName": "Delete Company",
"selectedRightType": 3,
}
]
},
{
"moduleId": 3,
"moduleName": "Tasks",
"subModules":[
{
"subModuleId": 7,
"subModuleName": "Add Task",
"selectedRightType": 1,
},{
"subModuleId": 8,
"subModuleName": "Update Task",
"selectedRightType": 2,
},{
"subModuleId": 9,
"subModuleName": "Delete Task",
"selectedRightType": 3,
}
]
}
]
HTML Template
<div *ngFor="let module of modules_object">
<div>{{module.moduleName}}</div>
<table width="100%">
<thead>
<tr>
<th>Submodule</th>
<th>
<input type="radio" name="{{module.moduleName}}_head_radio" [(ngModel)]="module.selHeader" (change)="selAllColumn(module)" [value]="1"> Read Only
</th>
<th>
<input type="radio" name="{{module.moduleName}}_head_radio" [(ngModel)]="module.selHeader" (change)="selAllColumn(module)" [value]="2"> Read Write
</th>
<th>
<input type="radio" name="{{module.moduleName}}_head_radio" [(ngModel)]="module.selHeader" (change)="selAllColumn(module)" [value]="3"> No Access
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let sm of module.subModules">
<td>{{sm.subModuleName}}</td>
<td>
<input type="radio" [checked]="sm.selectedRightType == '1'" [(ngModel)]="sm.selectedRightType" name="{{sm.subModuleId}}_radio" [value]="1">
</td>
<td class="cl-left">
<input type="radio" [checked]="sm.selectedRightType == '2'" [(ngModel)]="sm.selectedRightType" name="{{sm.subModuleId}}_radio" [value]="2">
</td>
<td class="cl-left">
<input type="radio" [checked]="sm.selectedRightType == '3'" [(ngModel)]="sm.selectedRightType" name="{{sm.subModuleId}}_radio" [value]="3">
</td>
</tr>
</tbody>
</table>
</div>
on windows, when you have no admin right, just create a new program shortcut to Rgui.exe. Then in the properties of that shortcut, go to the 'Shortcut' tab and modify the target to include the system language of your choice, e.g. "C:\Program Files\R\R-3.5.3\bin\x64\Rgui.exe" LANGUAGE=en
Though you have to be careful. It is not clearly said in your intro, if you are looking only at latine language. Some words can become meaningless or another meaning if you sanitize them with ascii characters only.
imagine you have "forêt poésie" (forest poetry), your sanitization might give "fort-posie" (strong + something meaningless)
Worse if you have to deal with chinese characters.
"???" your system might end up doing "---" which is doomed to fail after a while and not very helpful. So if you deal with only files I would encourage to either call them a generic chain that you control or to keep the characters as it is. For URIs, about the same.
Sometimes SUM_IF can get the job done.
Suppose you have a sheet of product information, including unique productID
in column A and unit price in column P. And a sheet of purchase order entries with product IDs in column A, and you want column T to calculate the unit price for the entry.
The following formula will do the trick in cell Entries!T2 and can be copied to the other cells in the same column.
=SUMIF(Products!$A$2:$A$9999,Entries!$A2, Products!$P$2:$9999)
Then you could have another column with number of items per entry and multiply it with the unit price to get total cost for the entry.
Use ENUM in MySQL for true / false it gives and accepts the true / false values without any extra code.
ALTER TABLE `itemcategory` ADD `aaa` ENUM('false', 'true') NOT NULL DEFAULT 'false'
a.shape
is just a limited version of np.info()
. Check this out:
import numpy as np
a = np.array([[1,2],[1,2]])
np.info(a)
Out
class: ndarray
shape: (2, 2)
strides: (8, 4)
itemsize: 4
aligned: True
contiguous: True
fortran: False
data pointer: 0x27509cf0560
byteorder: little
byteswap: False
type: int32
This works for me under Specific Page for MVC:
/Home/Index
Update: Currently, I just use a forward slash in the "Specific Page" textbox, and it takes me to the home page as defined in the routing:
/
Try this method:
public static Date addDay(int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, day);
return calendar.getTime();
}
You can use CSS white-space
property for \n
. You can also preserve the tabs as in \t
.
For line break \n
:
white-space: pre-line;
For line break \n
and tabs \t
:
white-space: pre-wrap;
document.getElementById('just-line-break').innerHTML = 'Testing 1\nTesting 2\n\tNo tab';_x000D_
_x000D_
document.getElementById('line-break-and-tab').innerHTML = 'Testing 1\nTesting 2\n\tWith tab';
_x000D_
#just-line-break {_x000D_
white-space: pre-line;_x000D_
}_x000D_
_x000D_
#line-break-and-tab {_x000D_
white-space: pre-wrap;_x000D_
}
_x000D_
<div id="just-line-break"></div>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<div id="line-break-and-tab"></div>
_x000D_
On my machine this only works in bin/idea.vmoptions
, adding the setting in ~/Library/Preferences/IntelliJIdea12/idea.vmoptions
causes the IDEA to hang during startup.
One nice feature of the Immediate Window in Visual Studio is its ability to evaluate the return value of a method particularly if it is called by your client code but it is not part of a variable assignment. In Debug mode, as mentioned, you can interact with variables and execute expressions in memory which plays an important role in being able to do this.
For example, if you had a static method that returns the sum of two numbers such as:
private static int GetSum(int a, int b)
{
return a + b;
}
Then in the Immediate Window you can type the following:
? GetSum(2, 4)
6
As you can seen, this works really well for static methods. However, if the method is non-static then you need to interact with a reference to the object the method belongs to.
For example, let’s say this is what your class looks like:
private class Foo
{
public string GetMessage()
{
return "hello";
}
}
If the object already exists in memory and it’s in scope, then you can call it in the Immediate Window as long as it has been instantiated before your current breakpoint (or, at least, before wherever the code is paused in debug mode):
? foo.GetMessage(); // object ‘foo’ already exists
"hello"
In addition, if you want to interact and test the method directly without relying on an existing instance in memory, then you can instantiate your own instance in the Immediate Window:
? Foo foo = new Foo(); // new instance of ‘Foo’
{temp.Program.Foo}
? foo.GetMessage()
"hello"
You can take it a step further and temporarily assign the method's results to variables if you want to do further evaluations, calculations, etc.:
? string msg = foo.GetMessage();
"hello"
? msg + " there!"
"hello there!"
Furthermore, if you don’t even want to declare a variable name for a new object and just want to run one of its methods/functions then do this:
? new Foo().GetMessage()
"hello"
A very common way to see the value of a method is to select the method name of a class and do a ‘Add Watch’ so that you can see its current value in the Watch window. However, once again, the object needs to be instantiated and in scope for a valid value to be displayed. This is much less powerful and more restrictive than using the Immediate Window.
Along with inspecting methods, you can do simple math equations:
? 5 * 6
30
or compare values:
? 5==6
false
? 6==6
true
The question mark ('?') is unnecessary if you are in directly in the Immediate Window but it is included here for clarity (to distinguish between the typed in expressions versus the results.) However, if you are in the Command Window and need to do some quick stuff in the Immediate Window then precede your statements with '?' and off you go.
Intellisense works in the Immediate Window, but it sometimes can be a bit inconsistent. In my experience, it seems to be only available in Debug mode, but not in design, non-debug mode.
Unfortunately, another drawback of the Immediate Window is that it does not support loops.
My solution was to use excel (2010).
In a new worksheet, select a cell, then:
Data -> From Other Sources -> From SQL Server
put in the server name, select table, etc,
When you get to the "Import Data" dialog,
click on Properties in the "Connection Properties" dialog,
select the "Definition" tab.
And there Excel nicely displays the Connection String for copying
(or even Export Connection File...)
If you want to use numpy only:
x = [-1, 2, 1, 3, 3]
vals,counts = np.unique(x, return_counts=True)
gives
(array([-1, 1, 2, 3]), array([1, 1, 1, 2]))
And extract it:
index = np.argmax(counts)
return vals[index]
Single line looping,
declare -a listOfNames=('db_a' 'db_b' 'db_c')
for databaseName in ${listOfNames[@]}; do echo $databaseName; done;
you will get an output like this,
db_a
db_b
db_c
What about using mysql -v
to put mysql client in verbose mode ?
Need to merge the properties in object. For Example,
const boxStyle = {
width : "50px",
height : "50px"
};
const redBackground = {
...boxStyle,
background: "red",
};
const blueBackground = {
...boxStyle,
background: "blue",
}
<div style={redBackground}></div>
<div style={blueBackground}></div>
Here are the steps:
click File > Import. The Import window opens.
Under Select an import source, click J2EE > App Client JAR file.
Click Next.
In the Application Client file field, enter the location and name of the application client JAR file that you want to import. You can click the Browse button to select the JAR file from the file system.
In the Application Client project field, type a new project name or select an application client project from the drop-down list. If you type a new name in this field, the application client project will be created based on the version of the application client JAR file, and it will use the default location.
In the Target runtime drop-down list, select the application server that you want to target for your development. This selection affects the run time settings by modifying the class path entries for the project.
If you want to add the new module to an enterprise application project, select the Add project to an EAR check box and then select an existing enterprise application project from the list or create a new one by clicking New.
Note: If you type a new enterprise application project name, the enterprise application project will be created in the default location with the lowest compatible J2EE version based on the version of the project being created. If you want to specify a different version or a different location for the enterprise application, you must use the New Enterprise Application Project wizard.
Click Finish to import the application client JAR file.
I tried all the suggested solutions but no luck.
Finally I found I need to use admin layout & template & skin from a fresh Magento version that you need to upgrade to. For example in my case it is 1.9.2.4
-- Basically, get all the files (from app/design/adminhtml/default of the fresh version), copy and paste these to the folder app/design/adminhtml/default of the current site to replace all the old files if any
-- Basically, get all the files (from skin/adminhtml/default of the fresh version), copy and paste these to the folder skin/adminhtml/default of the current site to replace all the old files if any
Of course, remember to make backups before doing that.
The best is to use a version control as GIT or SVN.
You could make a method:
public byte[] toBytes(char[] data) {
byte[] toRet = new byte[data.length];
for(int i = 0; i < toRet.length; i++) {
toRet[i] = (byte) data[i];
}
return toRet;
}
Hope this helps
Consider this question asked at StackOverflow today:
A good test and a practical example is what happens in the above scenario...
The developer used the name of the JavaScript function in one of his variables.
What's the problem with the code?
The code only works the first time the user clicks the button.
What's the solution?
Add the var
keyword before the variable name.
Comment out the res.render
lines in your code and add in next(err);
instead. If you're not using a view engine, the res.render
stuff will throw an error.
Sorry, you'll have to comment out this line as well:
app.set('view engine', 'html');
My solution would result in not using a view engine though. You don't need a view engine, but if that's the goal, try this:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//swap jade for ejs etc
You'll need the res.render
lines when using a view engine as well. Something like this:
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
next(err);
res.render('error', {
message: err.message,
error: {}
});
});
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.
The names of the first dataframe do not match the names of the second one. Just as the error message says.
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE
If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:
> names(xd.small[[1]]) <- names(xd.small[[2]])
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE
Then things should proceed happily.
For those coming from Google (etc.) such as myself:
convert_objects
has been deprecated since 0.17 - if you use it, you get a warning like this one:
FutureWarning: convert_objects is deprecated. Use the data-type specific converters
pd.to_datetime, pd.to_timedelta and pd.to_numeric.
You should do something like the following:
df =
df.astype(np.float)
df["A"] =
pd.to_numeric(df["A"])
Literally:
(using Firefox v3.6, with for-in
caveats as previously noted
(HOWEVER the use below might endorse for-in
for this very purpose! That is, enumerating array elements that ACTUALLY exist via a property index (HOWEVER, in particular, the array length
property is NOT enumerated in the for-in
property list!).).)
(Drag & drop the following complete URI's for immediate mode browser testing.)
function ObjInRA(ra){var has=false; for(i in ra){has=true; break;} return has;}
function check(ra){
return ['There is ',ObjInRA(ra)?'an':'NO',' object in [',ra,'].'].join('')
}
alert([
check([{}]), check([]), check([,2,3]),
check(['']), '\t (a null string)', check([,,,])
].join('\n'));
which displays:
There is an object in [[object Object]].
There is NO object in [].
There is an object in [,2,3].
There is an object in [].
(a null string)
There is NO object in [,,].
Wrinkles: if looking for a "specific" object consider:
JavaScript: alert({}!={}); alert({}!=={});
And thus:
obj = {prop:"value"};
ra1 = [obj];
ra2 = [{prop:"value"}];
alert(ra1[0] == obj);
alert(ra2[0] == obj);
Often ra2
is considered to "contain" obj
as the literal entity {prop:"value"}
.
A very coarse, rudimentary, naive (as in code needs qualification enhancing) solution:
obj={prop:"value"}; ra2=[{prop:"value"}];
alert(
ra2 . toSource() . indexOf( obj.toSource().match(/^.(.*).$/)[1] ) != -1 ?
'found' :
'missing' );
PowerShell currently doesn't didn't have a native Inline If (or ternary If) but you could consider to use the custom cmdlet:
IIf <condition> <condition-is-true> <condition-is-false>
simple and easier solution:
select extract(hour from systimestamp) from dual;
EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
16
Why not try with what angular docs mention https://docs.angularjs.org/api/ng/function/angular.element.
angular.element(callback)
I've used this inside my $onInit(){...} function.
var self = this;
angular.element(function () {
var target = document.getElementsByClassName('unitSortingModule');
target[0].addEventListener("touchstart", self.touchHandler, false);
...
});
This worked for me.
I had a similar issue and this is what worked for me.
Add the NodeSource package signing key:
curl -sSL https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -
# wget can also be used:
# wget --quiet -O - https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -
Add the desired NodeSource repository:
# Replace with the branch of Node.js or io.js you want to install: node_6.x, node_12.x, etc...
VERSION=node_12.x
# The below command will set this correctly, but if lsb_release isn't available, you can set it manually:
# - For Debian distributions: jessie, sid, etc...
# - For Ubuntu distributions: xenial, bionic, etc...
# - For Debian or Ubuntu derived distributions your best option is to use the codename corresponding to the upstream release your distribution is based off. This is an advanced scenario and unsupported if your distribution is not listed as supported per earlier in this README.
DISTRO="$(lsb_release -s -c)"
echo "deb https://deb.nodesource.com/$VERSION $DISTRO main" | sudo tee /etc/apt/sources.list.d/nodesource.list
echo "deb-src https://deb.nodesource.com/$VERSION $DISTRO main" | sudo tee -a /etc/apt/sources.list.d/nodesource.list
Update package lists and install Node.js
:
sudo apt-get update
sudo apt-get install nodejs
JavaScript
function playAudio(url) {
new Audio(url).play();
}
HTML
<img src="image.png" onclick="playAudio('mysound.mp3')">
Supported in most modern browsers and easy to embed into HTML elements.
Your web.config
file should have this structure:
<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="..." />
</connectionStrings>
</configuration>
Then, to create a SQL connection using the connection string named MyConnectionString
:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
If you'd prefer to keep your connection strings in the AppSettings
section of your configuration file, it would look like this:
<configuration>
<appSettings>
<add key="MyConnectionString" value="..." />
</appSettings>
</configuration>
And then your SqlConnection constructor would look like this:
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"]);
ES6 (ECMAScript 2015) Version:
const counts = [4, 9, 15, 6, 2];
const goal = 5;
const output = counts.reduce((prev, curr) => Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
console.log(output);
_x000D_
For reusability you can wrap in a curry function that supports placeholders (http://ramdajs.com/0.19.1/docs/#curry or https://lodash.com/docs#curry). This gives lots of flexibility depending on what you need:
const getClosest = _.curry((counts, goal) => {
return counts.reduce((prev, curr) => Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});
const closestToFive = getClosest(_, 5);
const output = closestToFive([4, 9, 15, 6, 2]);
console.log(output);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
You'll want to do get a Calendar instance and get it's day of month
Calendar cal = Calendar.getInstance();
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
String dayOfMonthStr = String.valueOf(dayOfMonth);
You can also get DAY_OF_WEEK, DAY_OF_YEAR, DAY_OF_WEEK_IN_MONTH, etc.
To test your method validation in a test, you have to wrap it a proxy in the @Before method.
@Before
public void setUp() {
this.classAutowiredWithFindStuffMethod = MethodValidationProxyFactory.createProxy(this.classAutowiredWithFindStuffMethod);
}
With MethodValidationProxyFactory as :
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
public class MethodValidationProxyFactory {
private static final StaticApplicationContext ctx = new StaticApplicationContext();
static {
MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
processor.afterPropertiesSet(); // init advisor
ctx.getBeanFactory()
.addBeanPostProcessor(processor);
}
@SuppressWarnings("unchecked")
public static <T> T createProxy(T instance) {
return (T) ctx.getAutowireCapableBeanFactory()
.applyBeanPostProcessorsAfterInitialization(instance, instance.getClass()
.getName());
}
}
And then, add your test :
@Test
public void findingNullStuff() {
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> this.classAutowiredWithFindStuffMethod.findStuff(null));
}
Either structure is valid and accessible, but the for
attribute should be equal to the id
of the input element:
<input type="radio" ... id="r1" /><label for="r1">button text</label>
or
<label for="r1"><input type="radio" ... id="r1" />button text</label>
The for
attribute is optional in the second version (label containing input), but IIRC there were some older browsers that didn't make the label text clickable unless you included it. The first version (label after input) is easier to style with CSS using the adjacent sibling selector +
:
input[type="radio"]:checked+label {font-weight:bold;}
The LDF stand for 'Log database file' and it is the transaction log. It keeps a record of everything done to the database for rollback purposes, you can restore a database even you lost .msf file because it contain all control information plus transaction information .
Put this code above any Soap call:
libxml_disable_entity_loader(false);
Ruby gem to convert zip code to timezone: https://github.com/Katlean/TZip (forked from https://github.com/farski/TZip).
> ActiveSupport::TimeZone.find_by_zipcode('90029')
=> "Pacific Time (US & Canada)"
It's fast, small, and has no external dependencies, but keep in mind that zip codes just don't map perfectly to timezones.
Since you return to the client just String
and its content type == 'text/plain'
, there is no any chance for default converters to determine how to convert String
response to the FFSampleResponseHttp
object.
The simple way to fix it:
expected-response-type
from <int-http:outbound-gateway>
replyChannel1
<json-to-object-transformer>
Otherwise you should write your own HttpMessageConverter
to convert the String to the appropriate object.
To make it work with MappingJackson2HttpMessageConverter
(one of default converters) and your expected-response-type
, you should send your reply with content type = 'application/json'
.
If there is a need, just add <header-enricher>
after your <service-activator>
and before sending a reply to the <int-http:inbound-gateway>
.
So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.
UPDATE
OK. Since you changed your server to return FfSampleResponseHttp
object as HTTP response, not String, just add contentType = 'application/json'
header before sending the response for the HTTP and MappingJackson2HttpMessageConverter
will do the stuff for you - your object will be converted to JSON and with correct contentType
header.
From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp"
and MappingJackson2HttpMessageConverter
should do the stuff for you again.
Of course you should remove <json-to-object-transformer>
from you message flow after <int-http:outbound-gateway>
.
Deleting node_modules and reinstalling it fixed the error(or at least gave me more specific ones)
How about something like
=LEFT(A1,SEARCH(" ",A1)-1)
or
=LEFT(A1,SEARCH("<b>",A1)-1)
Have a look at MS Excel: Search Function and Excel 2007 LEFT Function
Per Arvand:
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select Open declaration in layout/simple_list_item_1.xml. It'll direct you to the contents of the XML.
From there, if you then hover over the resulting simple_list_item_1.xml tab in the Editor, you'll see the file is located at C:\Data\applications\Android\android-sdk\platforms\android-19\data\res\layout\simple_list_item_1.xml (or equivalent location for your installation).
I use a pretty hack-ish solution for this in one of my recent applications that works for my purposes, and I find it quicker than writing custom hover settings functions in vanilla js (though, I recognize, maybe not a best practice in most environments..) So, in case you're still interested, here goes.
I create a parent element just for the sake of holding the inline javascript styles, then a child with a className or id that my css stylesheet will latch onto and write the hover style in my dedicated css file. This works because the more granular child element receives the inline js styles via inheritance, but has its hover styles overridden by the css file.
So basically, my actual css file exists for the sole purpose of holding hover effects, nothing else. This makes it pretty concise and easy to manage, and allows me to do the heavy-lifting in my in-line React component styles.
Here's an example:
const styles = {_x000D_
container: {_x000D_
height: '3em',_x000D_
backgroundColor: 'white',_x000D_
display: 'flex',_x000D_
flexDirection: 'row',_x000D_
alignItems: 'stretch',_x000D_
justifyContent: 'flex-start',_x000D_
borderBottom: '1px solid gainsboro',_x000D_
},_x000D_
parent: {_x000D_
display: 'flex',_x000D_
flex: 1,_x000D_
flexDirection: 'row',_x000D_
alignItems: 'stretch',_x000D_
justifyContent: 'flex-start',_x000D_
color: 'darkgrey',_x000D_
},_x000D_
child: {_x000D_
width: '6em',_x000D_
textAlign: 'center',_x000D_
verticalAlign: 'middle',_x000D_
lineHeight: '3em',_x000D_
},_x000D_
};_x000D_
_x000D_
var NavBar = (props) => {_x000D_
const menuOptions = ['home', 'blog', 'projects', 'about'];_x000D_
_x000D_
return (_x000D_
<div style={styles.container}>_x000D_
<div style={styles.parent}>_x000D_
{menuOptions.map((page) => <div className={'navBarOption'} style={styles.child} key={page}>{page}</div> )}_x000D_
</div>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
_x000D_
ReactDOM.render(_x000D_
<NavBar/>,_x000D_
document.getElementById('app')_x000D_
);
_x000D_
.navBarOption:hover {_x000D_
color: black;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id="app"></div>
_x000D_
Notice that the "child" inline style does not have a "color" property set. If it did, this would not work because the inline style would take precedence over my stylesheet.
You can do it manually with the next command:
find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf
This will remove all *.pyc files and __pycache__ directories recursively in the current directory.
On IE7, IE8, and IE9 just go to Settings->Internet Options->Security->Custom Level and change security settings under "Miscellaneous" set "Access data sources across domains" to Enable.
For me i made the fallowing as a test.
string_1="abcd"
def test(string_1):
i = 0
p = ""
x = len(string_1)
while i < x:
y = (string_1)[i]
i=i+1
s = chr(ord(y) + 1)
p=p+s
print(p)
test(string_1)
I found that the parser would complain if I used the
entity in my page. After a little research, I learned that if I added a DOCTYPE declaration to the beginning of the page, the entity was allowed. I use this DOCTYPE declaration:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
A side effect of this is that the resulting code (as seen by using the "view source" feature of a web browser) doesn't actually contain the
entity. It instead includes the actual characters that represent a nonbreaking space. Although it works, it's not really what I want. I'm still looking for a way to make the parser not replace the entity with the character.
More information here: http://java.net/jira/browse/JAVASERVERFACES-1576
Here are my observation, firstly you need to include the header math.h
as sqrt()
function declared in math.h
header file. For e.g
#include <math.h>
secondly, if you read manual page of sqrt you will notice this line Link with -lm.
#include <math.h> /* header file you need to include */
double sqrt(double x); /* prototype of sqrt() function */
Link with -lm. /* Library linking instruction */
But application still says undefined reference to sqrt. Do you see any problem here?
Compiler error is correct as you haven't linked your program with library lm
& linker is unable to find reference of sqrt()
, you need to link it explicitly. For e.g
gcc -Wall -Wextra -Werror -pedantic test.c -lm
You can try:
public function index()
{
return View::make('pages/index', array('title' => 'Home page'));
}
Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.
Check the answer -> Here
And here is an example:
Converter.bat
::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &@echo off
rem^ &call :'sub
rem^ &exit /b
:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b
'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester
This is the commandline for removing plugins in Cordova
cordova plugin remove <pluginid>
For example I ran cordova plugin
and got a list of plugins then I used the id for the plugin to uninstall
cordova plugin remove com.monday.contact-chooser
You can get help in the commandline by typing
cordova help <command>
I found a better way of doing it so you can get a input from a txtbox or have something be generated in that text box and be able to click a button to do it.!
import java.awt.datatransfer.*;
import java.awt.Toolkit;
private void /* Action performed when the copy to clipboard button is clicked */ {
String ctc = txtCommand.getText().toString();
StringSelection stringSelection = new StringSelection(ctc);
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);
}
// txtCommand is the variable of a text box
Here's what I use:
#ifdef _WIN32 // note the underscore: without it, it's not msdn official!
// Windows (x64 and x86)
#elif __unix__ // all unices, not all compilers
// Unix
#elif __linux__
// linux
#elif __APPLE__
// Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
#endif
EDIT: Although the above might work for the basics, remember to verify what macro you want to check for by looking at the Boost.Predef reference pages. Or just use Boost.Predef directly.
Android makes it easy.
public void setTabTextColors(int normalColor, int selectedColor) {
setTabTextColors(createColorStateList(normalColor, selectedColor));
}
So, we just say
mycooltablayout.setTabTextColors(Color.parseColor("#1464f4"), Color.parseColor("#880088"));
That will give us a blue normal color and purple selected color.
Now we set the height
public void setSelectedTabIndicatorHeight(int height) {
mTabStrip.setSelectedIndicatorHeight(height);
}
And for height we say
mycooltablayout.setSelectedIndicatorHeight(6);
I ran into this problem on the Raspberry Pi. After trying everything but a reinstall, on a whim, I deleted /var/run/apache2/apache2.pid. I restarted Apache and everything worked. Not sure how to explain that.
This API gives you the current time and several formats in JSON - https://market.mashape.com/parsify/format#time. Here's a sample response:
{
"time": {
"daysInMonth": 31,
"millisecond": 283,
"second": 42,
"minute": 55,
"hour": 1,
"date": 6,
"day": 3,
"week": 10,
"month": 2,
"year": 2013,
"zone": "+0000"
},
"formatted": {
"weekday": "Wednesday",
"month": "March",
"ago": "a few seconds",
"calendar": "Today at 1:55 AM",
"generic": "2013-03-06T01:55:42+00:00",
"time": "1:55 AM",
"short": "03/06/2013",
"slim": "3/6/2013",
"hand": "Mar 6 2013",
"handTime": "Mar 6 2013 1:55 AM",
"longhand": "March 6 2013",
"longhandTime": "March 6 2013 1:55 AM",
"full": "Wednesday, March 6 2013 1:55 AM",
"fullSlim": "Wed, Mar 6 2013 1:55 AM"
},
"array": [
2013,
2,
6,
1,
55,
42,
283
],
"offset": 1362534942283,
"unix": 1362534942,
"utc": "2013-03-06T01:55:42.283Z",
"valid": true,
"integer": false,
"zone": 0
}
I had to go a step forward because my file names were not the same as my nav bar titles. i.e. my first nav bar link was HOME but the file name is index..
So just grab the pathname and match it.
Obviously this is a crude example and could be more efficient but it is highly custom need.
var loc_path = location.pathname;
$('li.active').removeClass('active');
if(loc_path.includes('index')){
$('li :eq(0)').addClass('active');
}else if(loc_path.includes('blog')){
$('li :eq(2)').addClass('active');
}else if(loc_path.includes('news')){
$('li :eq(3)').addClass('active');
}else if(loc_path.includes('house')){
$('li :eq(4)').addClass('active');
}
By default ASPNetUserIds are 128 char strings and performance is just fine.
If the key HAS to be unique in the table it should be the Key. Here's why;
primary string key = Correct DB relationships, 1 string key(The primary), and 1 string Index(The Primary).
The other option is a typical int Key, but if the string HAS to be unique you'll still probably need to add an index because of non-stop queries to validate or check that its unique.
So using an int identity key = Incorrect DB Relationships, 1 int key(Primary), 1 int index(Primary), Probably a unique string Index, and manually having to validate the same string doesn't exist(something like a sql check maybe).
To get better performance using an int over a string for the primary key, when the string HAS to be unique, it would have to be a very odd situation. I've always preferred to use string keys. And as a good rule of thumb, don't denormalize a database until you NEED to.
Here is a good article from the MDC which explains the problems (and solutions) to form autocompletion. Microsoft has published something similar here, as well.
To be honest, if this is something important to your users, 'breaking' standards in this way seems appropriate. For example, Amazon uses the 'autocomplete' attribute quite a bit, and it seems to work well.
If you want to remove the warning entirely, you can use JavaScript to apply the attribute to browsers that support it (IE and Firefox are the important browsers) using someForm.setAttribute( "autocomplete", "off" ); someFormElm.setAttribute( "autocomplete", "off" );
Finally, if your site is using HTTPS, IE automatically turns off autocompletion (as do some other browsers, as far as I know).
Update
As this answer still gets quite a few upvotes, I just wanted to point out that in HTML5, you can use the 'autocomplete' attribute on your form element. See the documentation on W3C for it.
If you are using XAMPP as your server, you'll find a logs directory as a child of the XAMPP directory. If you have not tried XAMPP, which runs on any system (Windows, Mac OS & Linux) find more here: http://www.apachefriends.org/en/xampp.html
I don't know if this applies to python as well, but I think it depends on the operating system that you are running.
On Linux for example, output to terminal flushes the buffer on a newline, whereas for output to files it only flushes when the buffer is full (by default). This is because it is more efficient to flush the buffer fewer times, and the user is less likely to notice if the output is not flushed on a newline in a file.
You might be able to auto-flush the output if that is what you need.
EDIT: I think you would auto-flush in python this way (based from here)
#0 means there is no buffer, so all output
#will be auto-flushed
fsock = open('out.log', 'w', 0)
sys.stdout = fsock
#do whatever
fsock.close()
How about:
<asp:HtmlIframe ID="yourIframe" runat="server" />
Is supported since .Net Framework 4.5
If you have Problems using this control, you might take a look here.
If you want the fastest way for numpy arrays, use numba, which if you use conda should be already installed
The code will be fast because it will be compiled by numba
import numba
@numba.jit
def issorted(vec, ascending=True):
if len(vec) < 2:
return True
if ascending:
for i in range(1, len(vec)):
if vec[i-1] > vec[i]:
return False
return True
else:
for i in range(1, len(vec)):
if vec[i-1] < vec[i]:
return False
return True
and then:
>>> issorted(array([4,9,100]))
>>> True
For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'});
only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)
It could just be something that runs once the first time you initialize collapse with those parameters.
You will have more luck using the show
and hide
methods.
Here is an example:
$(function() {
var $active = true;
$('.panel-title > a').click(function(e) {
e.preventDefault();
});
$('.collapse-init').on('click', function() {
if(!$active) {
$active = true;
$('.panel-title > a').attr('data-toggle', 'collapse');
$('.panel-collapse').collapse('hide');
$(this).html('Click to disable accordion behavior');
} else {
$active = false;
$('.panel-collapse').collapse('show');
$('.panel-title > a').attr('data-toggle','');
$(this).html('Click to enable accordion behavior');
}
});
});
Update
Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.
I don't understand what's going on or why the show
seemed to be toggling in some places.
But After messing around for a while.. Finally came with the following solution:
$(function() {
var transition = false;
var $active = true;
$('.panel-title > a').click(function(e) {
e.preventDefault();
});
$('#accordion').on('show.bs.collapse',function(){
if($active){
$('#accordion .in').collapse('hide');
}
});
$('#accordion').on('hidden.bs.collapse',function(){
if(transition){
transition = false;
$('.panel-collapse').collapse('show');
}
});
$('.collapse-init').on('click', function() {
$('.collapse-init').prop('disabled','true');
if(!$active) {
$active = true;
$('.panel-title > a').attr('data-toggle', 'collapse');
$('.panel-collapse').collapse('hide');
$(this).html('Click to disable accordion behavior');
} else {
$active = false;
if($('.panel-collapse.in').length){
transition = true;
$('.panel-collapse.in').collapse('hide');
}
else{
$('.panel-collapse').collapse('show');
}
$('.panel-title > a').attr('data-toggle','');
$(this).html('Click to enable accordion behavior');
}
setTimeout(function(){
$('.collapse-init').prop('disabled','');
},800);
});
});
Obviously you know how this defeats the whole purpose of a SecureString, but I'll restate it anyway.
If you want a one-liner, try this: (.NET 4 and above only)
string password = new System.Net.NetworkCredential(string.Empty, securePassword).Password;
Where securePassword is a SecureString.
Use
var arrayNames = (from DataColumn x in dt.Columns
select x.ColumnName).ToArray();
you should just remove the 'boolean' in front of your boolean variable.
Do it like this:
boolean isLeapYear = true;
System.out.println(isLeapYear);
or
boolean isLeapYear = true;
System.out.println(isLeapYear?"yes":"no");
The other thing ist hat you seems not to call the method at all! The method and the variable are both not static, thus, you have to create an instance of your class first. Or you just make both static and than simply call your method directly from your maim method.
Thus there are a couple of mistakes in the code. May be you shoud start with a more simple example and than rework it until it does what you want.
Example:
import java.util.Scanner;
public class booleanfun {
static boolean isLeapYear;
public static void main(String[] args)
{
System.out.println("Enter a year to determine if it is a leap year or not: ");
Scanner kboard = new Scanner(System.in);
int year = kboard.nextInt();
isLeapYear(year);
}
public static boolean isLeapYear(int year) {
if (year % 4 != 0)
isLeapYear = false;
else if ((year % 4 == 0) && (year % 100 == 0))
isLeapYear = false;
else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0))
isLeapYear = true;
else
isLeapYear = false;
System.out.println(isLeapYear);
return isLeapYear;
}
}
You can't find a consistent reference because it seems to go by at least six different names!
I would like to add my solution to get reliable statistics on how many real users visit my site with javascript disabled over the total users. The check is done one time only per session with these benefits:
My code uses PHP, mysql and jquery with ajax but could be adapted to other languanges:
Create a table in your DB like this one:
CREATE TABLE IF NOT EXISTS `log_JS` (
`logJS_id` int(11) NOT NULL AUTO_INCREMENT,
`data_ins` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`session_id` varchar(50) NOT NULL,
`JS_ON` tinyint(1) NOT NULL DEFAULT '0',
`agent` varchar(255) DEFAULT NULL,
PRIMARY KEY (`logJS_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Add this to every page after using session_start() or equivalent (jquery required):
<? if (!isset($_SESSION["JSTest"]))
{
mysql_query("INSERT INTO log_JS (session_id, agent) VALUES ('" . mysql_real_escape_string(session_id()) . "', '" . mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']). "')");
$_SESSION["JSTest"] = 1; // One time per session
?>
<script type="text/javascript">
$(document).ready(function() { $.get('JSOK.php'); });
</script>
<?
}
?>
Create the page JSOK.php like this:
<?
include_once("[DB connection file].php");
mysql_query("UPDATE log_JS SET JS_ON = 1 WHERE session_id = '" . mysql_real_escape_string(session_id()) . "'");
You can use rowspan="n"
on a td element to make it span n
rows, and colspan="m"
on a td element to make it span m
columns.
Looks like your first td needs a rowspan="2"
and the next td needs a colspan="4"
.
I believe that using a combination of interfaces and base classes could work for you. It will enforce behavioral requirements at compile time (rq_ post "below" refers to a post above, which is not this one).
The interface sets the behavioral API that isn't met by the base class. You will not be able to set base class methods to call on methods defined in the interface (because you will not be able to implement that interface in the base class without having to define those behaviors). Maybe someone can come up with a safe trick to allow calling of the interface methods in the parent.
You have to remember to extend and implement in the class you will instantiate. It satisfies concerns about defining runtime-fail code. You also won't even be able to call the methods that would puke if you haven't implemented the interface (such as if you try to instantiate the Animal class). I tried having the interface extend the BaseAnimal below, but it hid the constructor and the 'name' field of BaseAnimal from Snake. If I had been able to do that, the use of a module and exports could have prevented accidental direct instantiation of the BaseAnimal class.
Paste this in here to see if it works for you: http://www.typescriptlang.org/Playground/
// The behavioral interface also needs to extend base for substitutability
interface AbstractAnimal extends BaseAnimal {
// encapsulates animal behaviors that must be implemented
makeSound(input : string): string;
}
class BaseAnimal {
constructor(public name) { }
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
// If concrete class doesn't extend both, it cannot use super methods.
class Snake extends BaseAnimal implements AbstractAnimal {
constructor(name) { super(name); }
makeSound(input : string): string {
var utterance = "sssss"+input;
alert(utterance);
return utterance;
}
move() {
alert("Slithering...");
super.move(5);
}
}
var longMover = new Snake("windy man");
longMover.makeSound("...am I nothing?");
longMover.move();
var fulture = new BaseAnimal("bob fossil");
// compile error on makeSound() because it is not defined.
// fulture.makeSound("you know, like a...")
fulture.move(1);
I came across FristvanCampen's answer as linked below. He says abstract classes are an anti-pattern, and suggests that one instantiate base 'abstract' classes using an injected instance of an implementing class. This is fair, but there are counter arguments made. Read for yourself: https://typescript.codeplex.com/discussions/449920
Part 2: I had another case where I wanted an abstract class, but I was prevented from using my solution above, because the defined methods in the "abstract class" needed to refer to the methods defined in the matching interface. So, I tool FristvanCampen's advice, sort of. I have the incomplete "abstract" class, with method implementations. I have the interface with the unimplemented methods; this interface extends the "abstract" class. I then have a class that extends the first and implements the second (it must extend both because the super constructor is inaccessible otherwise). See the (non-runnable) sample below:
export class OntologyConceptFilter extends FilterWidget.FilterWidget<ConceptGraph.Node, ConceptGraph.Link> implements FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link> {
subMenuTitle = "Ontologies Rendered"; // overload or overshadow?
constructor(
public conceptGraph: ConceptGraph.ConceptGraph,
graphView: PathToRoot.ConceptPathsToRoot,
implementation: FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link>
){
super(graphView);
this.implementation = this;
}
}
and
export class FilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> {
public implementation: IFilterWidget<N, L>
filterContainer: JQuery;
public subMenuTitle : string; // Given value in children
constructor(
public graphView: GraphView.GraphView<N, L>
){
}
doStuff(node: N){
this.implementation.generateStuff(thing);
}
}
export interface IFilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> extends FilterWidget<N, L> {
generateStuff(node: N): string;
}
ERRORLEVEL
will contain the return code of the last command. Sadly you can only check >=
for it.
Note specifically this line in the MSDN documentation for the If
statement:
errorlevel Number
Specifies a true condition only if the previous program run by Cmd.exe returned an exit code equal to or greater than Number.
So to check for 0 you need to think outside the box:
IF ERRORLEVEL 1 GOTO errorHandling
REM no error here, errolevel == 0
:errorHandling
Or if you want to code error handling first:
IF NOT ERRORLEVEL 1 GOTO no_error
REM errorhandling, errorlevel >= 1
:no_error
Further information about BAT programming: http://www.ericphelps.com/batch/
Or more specific for Windows cmd
: MSDN using batch files
REQUEST:
$.ajax({
url: "http://localhost:8079/students/add/",
type: "POST",
crossDomain: true,
data: JSON.stringify(somejson),
dataType: "json",
success: function (response) {
var resp = JSON.parse(response)
alert(resp.status);
},
error: function (xhr, status) {
alert("error");
}
});
RESPONSE:
response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")
return response
You could also try putting your code in the Activated event of the form, if you want it to occur, just when the form is activated. You would need to put in a boolean "has executed" check though if it is only supposed to run on the first activation.
If you're on Windows:
Go to your php.ini file and remove the ;
mark from the beginning of the following line:
;extension=php_curl.dll
After you have saved the file you must restart your HTTP server software (e.g. Apache) before this can take effect.
For Ubuntu 13.0 and above, simply use the debundled package. In a terminal type the following to install it and do not forgot to restart server.
sudo apt-get install php-curl
Or if you're using the old PHP5
sudo apt-get install php5-curl
or
sudo apt-get install php5.6-curl
Then restart apache to activate the package with
sudo service apache2 restart
You can rename the directory using the file system. Then you can do git rm <old directory>
and git add <new directory>
(Help page). Then you can commit and push.
Git will detect that the contents are the same and that it's just a rename operation, and it'll appear as a rename entry in the history. You can check that this is the case before the commit using git status
Your problem is well explained in this document by Apple. Example code on this page (at Listing 4-1
) does exactly what you need, it will scroll your view only when the current editing should be under the keyboard. You only need to put your needed controls in a scrollViiew.
The only problem is that this is Objective-C and I think you need it in Swift..so..here it is:
Declare a variable
var activeField: UITextField?
then add these methods
func registerForKeyboardNotifications()
{
//Adding notifies on keyboard appearing
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}
func deregisterFromKeyboardNotifications()
{
//Removing notifies on keyboard appearing
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWasShown(notification: NSNotification)
{
//Need to calculate keyboard exact size due to Apple suggestions
self.scrollView.scrollEnabled = true
var info : NSDictionary = notification.userInfo!
var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var aRect : CGRect = self.view.frame
aRect.size.height -= keyboardSize!.height
if let activeFieldPresent = activeField
{
if (!CGRectContainsPoint(aRect, activeField!.frame.origin))
{
self.scrollView.scrollRectToVisible(activeField!.frame, animated: true)
}
}
}
func keyboardWillBeHidden(notification: NSNotification)
{
//Once keyboard disappears, restore original positions
var info : NSDictionary = notification.userInfo!
var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
self.view.endEditing(true)
self.scrollView.scrollEnabled = false
}
func textFieldDidBeginEditing(textField: UITextField!)
{
activeField = textField
}
func textFieldDidEndEditing(textField: UITextField!)
{
activeField = nil
}
Be sure to declare your ViewController as UITextFieldDelegate
and set correct delegates in your initialization methods:
ex:
self.you_text_field.delegate = self
And remember to call registerForKeyboardNotifications
on viewInit and deregisterFromKeyboardNotifications
on exit.
func registerForKeyboardNotifications(){
//Adding notifies on keyboard appearing
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}
func deregisterFromKeyboardNotifications(){
//Removing notifies on keyboard appearing
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWasShown(notification: NSNotification){
//Need to calculate keyboard exact size due to Apple suggestions
self.scrollView.isScrollEnabled = true
var info = notification.userInfo!
let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize!.height, right: 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var aRect : CGRect = self.view.frame
aRect.size.height -= keyboardSize!.height
if let activeField = self.activeField {
if (!aRect.contains(activeField.frame.origin)){
self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
}
}
}
@objc func keyboardWillBeHidden(notification: NSNotification){
//Once keyboard disappears, restore original positions
var info = notification.userInfo!
let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: -keyboardSize!.height, right: 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
self.view.endEditing(true)
self.scrollView.isScrollEnabled = false
}
func textFieldDidBeginEditing(_ textField: UITextField){
activeField = textField
}
func textFieldDidEndEditing(_ textField: UITextField){
activeField = nil
}
You could also do it with a Func like this
@{
var getStyle = new Func<int, int, string>((width, margin) => string.Format("width: {0}px; margin: {1}px;", width, margin));
}
<div style="@getStyle(50, 2)"></div>
Yes, it's indeed a sad fact that keytool has no functionality to import a private key.
For the record, at the end I went with the solution described here
@CommonsWare's answer doesn't not actually work. I found that this is working properly :
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-33.88,151.21), 15));
I’d use tr
:
tr < file-with-nulls -d '\000' > file-without-nulls
If you are wondering if input redirection in the middle of the command arguments works, it does. Most shells will recognize and deal with I/O redirection (<
, >
, …) anywhere in the command line, actually.
I am not going to give you the whole answer (I don't think you're looking for the parsing and writing to file part anyway), but a pivotal hint should suffice: use python's set()
function, and then sorted()
or .sort()
coupled with .reverse()
:
>>> a=sorted(set([10,60,30,10,50,20,60,50,60,10,30]))
>>> a
[10, 20, 30, 50, 60]
>>> a.reverse()
>>> a
[60, 50, 30, 20, 10]
Try either CopyOnWriteArrayList or CopyOnWriteArraySet depending on what you are trying to do.
Another way to work this around is to add this into your module package.json
scripts section
"preinstall": "npm install {Packages You depend on}"
what this will does is, it will install all packages needed by the module and you won't get that error.
Assuming you use Python 2.7 (not 3):
print "I have", card.price
(as mentioned above).
print "I have %s" % card.price
(using string formatting)
print " ".join(map(str, ["I have", card.price]))
(by joining lists)
There are a lot of ways to do the same, actually. I would prefer the second one.
I found a tool "webchk” written in Python. Returns a status code for a list of urls. https://pypi.org/project/webchk/
Output looks like this:
? webchk -i ./dxieu.txt | grep '200'
http://salesforce-case-status.dxi.eu/login ... 200 OK (0.108)
https://support.dxi.eu/hc/en-gb ... 200 OK (0.389)
https://support.dxi.eu/hc/en-gb ... 200 OK (0.401)
Hope that helps!
Through my own experience trying to run some java code from within python i a manner similar to how python code runs within java code in python, I was unable to a find a straight forward methodology.
My solution to my problem was by running this java code as beanshell scripts by calling the beanshell interpreter as a shell commnad from within my python code after editing the java code in a temporary file with the appropriate packages and variables.
If what I am talking about is helpful in any manner, I am glad to help you sharing more details of my solutions.
You can try using System.arraycopy()
int[] src = new int[]{1,2,3,4,5};
int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );
But, probably better to use clone() in most cases:
int[] src = ...
int[] dest = src.clone();