To add a class to a div that is generated via the HtmlGenericControl
way you can use:
div1.Attributes.Add("class", "classname");
If you are using the Panel
option, it would be:
panel1.CssClass = "classname";
There are a number of people with this difficulty. The prevailing answer is that you can't protect content from editing while allowing unhindered sorting. Your options are:
1) Allow editing and sorting :(
2) Apply protection and create buttons with code to sort using VBA. There are other posts explaining how to do this. I think there are two methods, either (1) get the code to unprotect the sheet, apply the sort, then re-protect the sheet, or (2) have the sheet protected using UserInterfaceOnly:=True
.
3) Lorie's answer which does not allow users to select cells (https://stackoverflow.com/a/15390698/269953)
4) One solution that I haven't seen discussed is using VBA to provide some basic protection. For example, detect and revert changes using Worksheet_Change
. It's far from an ideal solution however.
5) You could keep the sheet protected when the user is selecting the data and unprotected when the user has the header is selected. This leaves countless ways the users could mess up the data while also causing some usability issues, but at least reduces the odds of pesky co-workers thoughtlessly making unwanted changes.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If (Target.row = HEADER_ROW) Then
wsMainTable.Unprotect Password:=PROTECTION_PASSWORD
Else
wsMainTable.Protect Password:=PROTECTION_PASSWORD, UserInterfaceOnly:=True
End If
End Sub
I would choose the second as you don't have to do a copy of the memory and the Iterator works faster. So you save memory and time.
$('#user_input, #pass_input, #v_pass_input, #email').bind('keyup', function() {
if(allFilled()) $('#register').removeAttr('disabled');
});
function allFilled() {
var filled = true;
$('body input').each(function() {
if($(this).val() == '') filled = false;
});
return filled;
}
JSFiddle with your code, works :)
from threading import Thread
threads=list()
for requestURI in requests:
t = Thread(target=self.openURL, args=(requestURI,))
t.start()
threads.append(t)
for thread in threads:
thread.join()
...
def openURL(self, requestURI):
o = urllib2.urlopen(requestURI, timeout = 600)
o...
If you are getting an error saying something about deprecated functions, try doing #define _CRT_SECURE_NO_WARNINGS
or #define _CRT_SECURE_NO_DEPRECATE
. These should fix it. You can also use Microsoft's "secure" functions, if you want.
Add another div
or img
to your main div
and blur that instead. jsfiddle
.blur {
background:url('http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465') no-repeat center;
background-size:cover;
-webkit-filter: blur(13px);
-moz-filter: blur(13px);
-o-filter: blur(13px);
-ms-filter: blur(13px);
filter: blur(13px);
position:absolute;
width:100%;
height:100%;
}
You would find the array keys with "${!foo[@]}"
(reference), so:
for i in "${!foo[@]}"; do
printf "%s\t%s\n" "$i" "${foo[$i]}"
done
Which means that indices will be in $i
while the elements themselves have to be accessed via ${foo[$i]}
This works in MSSQL and MySQL:
SELECT *
FROM Village
WHERE CastleType LIKE '%foo%';
You can optionally overload the = operator for the variable and can put the breakpoint inside the overloaded function on specific condition.
for eg. you may take
driver.get('https://www.naukri.com/')
since, it is a current window ,we can name it
main_page = driver.current_window_handle
if there are atleast 1 window popup except the current window,you may try this method and put if condition in break statement by hit n trial for the index
for handle in driver.window_handles:
if handle != main_page:
print(handle)
login_page = handle
break
driver.switch_to.window(login_page)
Now ,whatever the credentials you have to apply,provide after it is loggen in. Window will disappear, but you have to come to main page window and you are done
driver.switch_to.window(main_page)
sleep(10)
I was struggling with Outlook and Office365. Surprisingly the thing that seemed to work was:
<table align='center' style='text-align:center'>
<tr>
<td align='center' style='text-align:center'>
<!-- AMAZING CONTENT! -->
</td>
</tr>
</table>
I only listed some of the key things that resolved my Microsoft email issues.
Might I add that building an email that looks nice on all emails is a pain. This website was super nice for testing: https://putsmail.com/
It allows you to list all the emails you'd like to send your test email to. You can paste your code right into the window, edit, send, and resend. It helped me a ton.
Here's a batch file that works for Windows - assumes DiffMerge installed in default location, handles x64, handles forward to backslash replacement as necessary and has ability to install itself. Should be easy to replace DiffMerge with your favourite diff program.
To install:
gitvdiff --install
gitvdiff.bat:
@echo off
REM ---- Install? ----
REM To install, run gitvdiff --install
if %1==--install goto install
REM ---- Find DiffMerge ----
if DEFINED ProgramFiles^(x86^) (
Set DIFF="%ProgramFiles(x86)%\SourceGear\DiffMerge\DiffMerge.exe"
) else (
Set DIFF="%ProgramFiles%\SourceGear\DiffMerge\DiffMerge.exe"
)
REM ---- Switch forward slashes to back slashes ----
set oldW=%2
set oldW=%oldW:/=\%
set newW=%5
set newW=%newW:/=\%
REM ---- Launch DiffMerge ----
%DIFF% /title1="Old Version" %oldW% /title2="New Version" %newW%
goto :EOF
REM ---- Install ----
:install
set selfL=%~dpnx0
set selfL=%selfL:\=/%
@echo on
git config --global diff.external %selfL%
@echo off
:EOF
One pragmatic tip: you can search easily for the static_cast keyword in your source code if you plan to tidy up the project.
THIS SOLUTION WORKS
You do not need to map manually even if you dont have a PK. You just need to tell the EF that one of your columns is index and index column is not nullable.
To do this you can add a row number to your view with isNull function like the following
select
ISNULL(ROW_NUMBER() OVER (ORDER BY xxx), - 9999) AS id
from a
ISNULL(id, number)
is the key point here because it tells the EF that this column can be primary key
Alternatively you could assign the form actiob on the fly...might not be the best solution, but sure does relieve the server-side logic...
<form name="frm" method="post">
<input type="submit" value="One" onclick="javascript:this.form.action='1.htm'" />
<input type="submit" value="Two" onclick="javascript:this.form.action='2.htm'" />
</form>
With the upcoming Xcode 7 it's now possible to install apps on your devices without an apple developer license, so now it is possible to skip the app store and you don't have to jailbreak your device.
Now everyone can get their app on their Apple device.
Xcode 7 and Swift now make it easier for everyone to build apps and run them directly on their Apple devices. Simply sign in with your Apple ID, and turn your idea into an app that you can touch on your iPad, iPhone, or Apple Watch. Download Xcode 7 beta and try it yourself today. Program membership is not required.
Quoted from: https://developer.apple.com/xcode/
Update:
XCode 7 is now released:
Free On-Device Development Now everyone can run and test their own app on a device—for free. You can run and debug your own creations on a Mac, iPhone, iPad, iPod touch, or Apple Watch without any fees, and no programs to join. All you need to do is enter your free Apple ID into Xcode. You can even use the same Apple ID you already use for the App Store or iTunes. Once you’ve perfected your app the Apple Developer Program can help you get it on the App Store.
See Launching Your App on Devices for detailed information about installing and running on devices.
I think max value of int(11) is 4294967295
The logic is simple. setOnClickListener
belongs to step 2.
OnClickListener
* like it's done in that example and override the onClick
-method.OnClickListener
to that button using btn.setOnClickListener(myOnClickListener);
in your fragments/activities onCreate
-method.onClick
function of the assigned OnClickListener
is called.*If you import android.view.View;
you use View.OnClickListener
. If you import android.view.View.*;
or import android.view.View.OnClickListener;
you use OnClickListener
as far as I get it.
Another way is to let you activity/fragment inherit from OnClickListener
. This way you assign your fragment/activity as the listener for your button and implement onClick
as a member-function.
To use the window
object is not a good idea. As I see in comments,
'use strict';
function showMessage() {
window.say_hello = 'hello!';
}
console.log(say_hello);
This will throw an error to use the say_hello
variable we need to first call the showMessage function
.
Dispose simply gets called when you leave the scope of using. The intention of "using" is to give developers a guaranteed way to make sure that resources get disposed.
From MSDN:
A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.
Finally after comparing all solution, I think starting from build.gradle
file can be convenient.
Gradle distribution has samples
folder with a lot of examples, and there is gradle init --type basic
comand see Chapter 47. Build Init Plugin. But they all needs some editing.
You can use template below as well, then run gradle initSourceFolders eclipse
/*
* Nodeclipse/Enide build.gradle template for basic Java project
* https://github.com/Nodeclipse/nodeclipse-1/blob/master/org.nodeclipse.enide.editors.gradle/docs/java/basic/build.gradle
* Initially asked on
* http://stackoverflow.com/questions/14017364/how-to-create-java-gradle-project
* Usage
* 1. create folder (or general Eclipse project) and put this file inside
* 2. run `gradle initSourceFolders eclipse` or `gradle initSourceFolders idea`
* @author Paul Verest;
* based on `gradle init --type basic`, that does not create source folders
*/
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
task initSourceFolders { // add << before { to prevent executing during configuration phase
sourceSets*.java.srcDirs*.each { it.mkdirs() }
sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}
task wrapper(type: Wrapper) {
gradleVersion = '1.11'
}
// In this section you declare where to find the dependencies of your project
repositories {
// Use Maven Central for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
mavenCentral()
}
// In this section you declare the dependencies for your production and test code
dependencies {
//compile fileTree(dir: 'libs', include: '*.jar')
// The production code uses the SLF4J logging API at compile time
//compile 'org.slf4j:slf4j-api:1.7.5'
// Declare the dependency for your favourite test framework you want to use in your tests.
// TestNG is also supported by the Gradle Test task. Just change the
// testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
// 'test.useTestNG()' to your build script.
testCompile "junit:junit:4.11"
}
The result is like below.
That can be used without any Gradle plugin for Eclipse,
or with (Enide) Gradle for Eclipse, Jetty, Android alternative to Gradle Integration for Eclipse
Following is the json format instagram is using
{
"meta": {
"error_type": "OAuthException",
"code": 400,
"error_message": "..."
}
"data": {
...
},
"pagination": {
"next_url": "...",
"next_max_id": "13872296"
}
}
Using Math.Round()
:
int percentComplete = (int)Math.Round((double)(100 * complete) / total);
or manually rounding:
int percentComplete = (int)(0.5f + ((100f * complete) / total));
My experience:
var text = $('#myInputField');
var myObj = {title: 'Some title', content: text};
$.post(myUrl, myObj, callback);
The problem is that I forgot to add .val() to the end of $('#myInputField'); this action makes me waste time trying to figure out what was wrong, causing Illegal Invocation Error, since $('#myInputField') was in a different file than that system pointed out incorrect code. Hope this answer help fellows in the same mistake to avoid to loose time.
You can add the SVG as background-image
of an empty :after
or :before
.
Here you go:
.anchor:before {
display: block;
content: ' ';
background-image: url('../images/anchor.svg');
background-size: 28px 28px;
height: 28px;
width: 28px;
}
With correct quoting (this can be tricky sometimes):
start "" /D "C:\Program Files\ProgramToLaunch" "cmd.exe" "/c call ""C:\Program Files\ProgramToLaunch\programname.bat"""
1st arg - Title (empty in this case)
2nd arg - /D specifies starting directory, can be ommited if want the current working dir (such as "%~dp0")
3rd arg - command to launch, "cmd.exe"
4th arg - arguments to command, with doubled up quotes for the arguments inside it (this is how you escape quotes within quotes in batch)
The top answer of the question Anders Lindahl refers to an xsd file.
Personally I found this xsd file also very useful (I don't remember how I found that one). It looks a bit less intimidating, and as far as I used it, all the elements and attributes seem to be recognized by Jenkins (v1.451)
One thing though: when adding multiple <failure ...
elements, only one was retained in Jenkins. When creating the xml file, I now concatenate all the failures in one.
Update 2016-11 The link is broken now. A better alternative is this page from cubic.org: JUnit XML reporting file format, where a nice effort has been taken to provide a sensible documented example. Example and xsd are copied below, but their page looks waay nicer.
<?xml version="1.0" encoding="UTF-8"?>
<!-- a description of the JUnit XML format and how Jenkins parses it. See also junit.xsd -->
<!-- if only a single testsuite element is present, the testsuites
element can be omitted. All attributes are optional. -->
<testsuites disabled="" <!-- total number of disabled tests from all testsuites. -->
errors="" <!-- total number of tests with error result from all testsuites. -->
failures="" <!-- total number of failed tests from all testsuites. -->
name=""
tests="" <!-- total number of successful tests from all testsuites. -->
time="" <!-- time in seconds to execute all test suites. -->
>
<!-- testsuite can appear multiple times, if contained in a testsuites element.
It can also be the root element. -->
<testsuite name="" <!-- Full (class) name of the test for non-aggregated testsuite documents.
Class name without the package for aggregated testsuites documents. Required -->
tests="" <!-- The total number of tests in the suite, required. -->
disabled="" <!-- the total number of disabled tests in the suite. optional -->
errors="" <!-- The total number of tests in the suite that errored. An errored test is one that had an unanticipated problem,
for example an unchecked throwable; or a problem with the implementation of the test. optional -->
failures="" <!-- The total number of tests in the suite that failed. A failure is a test which the code has explicitly failed
by using the mechanisms for that purpose. e.g., via an assertEquals. optional -->
hostname="" <!-- Host on which the tests were executed. 'localhost' should be used if the hostname cannot be determined. optional -->
id="" <!-- Starts at 0 for the first testsuite and is incremented by 1 for each following testsuite -->
package="" <!-- Derived from testsuite/@name in the non-aggregated documents. optional -->
skipped="" <!-- The total number of skipped tests. optional -->
time="" <!-- Time taken (in seconds) to execute the tests in the suite. optional -->
timestamp="" <!-- when the test was executed in ISO 8601 format (2014-01-21T16:17:18). Timezone may not be specified. optional -->
>
<!-- Properties (e.g., environment settings) set during test
execution. The properties element can appear 0 or once. -->
<properties>
<!-- property can appear multiple times. The name and value attributres are required. -->
<property name="" value=""/>
</properties>
<!-- testcase can appear multiple times, see /testsuites/testsuite@tests -->
<testcase name="" <!-- Name of the test method, required. -->
assertions="" <!-- number of assertions in the test case. optional -->
classname="" <!-- Full class name for the class the test method is in. required -->
status=""
time="" <!-- Time taken (in seconds) to execute the test. optional -->
>
<!-- If the test was not executed or failed, you can specify one
the skipped, error or failure elements. -->
<!-- skipped can appear 0 or once. optional -->
<skipped/>
<!-- Indicates that the test errored. An errored test is one
that had an unanticipated problem. For example an unchecked
throwable or a problem with the implementation of the
test. Contains as a text node relevant data for the error,
for example a stack trace. optional -->
<error message="" <!-- The error message. e.g., if a java exception is thrown, the return value of getMessage() -->
type="" <!-- The type of error that occured. e.g., if a java execption is thrown the full class name of the exception. -->
></error>
<!-- Indicates that the test failed. A failure is a test which
the code has explicitly failed by using the mechanisms for
that purpose. For example via an assertEquals. Contains as
a text node relevant data for the failure, e.g., a stack
trace. optional -->
<failure message="" <!-- The message specified in the assert. -->
type="" <!-- The type of the assert. -->
></failure>
<!-- Data that was written to standard out while the test was executed. optional -->
<system-out></system-out>
<!-- Data that was written to standard error while the test was executed. optional -->
<system-err></system-err>
</testcase>
<!-- Data that was written to standard out while the test suite was executed. optional -->
<system-out></system-out>
<!-- Data that was written to standard error while the test suite was executed. optional -->
<system-err></system-err>
</testsuite>
</testsuites>
<?xml version="1.0" encoding="UTF-8" ?>
<!-- from https://svn.jenkins-ci.org/trunk/hudson/dtkit/dtkit-format/dtkit-junit-model/src/main/resources/com/thalesgroup/dtkit/junit/model/xsd/junit-4.xsd -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="failure">
<xs:complexType mixed="true">
<xs:attribute name="type" type="xs:string" use="optional"/>
<xs:attribute name="message" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
<xs:element name="error">
<xs:complexType mixed="true">
<xs:attribute name="type" type="xs:string" use="optional"/>
<xs:attribute name="message" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
<xs:element name="properties">
<xs:complexType>
<xs:sequence>
<xs:element ref="property" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="property">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required"/>
<xs:attribute name="value" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
<xs:element name="skipped" type="xs:string"/>
<xs:element name="system-err" type="xs:string"/>
<xs:element name="system-out" type="xs:string"/>
<xs:element name="testcase">
<xs:complexType>
<xs:sequence>
<xs:element ref="skipped" minOccurs="0" maxOccurs="1"/>
<xs:element ref="error" minOccurs="0" maxOccurs="unbounded"/>
<xs:element ref="failure" minOccurs="0" maxOccurs="unbounded"/>
<xs:element ref="system-out" minOccurs="0" maxOccurs="unbounded"/>
<xs:element ref="system-err" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required"/>
<xs:attribute name="assertions" type="xs:string" use="optional"/>
<xs:attribute name="time" type="xs:string" use="optional"/>
<xs:attribute name="classname" type="xs:string" use="optional"/>
<xs:attribute name="status" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
<xs:element name="testsuite">
<xs:complexType>
<xs:sequence>
<xs:element ref="properties" minOccurs="0" maxOccurs="1"/>
<xs:element ref="testcase" minOccurs="0" maxOccurs="unbounded"/>
<xs:element ref="system-out" minOccurs="0" maxOccurs="1"/>
<xs:element ref="system-err" minOccurs="0" maxOccurs="1"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required"/>
<xs:attribute name="tests" type="xs:string" use="required"/>
<xs:attribute name="failures" type="xs:string" use="optional"/>
<xs:attribute name="errors" type="xs:string" use="optional"/>
<xs:attribute name="time" type="xs:string" use="optional"/>
<xs:attribute name="disabled" type="xs:string" use="optional"/>
<xs:attribute name="skipped" type="xs:string" use="optional"/>
<xs:attribute name="timestamp" type="xs:string" use="optional"/>
<xs:attribute name="hostname" type="xs:string" use="optional"/>
<xs:attribute name="id" type="xs:string" use="optional"/>
<xs:attribute name="package" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
<xs:element name="testsuites">
<xs:complexType>
<xs:sequence>
<xs:element ref="testsuite" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="optional"/>
<xs:attribute name="time" type="xs:string" use="optional"/>
<xs:attribute name="tests" type="xs:string" use="optional"/>
<xs:attribute name="failures" type="xs:string" use="optional"/>
<xs:attribute name="disabled" type="xs:string" use="optional"/>
<xs:attribute name="errors" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
</xs:schema>
I ran into this problem after I cloned a git repository to a directory, renamed the directory, then tried to run npm install
. I'm not sure what the problem was, but something was bungled. Deleting everything, re-cloning (this time with the correct directory name), and then running npm install
resolved my issue.
On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:
{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}
You can use the below effect to animate, you can change the values as per your requirements
$("#myElem").fadeIn('slow').animate({opacity: 1.0}, 1500).effect("pulsate", { times: 2 }, 800).fadeOut('slow');
There is no explicit Clone
button. Basically what you do is create an image, or snapshot of an existing EC2 instance, and then spin up a new instance using that snapshot.
First create an image from an existing EC2 instance.
Check your snapshots list to see if the process is completed. This usually takes around 20 minutes depending on how large your instance drive is.
Then, you need to create a new instance and use that image as the AMI.
\dt information_schema.
from within psql, should be fine.
Read the input continuously within the loop so that the variable line
is assigned a value other than the initial value
while ((line = br.readLine()) !=null) {
...
}
Aside: This problem has already been solved using CSV libraries such as OpenCSV. Here are examples for reading and writing CSV files
<div style="float:left;margin:0 10px 10px 0" markdown="1">
![book](/images/book01.jpg)
</div>
The attribute markdown
possibility inside Markdown.
Use position:fixed
this way your div will remain over the whole viewable area continuously ..
give your div a class overlay
and create the following rule in your CSS
.overlay{
opacity:0.8;
background-color:#ccc;
position:fixed;
width:100%;
height:100%;
top:0px;
left:0px;
z-index:1000;
}
To provide another perspective, "def" in Scala means something that will be evaluated each time when it's used, while val is something that is evaluated immediately and only once. Here, the expression def person = new Person("Kumar",12)
entails that whenever we use "person" we will get a new Person("Kumar",12)
call. Therefore it's natural that the two "person.age" are non-related.
This is the way I understand Scala(probably in a more "functional" manner). I'm not sure if
def defines a method
val defines a fixed value (which cannot be modified)
var defines a variable (which can be modified)
is really what Scala intends to mean though. I don't really like to think that way at least...
This grants root access with the same password from any machine in *.example.com
:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%.example.com'
IDENTIFIED BY 'some_characters'
WITH GRANT OPTION;
FLUSH PRIVILEGES;
If name resolution is not going to work, you may also grant access by IP or subnet:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.%'
IDENTIFIED BY 'some_characters'
WITH GRANT OPTION;
FLUSH PRIVILEGES;
For myself I use following extension functions:
fun T?.or<T>(default: T): T = if (this == null) default else this
fun T?.or<T>(compute: () -> T): T = if (this == null) compute() else this
First one will return provided default value in case object equals null. Second will evaluate expression provided in lambda in the same case.
Usage:
1) e?.getMessage().or("unknown")
2) obj?.lastMessage?.timestamp.or { Date() }
Personally for me code above more readable than if
construction inlining
Your format specifier is incorrect. From the printf()
man page on my machine:
0
A zero '0
' character indicating that zero-padding should be used rather than blank-padding. A '-
' overrides a '0
' if both are used;Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);
Precision: An optional period, '
.
', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;
For your case, your format would be %09.3f
:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%09.3f\n", 4917.24);
return 0;
}
Output:
$ make testapp
cc testapp.c -o testapp
$ ./testapp
04917.240
Note that this answer is conditional on your embedded system having a printf()
implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.
Try putting the btn-group
inside the H4
like this..
<div class="panel-heading">
<h4>Panel header
<span class="btn-group pull-right">
<a href="#" class="btn btn-default btn-sm">## Lock</a>
<a href="#" class="btn btn-default btn-sm">## Delete</a>
<a href="#" class="btn btn-default btn-sm">## Move</a>
</span>
</h4>
</div>
Adding even more simplicity of use to Jasper Bekkers' fantastic answer:
Set up once:
#define MAKE_ENUM(VAR) VAR,
#define MAKE_STRINGS(VAR) #VAR,
#define MAKE_ENUM_AND_STRINGS(source, enumName, enumStringName) \
enum enumName { \
source(MAKE_ENUM) \
};\
const char* const enumStringName[] = { \
source(MAKE_STRINGS) \
};
Then, for usage:
#define SOME_ENUM(DO) \
DO(Foo) \
DO(Bar) \
DO(Baz)
...
MAKE_ENUM_AND_STRINGS(SOME_ENUM, someEnum, someEnumNames)
timedelta
accepts minus(-) time values. so it could be simple as below
import datetime
enter = datetime.time(hour=1, minute=30)
exit = datetime.time(hour=2, minute=0)
duration = datetime.timedelta(hours=exit.hour-enter.hour, minutes=exit.minute-enter.minute)
# duration = datetime.timedelta(hours=1, minutes=-30)
result
>>> duration
datetime.timedelta(seconds=1800)
If you're new
ing up an element with initializer syntax, you can do something like this:
var row = new HtmlTableRow
{
Cells =
{
new HtmlTableCell
{
InnerText = text,
Attributes = { ["style"] = "min-width: 35px;" }
},
}
};
Or if using the CssStyleCollection
specifically:
var row = new HtmlTableRow
{
Cells =
{
new HtmlTableCell
{
InnerText = text,
Style = { ["min-width"] = "35px" }
},
}
};
How about this:
int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
// task completed within timeout
} else {
// timeout logic
}
Addition: at the request of a comment on my answer, here is an expanded solution that includes cancellation handling. Note that passing cancellation to the task and the timer means that there are multiple ways cancellation can be experienced in your code, and you should be sure to test for and be confident you properly handle all of them. Don't leave to chance various combinations and hope your computer does the right thing at runtime.
int timeout = 1000;
var task = SomeOperationAsync(cancellationToken);
if (await Task.WhenAny(task, Task.Delay(timeout, cancellationToken)) == task)
{
// Task completed within timeout.
// Consider that the task may have faulted or been canceled.
// We re-await the task so that any exceptions/cancellation is rethrown.
await task;
}
else
{
// timeout/cancellation logic
}
You are incorrectly using the super
and this
keyword. Here is an example of how they work:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
move(meters: number) {
console.log(this.name + " moved " + meters + "m.");
}
}
class Horse extends Animal {
move() {
console.log(super.name + " is Galloping...");
console.log(this.name + " is Galloping...");
super.move(45);
}
}
var tom: Animal = new Horse("Tommy the Palomino");
Animal.prototype.name = 'horseee';
tom.move(34);
// Outputs:
// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.
Explanation:
super.name
, this refers to the prototype chain of the object tom
, not the object tom
self. Because we have added a name property on the Animal.prototype
, horseee will be outputted.this.name
, the this
keyword refers to the the tom object itself. move
method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);
. Using the super
keyword in this context will look for a move
method on the prototype chain which is found on the Animal prototype.Remember TS still uses prototypes under the hood and the class
and extends
keywords are just syntactic sugar over prototypical inheritance.
An <iframe>
background can be changed like this:
<iframe allowtransparency="true" style="background: #FFFFFF;"
src="http://zingaya.com/widget/9d043c064dc241068881f045f9d8c151"
frameborder="0" height="184" width="100%">
</iframe>
I don't think it's possible to change the background of the page that you have loaded in the iframe.
Add -lrt
to the end of g++ command line. This links in the librt.so "Real Time" shared library.
$('#submenu li').hover(function(){
$('#carousel').css('backgroundPosition', newValue);
});
The closest you will ever get to doing such thing is a dissasembler, or debug info (Log2Vis.pdb).
I would like to add my comments. When you choose a ready engine, such as jBPM, Activity and others (there are plenty of them), then you have to spend some time learning the system itself, this may not be an easy task. Especially, when you need only to automate small piece of code.
Then, when an issue occurs you have to deal with the vendor's support, which is not as speedy as you would imagine. Even pay for some consultancy.
And, last, a most important reason, you have to develop in the ecosystem of the engine. Although, the vendors tend to say that their system are flexible to be incorporated into any systems, this may not be case. Eventually you end up re-writing your application to match with the BPM ecosystem.
Another solution to this is to use an HTML minifier. This works best with a Grunt build process, where the HTML can be minified on the fly.
The extra linebreaks and whitespace are removed, which solves the margin problem neatly, and lets you write markup however you like in the IDE (no </li><li>
).
In my case, Environment.NewLine was working fine while previewing the report in Visual Studio. But when I tried to publish the rdl to Dynamics 365 CE, I received the error "The report server has RDLSandboxing enabled and the Value expression for the text box 'Textbox10' contains a reference to a type, namespace, or member 'Environment' that is not allowed."
So I had to replace Environment.NewLine with vbcrlf.
DataSet ds = new DataSet();
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(query, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(ds);
}
return ds;
You should use:
card_value= array.eq(i).val(); //gets jquery object at index i
or
card_value= array[i].value; //gets dom element at index i
Normally, the exe can be found in the debug folder, as suggested previously, but not in the release folder, that is disabled by default in my configuration. If you want to activate the release folder, you can do this: BUILD->Batch Build And activate the "build" checkbox in the release configuration. When you click the build button, the exe with some dependencies will be generated. Now you can copy and use it.
The method you are trying to use checks if the button is active:
btnAdd.isEnabled()
When enabled, any component associated with this object is active and able to fire this object's actionPerformed method.
This method does not check if the button is pressed.
If i understand your question correctly, you want to disable your "Add" button after the user clicks "Check out".
Try disabling your button at start: btnAdd.setEnabled(false)
or after the user presses "Check out"
I recently faced similar issue where the atom editor will not close. Neither was responding. Kill / kill -9 / force exit from Activity Monitor - didn't work. Finally had to restart my mac to close the app.
If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:
<a id="sign_up" class="sign_new">Sign up</a>
And jQuery:
$(document).ready(function(){
$('#sign_up').click(function(){
alert('Sign new href executed.');
});
});
If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).
$(document).ready(function(){
$('#sign_up').click(function(event){
alert('Sign new href executed.');
event.stopPropagation();
});
});
var fav = [];
$.each($("input[name='name']:checked"), function(){
fav.push($(this).val());
});
It will give you the value separeted by commas
The Picup app is a way to take pictures from an HTML5 page and upload them to your server. It requires some extra programming on the server, but apart from PhoneGap, I have not found another way.
I think you could have used:
value.ToString("F"+NumberOfDecimals)
value = 10,502
value.ToString("F2") //10,50
value = 10,5
value.ToString("F2") //10,50
Here is a detailed description of Numeric Format Strings
The primary difference between the two is the following
typeof Reference: http://www.delorie.com/gnu/docs/gcc/gcc_36.html
typeid Reference: https://en.wikipedia.org/wiki/Typeid
Ctrl-Z should normally do the trick.
You can do this with a Correlated Subquery (That is a subquery wherein you reference a field in the main query). In this case:
SELECT *
FROM yourtable t1
WHERE date = (SELECT max(date) from yourtable WHERE id = t1.id)
Here we give the yourtable
table an alias of t1
and then use that alias in the subquery grabbing the max(date)
from the same table yourtable
for that id
.
ALTER TABLE table
DROP FOREIGN KEY fk_key
EDIT: didn't notice you were using sql-server, my bad
ALTER TABLE table
DROP CONSTRAINT fk_key
Depends on what your target browsers are. In newer ones it's as simple as:
-moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
box-shadow: 0 0 5px #fff;
For older browsers you have to implement workarounds, e.g., based on this example, but you will most probably need extra mark-up.
Followed the steps.
DevKit
to path C:\Ruby193\DevKit
cd C:\Ruby192\DevKit
ruby dk.rb init
ruby dk.rb review
ruby dk.rb install
Then I wrote the command
gem install rails -r -y
SELECT last_value, increment_by from "other_schema".id_seq;
for adding a seq to a column where the schema is not public try this.
nextval('"other_schema".id_seq'::regclass)
I had the same need/problem but nothing here worked for me (or I didn't understand everything), so this is my solution.
I post my minimal_http_server.sh (working with my /bin/bash (4.3.11) but not /bin/sh because of the redirection):
rm -f out
mkfifo out
trap "rm -f out" EXIT
while true
do
cat out | nc -l 1500 > >( # parse the netcat output, to build the answer redirected to the pipe "out".
export REQUEST=
while read -r line
do
line=$(echo "$line" | tr -d '\r\n')
if echo "$line" | grep -qE '^GET /' # if line starts with "GET /"
then
REQUEST=$(echo "$line" | cut -d ' ' -f2) # extract the request
elif [ -z "$line" ] # empty line / end of request
then
# call a script here
# Note: REQUEST is exported, so the script can parse it (to answer 200/403/404 status code + content)
./a_script.sh > out
fi
done
)
done
And my a_script.sh (with your need):
#!/bin/bash
echo -e "HTTP/1.1 200 OK\r"
echo "Content-type: text/html"
echo
date
Another "kill it with fire" approach is to just restart the MSSQLSERVER service. I like to do stuff from the commandline. Pasting this exactly into CMD will do it: NET STOP MSSQLSERVER & NET START MSSQLSERVER
Or open "services.msc" and find "SQL Server (MSSQLSERVER)" and right-click, select "restart".
This will "for sure, for sure" kill ALL connections to ALL databases running on that instance.
(I like this better than many approaches that change and change back the configuration on the server/database)
OK, Firefox 7 implemented text-overflow: ellipsis
as well as text-overflow: "string"
. Final release is planned for 2011-09-27.
adb devices
.This works on Windows and Ubuntu Linux, and should work on Mac as well.
Change the cell type to Markdown in the menu bar, from Code
to Markdown
. Currently in Notebook 4.x
, the keyboard shortcut for such an action is: Esc
(for command mode), then m
(for markdown).
UPDATE 2:
See this answer . - 2019-11-05
You can also now have it auto-open Developer Tools in Pop-ups if they were open where you opened them from. For example, if you do not have Dev Tools open and you get a popup, it won't open with Dev Tools. But if you Have Dev Tools Open and then you click something, the popup will have Dev-Tools Automatically opened.
UPDATE:
Time has changed, you can now use --auto-open-devtools-for-tabs as in this answer – Wouter Huysentruit May 18 at 11:08
OP:
I played around with the startup string for Chrome on execute, but couldn't get it to persist to new tabs.
I also thought about a defined PATH method that you could invoke from prompt. This is possible with the SendKeys command, but again, only on a new instance. And DevTools doesn't persist to new tabs.
Browsing the Google Product Forums, there doesn't seem to be a built-in way to do this in Chrome. You'll have to use a keystroke solution or F12 as mentioned above.
I recommended it as a feature. I know I'm not the first either.
SELECT * FROM (
SELECT id, name, form_id, DATE(updated_at) as date
FROM wp_frm_items
WHERE user_id = 11 && form_id=9
ORDER BY updated_at DESC
) AS TEMP
ORDER BY DATE(updated_at) DESC, name DESC
Give it a try.
I'm trying to learn closures and I think the example that I have created is a practical use case. You can run a snippet and see the result in the console.
We have two separate users who have separate data. Each of them can see the actual state and update it.
function createUserWarningData(user) {
const data = {
name: user,
numberOfWarnings: 0,
};
function addWarning() {
data.numberOfWarnings = data.numberOfWarnings + 1;
}
function getUserData() {
console.log(data);
return data;
}
return {
getUserData: getUserData,
addWarning: addWarning,
};
}
const user1 = createUserWarningData("Thomas");
const user2 = createUserWarningData("Alex");
//USER 1
user1.getUserData(); // Returning data user object
user1.addWarning(); // Add one warning to specific user
user1.getUserData(); // Returning data user object
//USER2
user2.getUserData(); // Returning data user object
user2.addWarning(); // Add one warning to specific user
user2.addWarning(); // Add one warning to specific user
user2.getUserData(); // Returning data user object
_x000D_
Type 3, in order to work would have to look like this:
(function($){
//Attach this new method to jQuery
$.fn.extend({
//This is where you write your plugin's name
'pluginname': function(_options) {
// Put defaults inline, no need for another variable...
var options = $.extend({
'defaults': "go here..."
}, _options);
//Iterate over the current set of matched elements
return this.each(function() {
//code to be inserted here
});
}
});
})(jQuery);
I am unsure why someone would use extend over just directly setting the property in the jQuery prototype, it is doing the same exact thing only in more operations and more clutter.
Adding to the solutions of others, I'd like to suggest using the plotly
package for R
, as this has worked well for me.
Below, I'm using the reformatted dataset suggested above, from xyz-tripplets to axis vectors x and y and a matrix z:
x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z
library(plotly)
plot_ly(x=x,y=y,z=z, type="surface")
The rendered surface can be rotated and scaled using the mouse. This works fairly well in RStudio.
You can also try it with the built-in volcano
dataset from R
:
plot_ly(z=volcano, type="surface")
For me it worked by closing the Eclipse and using the command line to build the project. Seems like Eclipse had taken a lock on the files.
Since mysql_connect This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. by default xampp does not load it automatically
in your php.ini file you should uncomment
;; extension=php_mysql.dll
to
extension=php_mysql.dll
Then restart your apache you should be fine
It doesn't - the C# compiler does :)
So this code:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
actually gets compiled as:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - intervening edit removed other bits accidentally.)
The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y
which then needs to be copied again as part of the concatenation of (x + y)
and z
. Instead, we get it all done in one go.
EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:
string x = "";
foreach (string y in strings)
{
x += y;
}
just ends up as equivalent to:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... so this does generate a lot of garbage, and it's why you should use a StringBuilder
for such cases. I have an article going into more details about the two which will hopefully answer further questions.
This article Time Period Library for .NET describes the relation of two time periods by the enumeration PeriodRelation:
// ------------------------------------------------------------------------
public enum PeriodRelation
{
After,
StartTouching,
StartInside,
InsideStartTouching,
EnclosingStartTouching,
Enclosing,
EnclosingEndTouching,
ExactMatch,
Inside,
InsideEndTouching,
EndInside,
EndTouching,
Before,
} // enum PeriodRelation
Use the CSS display values of table and table-cell:
HTML
<html>
<body>
<div class="valign bottom">
<div>
<div>my bottom aligned div 1</div>
<div>my bottom aligned div 2</div>
<div>my bottom aligned div 3</div>
</div>
</div>
</body>
</html>
CSS
html,body {
width: 100%;
height: 100%;
}
.valign {
display: table;
width: 100%;
height: 100%;
}
.valign > div {
display: table-cell;
width: 100%;
height: 100%;
}
.valign.bottom > div {
vertical-align: bottom;
}
I've created a JSBin demo here: http://jsbin.com/INOnAkuF/2/edit
The demo also has an example how to vertically center align using the same technique.
df1 = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]})
p = df1.index.values
df1.insert( 0, column="new",value = p)
df1
new gi ptt
0 0 232 342
1 1 66 56
2 2 34 662
3 3 43 123
Without jquery or anything like that beacuse why not ?
var loaded=0;
var loaded1min=0;
document.addEventListener("DOMContentLoaded", function(event) {
loaded=1;
setTimeout(function () {
loaded1min=1;
}, 60000);
});
If you haven't yet commited the changes, then:
git diff > mypatch.patch
But sometimes it happens that part of the stuff you're doing are new files that are untracked and won't be in your git diff
output. So, one way to do a patch is to stage everything for a new commit (git add
each file, or just git add .
) but don't do the commit, and then:
git diff --cached > mypatch.patch
Add the 'binary' option if you want to add binary files to the patch (e.g. mp3 files):
git diff --cached --binary > mypatch.patch
You can later apply the patch:
git apply mypatch.patch
Many possibilities...
You know how to generate randomly an integer right? You can thus generate a char from it... (ex 65 -> A)
It depends what you need, the level of randomness, the security involved... but for a school project i guess getting UUID substring would fit :)
if (($num >= $lower_boundary) && ($num <= $upper_boundary)) {
You may want to adjust the comparison operators if you want the boundary values not to be valid.
You did not supply the file handling code, but I assume you made the same mistake everyone does when first writing such a thing: the filewatcher event will be raised as soon as the file is created. However, it will take some time for the file to be finished. Take a file size of 1 GB for example. The file may be created by another program (Explorer.exe copying it from somewhere) but it will take minutes to finish that process. The event is raised at creation time and you need to wait for the file to be ready to be copied.
You can wait for a file to be ready by using this function in a loop.
I was able to resolve it simply by opening the notification bar of the android phone , clicking on "tap for more options" and selecting PTP
Take a look at the @Deprecated
annotation.
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.
You may also get that error when CSRF "token" for the active user session is out of date, even if the token was specified in ajax request.
In the case where one is using the ADO.NET Entity Framework, EchoStorm's solution also works perfectly. But it took me a few minutes to wrap my head around it. Assuming you have a database context, dc, and want to find rows in table x not linked in table y, the complete answer answer looks like:
var linked =
from x in dc.X
from y in dc.Y
where x.MyProperty == y.MyProperty
select x;
var notLinked =
dc.X.Except(linked);
In response to Andy's comment, yes, one can have two from's in a LINQ query. Here's a complete working example, using lists. Each class, Foo and Bar, has an Id. Foo has a "foreign key" reference to Bar via Foo.BarId. The program selects all Foo's not linked to a corresponding Bar.
class Program
{
static void Main(string[] args)
{
// Creates some foos
List<Foo> fooList = new List<Foo>();
fooList.Add(new Foo { Id = 1, BarId = 11 });
fooList.Add(new Foo { Id = 2, BarId = 12 });
fooList.Add(new Foo { Id = 3, BarId = 13 });
fooList.Add(new Foo { Id = 4, BarId = 14 });
fooList.Add(new Foo { Id = 5, BarId = -1 });
fooList.Add(new Foo { Id = 6, BarId = -1 });
fooList.Add(new Foo { Id = 7, BarId = -1 });
// Create some bars
List<Bar> barList = new List<Bar>();
barList.Add(new Bar { Id = 11 });
barList.Add(new Bar { Id = 12 });
barList.Add(new Bar { Id = 13 });
barList.Add(new Bar { Id = 14 });
barList.Add(new Bar { Id = 15 });
barList.Add(new Bar { Id = 16 });
barList.Add(new Bar { Id = 17 });
var linked = from foo in fooList
from bar in barList
where foo.BarId == bar.Id
select foo;
var notLinked = fooList.Except(linked);
foreach (Foo item in notLinked)
{
Console.WriteLine(
String.Format(
"Foo.Id: {0} | Bar.Id: {1}",
item.Id, item.BarId));
}
Console.WriteLine("Any key to continue...");
Console.ReadKey();
}
}
class Foo
{
public int Id { get; set; }
public int BarId { get; set; }
}
class Bar
{
public int Id { get; set; }
}
If you use a pem file to authenticate u can use the following command (which will exclude files with something extension):
rsync -Lavz -e "ssh -i <full-path-to-pem> -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --exclude "*.something" --progress <path inside local host> <user>@<host>:<path inside remote host>
The -L means follow links (copy files not links). Use full path to your pem file and not relative.
Using sshfs is not recommended since it works slowly. Also, the combination of find and scp that was presented above is also a bad idea since it will open a ssh session per file which is too expensive.
Add spring-tx jar file and it should settle it.
I didn't need to set up remote debugging in order to get this working, I used Maven.
spring-boot::run
.NB. If your IDE has problems finding your project's source code when doing line-by-line debugging, take a look at this SO answer to find out how to manually attach your source code to the debug application.
Hope this helps someone!
There's an Abstract Class Dictionary
http://docs.oracle.com/javase/6/docs/api/java/util/Dictionary.html
However this requires implementation.
Java gives us a nice implementation called a Hashtable
http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html
Use ld.charAt(0)
. It will return the first char
of the String
.
With ld.substring(0, 1)
, you can get the first character as String
.
Your belief about what will happen is not correct. Setting a default value for a column will not affect the existing data in the table.
I create a table with a column col2
that has no default value
SQL> create table foo(
2 col1 number primary key,
3 col2 varchar2(10)
4 );
Table created.
SQL> insert into foo( col1 ) values (1);
1 row created.
SQL> insert into foo( col1 ) values (2);
1 row created.
SQL> insert into foo( col1 ) values (3);
1 row created.
SQL> select * from foo;
COL1 COL2
---------- ----------
1
2
3
If I then alter the table to set a default value, nothing about the existing rows will change
SQL> alter table foo
2 modify( col2 varchar2(10) default 'foo' );
Table altered.
SQL> select * from foo;
COL1 COL2
---------- ----------
1
2
3
SQL> insert into foo( col1 ) values (4);
1 row created.
SQL> select * from foo;
COL1 COL2
---------- ----------
1
2
3
4 foo
Even if I subsequently change the default again, there will still be no change to the existing rows
SQL> alter table foo
2 modify( col2 varchar2(10) default 'bar' );
Table altered.
SQL> select * from foo;
COL1 COL2
---------- ----------
1
2
3
4 foo
SQL> insert into foo( col1 ) values (5);
1 row created.
SQL> select * from foo;
COL1 COL2
---------- ----------
1
2
3
4 foo
5 bar
String input = ....;
int index = input.IndexOf('.');
if(index >= 0)
{
return input.Substring(index + 1);
}
This will return the new word.
transform: scale(0.5);
<div>Normal</div>
<div class="scaled">Scaled</div>
div {
width: 80px;
height: 80px;
background-color: skyblue;
}
.scaled {
transform: scale(0.7); /* Equal to scaleX(0.7) scaleY(0.7) */
background-color: pink;
}
see: https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scale
If the variable is declared (either with the var
keyword, as a function argument, or as a global variable), I think the best way to do it is:
if (my_variable === undefined)
jQuery does it, so it's good enough for me :-)
Otherwise, you'll have to use typeof
to avoid a ReferenceError
.
If you expect undefined to be redefined, you could wrap your code like this:
(function(undefined){
// undefined is now what it's supposed to be
})();
Or obtain it via the void
operator:
const undefined = void 0;
// also safe
if x is a string and you search for y which also a string their is two cases : case 1: y is exist in x so x.find(y) = the index (the position) of the y in x . case 2: y is not exist so x.find (y) = -1 this mean y is not found in x.
One easy non-loop approach would be to use genvarname
to create a cell array of strings:
>> N = 5;
>> f = genvarname(repmat({'f'}, 1, N), 'f')
f =
'f1' 'f2' 'f3' 'f4' 'f5'
The function genvarname
has been deprecated, so matlab.lang.makeUniqueStrings
can be used instead in the following way to get the same output:
>> N = 5;
>> f = strrep(matlab.lang.makeUniqueStrings(repmat({'f'}, 1, N), 'f'), '_', '')
f =
1×5 cell array
'f1' 'f2' 'f3' 'f4' 'f5'
In cmd
, you can do this:
copy one.txt+two.txt+three.txt four.txt
In PowerShell this would be:
cmd /c copy one.txt+two.txt+three.txt four.txt
While the PowerShell way would be to use gc, the above will be pretty fast, especially for large files. And it can be used on on non-ASCII files too using the /B
switch.
You can't really. You'll have to have both the drop down, and the text box, and have them pick or fill in the form. Without javascript you could create a separate radio button set where they choose dropdown or text input, but this seems messy to me. With some javascript you could toggle disable one or the other depending on which one they choose, for instance, have an 'other' option in the dropdown that triggers the text field.
Your code is passing a function as an argument to find
. That function takes an element
argument (of type Conversation
) and returns void
(meaning there is no return value). TypeScript describes this as (element: Conversation) => void'
What TypeScript is saying is that the find
function doesn't expect to receive a function that takes a Conversation and returns void. It expects a function that takes a Conversations
, a number
and a Conversation
array, and that this function should return a boolean
.
So bottom line is that you either need to change your code to pass in the values to find
correctly, or else you need to provide an overload to the definition of find
in your definition file that accepts a Conversation
and returns void
.
You need to add a '/' after the dir name
<exclude name="WEB-INF/" />
SHOW ENGINE INNODB STATUS \G
Look for the Section -
TRANSACTIONS
We can use INFORMATION_SCHEMA Tables.
Useful Queries
To check about all the locks transactions are waiting for:
USE INFORMATION_SCHEMA;
SELECT * FROM INNODB_LOCK_WAITS;
A list of blocking transactions:
SELECT *
FROM INNODB_LOCKS
WHERE LOCK_TRX_ID IN (SELECT BLOCKING_TRX_ID FROM INNODB_LOCK_WAITS);
OR
SELECT INNODB_LOCKS.*
FROM INNODB_LOCKS
JOIN INNODB_LOCK_WAITS
ON (INNODB_LOCKS.LOCK_TRX_ID = INNODB_LOCK_WAITS.BLOCKING_TRX_ID);
A List of locks on particular table:
SELECT * FROM INNODB_LOCKS
WHERE LOCK_TABLE = db_name.table_name;
A list of transactions waiting for locks:
SELECT TRX_ID, TRX_REQUESTED_LOCK_ID, TRX_MYSQL_THREAD_ID, TRX_QUERY
FROM INNODB_TRX
WHERE TRX_STATE = 'LOCK WAIT';
Reference - MySQL Troubleshooting: What To Do When Queries Don't Work, Chapter 6 - Page 96.
The twelve step solution covered above helped get me out of a jam as well. Thanks. The key steps were to enter:
git fsck --full
and remove all empty objects
rm .git/objects/...
Then getting the two lines of the flog:
tail -n 2 .git/logs/refs/heads/master
With the returned values
git update-ref HEAD ...
At this point I had no more errors, so I made a backup of my most recent files. Then do a git pull followed by a git push. Copied my backups to my git repository file and did another git push. That got me current.
Short answer: You can't. rm
removes files blindly, with no concept of 'trash'.
Some Unix and Linux systems try to limit its destructive ability by aliasing it to rm -i
by default, but not all do.
Long answer: Depending on your filesystem, disk activity, and how long ago the deletion occured, you may be able to recover some or all of what you deleted. If you're using an EXT3 or EXT4 formatted drive, you can check out extundelete
.
In the future, use rm
with caution. Either create a del
alias that provides interactivity, or use a file manager.
Since there is no programmatic way to mimic minimal-ui
, we have come up with a different workaround, using calc()
and known iOS address bar height to our advantage:
The following demo page (also available on gist, more technical details there) will prompt user to scroll, which then triggers a soft-fullscreen (hide address bar/menu), where header and content fills the new viewport.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scroll Test</title>
<style>
html, body {
height: 100%;
}
html {
background-color: red;
}
body {
background-color: blue;
margin: 0;
}
div.header {
width: 100%;
height: 40px;
background-color: green;
overflow: hidden;
}
div.content {
height: 100%;
height: calc(100% - 40px);
width: 100%;
background-color: purple;
overflow: hidden;
}
div.cover {
position: absolute;
top: 0;
left: 0;
z-index: 100;
width: 100%;
height: 100%;
overflow: hidden;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
display: none;
}
@media screen and (width: 320px) {
html {
height: calc(100% + 72px);
}
div.cover {
display: block;
}
}
</style>
<script>
var timeout;
window.addEventListener('scroll', function(ev) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
if (window.scrollY > 0) {
var cover = document.querySelector('div.cover');
cover.style.display = 'none';
}
}, 200);
});
</script>
</head>
<body>
<div class="header">
<p>header</p>
</div>
<div class="content">
<p>content</p>
</div>
<div class="cover">
<p>scroll to soft fullscreen</p>
</div>
</body>
</html>
Virtual classes are not the same as virtual inheritance. Virtual classes you cannot instantiate, virtual inheritance is something else entirely.
Wikipedia describes it better than I can. http://en.wikipedia.org/wiki/Virtual_inheritance
I think this may be another way
var width= $('#elm').width();
$('#element').css({ 'width': 'calc(100% - ' + width+ 'px)' });
Please see if you are setting client_max_body_size directive inside http {} block and not inside location {} block. I have set it inside http{} block and it works
As I understand , all of previous answers , does not make an Array output, In my case : I have a model with parent-children structure (simplified code here):
public function parent(){
return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}
and if you want to have all of children IDs as an Array , This approach is fine and working for me :
public function allChildren()
{
$allChildren = [];
if ($this->has_branch) {
foreach ($this->children as $child) {
$subChildren = $child->allChildren();
if (count($subChildren) == 1) {
$allChildren [] = $subChildren[0];
} else if (count($subChildren) > 1) {
$allChildren += $subChildren;
}
}
}
$allChildren [] = $this->id;//adds self Id to children Id list
return $allChildren;
}
the allChildren() returns , all of childrens as a simple Array .
It is worth to mention how to remove the extension also in parallel with getting the extension:
var name = Path.GetFileNameWithoutExtension(fileFullName); // Get the name only
var extension = Path.GetExtension(fileFullName); // Get the extension only
One of the values you pass on to Ancestors
becomes None
at some point, it says, so check if otu
, tree
, tree[otu]
or tree[otu][0]
are None
in the beginning of the function instead of only checking tree[otu][0][0] == None
. But perhaps you should reconsider your path of action and the datatype in question to see if you could improve the structure somewhat.
My understanding of the asker's question is such that:
How does this magic work:
(function(){}) ('input') // Used in his example
I may be wrong. However, the usual practice that people are familiar with is:
(function(){}('input') )
The reason is such that JavaScript parentheses AKA ()
, can't contain statements and when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.
Source: blog post Immediately-Invoked Function Expression (IIFE)
I strongly suggest placing this somewhere in your project:
extension String {
func trim() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
func trim(withSet: NSCharacterSet) -> String {
return self.stringByTrimmingCharactersInSet(withSet)
}
}
Nowadays, it is the most efficient and comfortable to use lubridate and dplyr libraries.
lubridate
contains a number of functions that make parsing dates into POSIXct
or Date
objects easy. Here we use dmy
which automatically parses dates in Day, Month, Year
formats. Once your data is in a date format, you can sort it with dplyr::arrange
(or any other ordering function) as desired:
d$V3 <- lubridate::dmy(d$V3)
dplyr::arrange(d, V3)
I think that it is better (for my expirience) to use: :first-of-type
, :nth-of-type()
, :last-of-type
. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type
, than *-child
selectors.
Are you using the interactive interpreter? You can use
sys.argv[0]
You should read: How do I get the path of the current executed file in Python?
If you need to re-type this several times, you can do like I did once. Get your columns` names into rows in excel sheet (write down at the end of each column name (=) which is easy in notepad++) on the right side make a column to copy and paste your value that will correspond to the new entries at each column. Then on the right of them in an independent column put the commas as designed
Then you will have to copy your values into the middle column each time then just paste then and run
I do not know an easier solution
First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:
raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it
freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level
Then you need to create a data frame out of it, melt it and plot it:
Names=c("Food","Music","People") # create list of names
data=data.frame(cbind(freq),Names) # combine them into a data frame
data=data[,c(5,3,1,2,4)] # sort columns
# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')
# plot everything
ggplot(data.m, aes(Names, value)) +
geom_bar(aes(fill = variable), position = "dodge", stat="identity")
Is this what you're after?
To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:
> head(df)
ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1 1 A 1980 450 338 154 36 13 9
2 2 A 2000 288 407 212 54 16 23
3 3 A 2020 196 434 246 68 19 36
4 4 B 1980 111 326 441 90 21 11
5 5 B 2000 63 298 443 133 42 21
6 6 B 2020 36 257 462 162 55 30
Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape
and plotted.
For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw))
to get this:
> data
Names Very.Bad Bad Good Very.Good
1 Food 7 6 5 2
2 Music 5 5 7 3
3 People 6 3 7 4
Just imagine you have Very.Bad
, Bad
, Good
and so on instead of X1PCE
, X2PCE
, X3PCE
. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw))
.
here's a link that explains many different hash functions, for now I prefer the ELF hash function for your particular problem. It takes as input a string of arbitrary length.
<context:component-scan /> implicitly enables <context:annotation-config/>
try with <context:component-scan base-package="..." annotation-config="false"/>
, in your configuration @Service, @Repository, @Component works fine, but @Autowired,@Resource and @Inject doesn't work.
This means AutowiredAnnotationBeanPostProcessor will not be enabled and Spring container will not process the Autowiring annotations.
These numbers come from the IEEE-754 standard, which defines the standard representation of floating point numbers. Wikipedia article at the link explains how to arrive at these ranges knowing the number of bits used for the signs, mantissa, and the exponent.
Angular's $http has a cache built in. According to the docs:
cache – {boolean|Object} – A boolean value or object created with $cacheFactory to enable or disable caching of the HTTP response. See $http Caching for more information.
So you can set cache
to true in its options:
$http.get(url, { cache: true}).success(...);
or, if you prefer the config type of call:
$http({ cache: true, url: url, method: 'GET'}).success(...);
You can also use a cache factory:
var cache = $cacheFactory('myCache');
$http.get(url, { cache: cache })
You can implement it yourself using $cacheFactory (especially handly when using $resource):
var cache = $cacheFactory('myCache');
var data = cache.get(someKey);
if (!data) {
$http.get(url).success(function(result) {
data = result;
cache.put(someKey, data);
});
}
The data-toggle attribute simple tell Bootstrap what exactly to do by giving it the name of the toggle action it is about to perform on a target element. If you specify collapse. It means bootstrap will collapse or uncollapse the element pointed by data-target of the action you clicked
Note: the target element must have the appropriate class for bootstrap to carry out the action
Source action:
data-toggle = collapse //type of toggle
data-target = #myDiv
Target:
class=collapse //I can collapse
id=myDiv
This is same for other type of toggle actions like tab, modal, dropdown
No, it isn't. You will need something on the server to send a Content-Disposition header to set the file as an attachment instead of being inline. You could do this with plain Apache configuration though.
I've found an example of doing it using mod_rewrite, although I know there is a simpler way.
I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):
I just had to update legacy Weblogic 8 app to use a data-source instead of hard-coded JDBC string. Datasource JNDI name on the configuration tab in the Weblogic admin showed: "weblogic.jdbc.ESdatasource", below are two ways that worked:
Context ctx = new InitialContext();
DataSource dataSource;
try {
dataSource = (DataSource) ctx.lookup("weblogic.jdbc.ESdatasource");
response.getWriter().println("A " +dataSource);
}catch(Exception e) {
response.getWriter().println("A " + e.getMessage() + e.getCause());
}
//or
try {
dataSource = (DataSource) ctx.lookup("weblogic/jdbc/ESdatasource");
response.getWriter().println("F "+dataSource);
}catch(Exception e) {
response.getWriter().println("F " + e.getMessage() + e.getCause());
}
//use your datasource
conn = datasource.getConnection();
That's all folks. No passwords and initial context factory needed from the inside of Weblogic app.
You can export a certificate using Firefox, this site has instructions. Then you use keytool to add the certificate.
For users that are not members of the sysadmin role on the SQL Server instance you need to do the following actions to grant access to the xp_cmdshell extended stored procedure. In addition if you forgot one of the steps I have listed the error that will be thrown.
Enable the xp_cmdshell procedure
Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1 SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', see "Surface Area Configuration" in SQL Server Books Online.*
Create a login for the non-sysadmin user that has public access to the master database
Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*
Grant EXEC permission on the xp_cmdshell stored procedure
Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*
Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account
Msg 15153, Level 16, State 1, Procedure xp_cmdshell, Line 1 The xp_cmdshell proxy account information cannot be retrieved or is invalid. Verify that the '##xp_cmdshell_proxy_account##' credential exists and contains valid information.*
It would seem from your error that either step 2 or 3 was missed. I am not familiar with clusters to know if there is anything particular to that setup.
A colleague found this MS auto-uninstall tool which has successfully uninstalled VS2008 for me and saved me hours of work!!
Hopefully this might be useful to others. Doesn't speak highly of MS's faith in their usual VS maintenance tools that they have to provide this as well!
Apache 2.4 virtual hosts hack
1.In http.conf specify the ports , below “Listen”
Listen 80
Listen 4000
Listen 7000
Listen 9000
In httpd-vhosts.conf
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html"
ServerName hitesh_web.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common
<Directory "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html">
Allow from all
Require all granted
</Directory>
</VirtualHost>
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "E:/dabkick_git/DabKickWebsite"
ServerName www.my_mobile.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common
<Directory "E:/dabkick_git/DabKickWebsite">
Allow from all
Require all granted
</Directory>
</VirtualHost>
In hosts.ics file of windows os “C:\Windows\System32\drivers\etc\host.ics”
127.0.0.1 localhost
127.0.0.1 hitesh_web.dev
127.0.0.1 www.my_mobile.dev
127.0.0.1 demo.multisite.dev
4.now type your “domain names” in the browser it will ping the particular folder specified in the documentRoot path
5.if you want to access those files in a particular port then replace 80 in httpd-vhosts.conf with port numbers like below and restart apache
<VirtualHost *:4000>
ServerAdmin [email protected]
DocumentRoot "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html"
ServerName hitesh_web.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common
<Directory "C:/Users/Vikas/Documents/NetBeansProjects/slider_website_hitesh/public_html">
Allow from all
Require all granted
</Directory>
</VirtualHost>
<VirtualHost *:7000>
ServerAdmin [email protected]
DocumentRoot "E:/dabkick_git/DabKickWebsite"
ServerName www.dabkick_mobile.dev
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common
<Directory "E:/dabkick_git/DabKickWebsite">
Allow from all
Require all granted
</Directory>
</VirtualHost>
Note: for port number given virtual hosts you have to ping in browser like “http://hitesh_web.dev:4000/” or “http://www.dabkick_mobile.dev:7000/”
6.After doing all those changes you have to save the files and restart apache respectively.
Since Go 1.11+, GOPATH is no longer recommended, the new way is using Go Modules.
simple
:Create a directory:
mkdir simple
cd simple
Create a new module:
go mod init github.com/username/simple
# Here, the module name is: github.com/username/simple.
# You're free to choose any module name.
# It doesn't matter as long as it's unique.
# It's better to be a URL: so it can be go-gettable.
Put all your files in that directory.
Finally, run:
go run .
Alternatively, you can create an executable program by building it:
go build .
# then:
./simple # if you're on xnix
# or, just:
simple # if you're on Windows
For more information, you may read this.
Go has included support for versioned modules as proposed here since 1.11. The initial prototype vgo was announced in February 2018. In July 2018, versioned modules landed in the main Go repository. In Go 1.14, module support is considered ready for production use, and all users are encouraged to migrate to modules from other dependency management systems.
For completeness, one other way is to clear the softspace value after performing the write.
import sys
print "hello",
sys.stdout.softspace=0
print "world",
print "!"
prints helloworld !
Using stdout.write() is probably more convenient for most cases though.
According to C99/GNU99 specification:
static
is storage-class specifier
objects of file level scope by default has external linkage
const
is type-qualifier (is a part of type)
keyword applied to immediate left instance - i.e.
MyObj const * myVar;
- unqualified pointer to const qualified object type
MyObj * const myVar;
- const qualified pointer to unqualified object type
Leftmost usage - applied to the object type, not variable
const MyObj * myVar;
- unqualified pointer to const qualified object typeTHUS:
static NSString * const myVar;
- constant pointer to immutable string with internal linkage.
Absence of the static
keyword will make variable name global and might lead to name conflicts within the application.
a="abc"
b="def"
# Equality Comparison
if [ "$a" == "$b" ]; then
echo "Strings match"
else
echo "Strings don't match"
fi
# Lexicographic (greater than, less than) comparison.
if [ "$a" \< "$b" ]; then
echo "$a is lexicographically smaller then $b"
elif [ "$a" \> "$b" ]; then
echo "$b is lexicographically smaller than $a"
else
echo "Strings are equal"
fi
Notes:
if
and [
and ]
are important>
and <
are redirection operators so escape it with \>
and \<
respectively for strings.Normally the views belong with a specific matching controller that supports its data requirements, or the view belongs in the Views/Shared
folder if shared between controllers (hence the name).
You can refer to views/partial views from another controller, by specifying the full path (including extension) like:
return PartialView("~/views/ABC/XXX.cshtml", zyxmodel);
or a relative path (no extension), based on the answer by @Max Toro
return PartialView("../ABC/XXX", zyxmodel);
BUT THIS IS NOT A GOOD IDEA ANYWAY
*Note: These are the only two syntax that work. not ABC\\XXX
or ABC/XXX
or any other variation as those are all relative paths and do not find a match.
You can use Html.Renderpartial
in your view instead, but it requires the extension as well:
Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);
Use @Html.Partial
for inline Razor syntax:
@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)
You can use the ../controller/view
syntax with no extension (again credit to @Max Toro):
@Html.Partial("../ControllerName/ViewName", modeldata)
Note: Apparently RenderPartial
is slightly faster than Partial, but that is not important.
If you want to actually call the other controller, use:
@Html.Action("action", "controller", parameters)
My personal preference is to use @Html.Action
as it allows each controller to manage its own views, rather than cross-referencing views from other controllers (which leads to a large spaghetti-like mess).
You would normally pass just the required key values (like any other view) e.g. for your example:
@Html.Action("XXX", "ABC", new {id = model.xyzId })
This will execute the ABC.XXX
action and render the result in-place. This allows the views and controllers to remain separately self-contained (i.e. reusable).
I have just hit a situation where I could not use @Html.Action, but needed to create a view path based on a action
and controller
names. To that end I added this simple View
extension method to UrlHelper
so you can say return PartialView(Url.View("actionName", "controllerName"), modelData)
:
public static class UrlHelperExtension
{
/// <summary>
/// Return a view path based on an action name and controller name
/// </summary>
/// <param name="url">Context for extension method</param>
/// <param name="action">Action name</param>
/// <param name="controller">Controller name</param>
/// <returns>A string in the form "~/views/{controller}/{action}.cshtml</returns>
public static string View(this UrlHelper url, string action, string controller)
{
return string.Format("~/Views/{1}/{0}.cshtml", action, controller);
}
}
When I've only needed to specify specific columns, and I want to be explicit, I've used (per DOCS LOCATION):
dataframe = dataframe.astype({'col_name_1':'int','col_name_2':'float64', etc. ...})
So, using the original question, but providing column names to it ...
a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['col_name_1', 'col_name_2', 'col_name_3'])
df = df.astype({'col_name_2':'float64', 'col_name_3':'float64'})
How to center a view or its content e.g. TextView or Button horizontally and vertically? layout_gravity can be used to position a view in the center of its parent. While gravity attribute is used to position view’s content e.g. “text” in the center of the view.
( 1 ) Center TextView Horizontally
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="10dp"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_gravity="center"
android:background="#333"
android:textColor="#fff"
/>
</LinearLayout>
( 2 ) Center TextView Vertically
android:layout_gravity=”center_vertical” dose not work!!
To center TextView vertically, you need to make a trick. Place TextView inside a RelativeLayout then set the TextView attribute android:layout_centerInParent=”true”
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="10dp"
tools:context=".MainActivity" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_centerInParent="true"
android:layout_gravity="center_vertical"
android:gravity="center"
android:background="#333"
android:textColor="#fff"
/>
</RelativeLayout>
( 3 ) Center Text Horizontally
android:gravity=”center_horizontal"
( 4 ) Center Text Horizontally & Vertically
android:gravity=”center” this will center the text horizontally and vertically
<TextView android:layout_width="fill_parent" android:layout_height="100dp" android:text="Hello World!" android:gravity="center" android:background="#333" android:textColor="#fff" />
I faced this issue, I was not able to copy zeppelin [1GB] directory into docker container and was getting issue
COPY failed: stat /var/lib/docker/tmp/docker-builder977188321/zeppelin-0.7.2-bin-all: no such file or directory
I am using docker Version: 17.09.0-ce and resolved the issue with the following steps.
Step 1: copy zeppelin directory [which i want to copy into docker package]into directory contain "Dockfile"
Step 2: edit Dockfile and add command [location where we want to copy] ADD ./zeppelin-0.7.2-bin-all /usr/local/
Step 3: go to directory which contain DockFile and run command [alternatives also available] docker build
Step 4: docker image created Successfully with logs
Step 5/9 : ADD ./zeppelin-0.7.2-bin-all /usr/local/ ---> 3691c902d9fe
Step 6/9 : WORKDIR $ZEPPELIN_HOME ---> 3adacfb024d8 .... Successfully built b67b9ea09f02
I had various JDK from 1.5 to 1.7 installed on my PC. I had a need to learn JDK1.8 so installed and my earlier versions of Eclipse (depended on earlier versions of JDK) and I got errors launching my Eclipse IDE, on the command line I tried to check the Java Version and got the error below,
C:\>java -version Registry key 'Software\JavaSoft\Java Runtime Environment\CurrentVersion' has value '1.8', but '1.6' is required. Error: could not find java.dll Error: could not find Java SE Runtime Environment.
Solution:- I removed
C:\ProgramData\Oracle\Java\javapath;from the PATH variable and moved %JAVA%\bin to the start of the PATH variable, that solved the problem for me.
This cannot work because ppCombined
is a collection of objects in memory and you cannot join a set of data in the database with another set of data that is in memory. You can try instead to extract the filtered items personProtocol
of the ppCombined
collection in memory after you have retrieved the other properties from the database:
var persons = db.Favorites
.Where(f => f.userId == userId)
.Join(db.Person, f => f.personId, p => p.personId, (f, p) =>
new // anonymous object
{
personId = p.personId,
addressId = p.addressId,
favoriteId = f.favoriteId,
})
.AsEnumerable() // database query ends here, the rest is a query in memory
.Select(x =>
new PersonDTO
{
personId = x.personId,
addressId = x.addressId,
favoriteId = x.favoriteId,
personProtocol = ppCombined
.Where(p => p.personId == x.personId)
.Select(p => new PersonProtocol
{
personProtocolId = p.personProtocolId,
activateDt = p.activateDt,
personId = p.personId
})
.ToList()
});
If you want to remove the file from the remote repo, first remove it from your project with --cache option and then push it:
git rm --cache /path/to/file
git commit -am "Remove file"
git push
(This works even if the file was added to the remote repo some commits ago) Remember to add to .gitignore the file extensions that you don't want to push.
There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that are defined in the List interface. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.
Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).
That's called polymorphism. You can read up on it.
For mac :
I have added below two commands its working fine!
-vm
/usr/bin
/usr/libexec/java_home --verbose
I could not understand those 3 rules in the specs too well -- hope to have something that is more plain English -- but here is what I gathered from JavaScript: The Definitive Guide, 6th Edition, David Flanagan, O'Reilly, 2011:
Quote:
JavaScript does not treat every line break as a semicolon: it usually treats line breaks as semicolons only if it can’t parse the code without the semicolons.
Another quote: for the code
var a
a
=
3 console.log(a)
JavaScript does not treat the second line break as a semicolon because it can continue parsing the longer statement a = 3;
and:
two exceptions to the general rule that JavaScript interprets line breaks as semicolons when it cannot parse the second line as a continuation of the statement on the first line. The first exception involves the return, break, and continue statements
... If a line break appears after any of these words ... JavaScript will always interpret that line break as a semicolon.
... The second exception involves the ++ and -- operators ... If you want to use either of these operators as postfix operators, they must appear on the same line as the expression they apply to. Otherwise, the line break will be treated as a semicolon, and the ++ or -- will be parsed as a prefix operator applied to the code that follows. Consider this code, for example:
x
++
y
It is parsed as
x; ++y;
, not asx++; y
So I think to simplify it, that means:
In general, JavaScript will treat it as continuation of code as long as it makes sense -- except 2 cases: (1) after some keywords like return
, break
, continue
, and (2) if it sees ++
or --
on a new line, then it will add the ;
at the end of the previous line.
The part about "treat it as continuation of code as long as it makes sense" makes it feel like regular expression's greedy matching.
With the above said, that means for return
with a line break, the JavaScript interpreter will insert a ;
(quoted again: If a line break appears after any of these words [such as return
] ... JavaScript will always interpret that line break as a semicolon)
and due to this reason, the classic example of
return
{
foo: 1
}
will not work as expected, because the JavaScript interpreter will treat it as:
return; // returning nothing
{
foo: 1
}
There has to be no line-break immediately after the return
:
return {
foo: 1
}
for it to work properly. And you may insert a ;
yourself if you were to follow the rule of using a ;
after any statement:
return {
foo: 1
};
It is the directory from where you run the command to execute your batch file.
As mentioned in the above answers you can add the below command to your script to verify:
> set current_dir=%cd%
> echo %current_dir%
Before I happened to find this thread, I had the same problem. I had user dependant column types, so I wrote a for
loop going through them and getting needed columns scale
'd. There are probably better ways to do it, but this solved the problem just fine:
for(i in 1:length(colnames(df))) {
if(class(df[,i]) == "numeric" || class(df[,i]) == "integer") {
df[,i] <- as.vector(scale(df[,i])) }
}
as.vector
is a needed part, because it turned out scale
does rownames x 1
matrix which is usually not what you want to have in your data.frame
.
Create a class Language
public class Language
{
public string Name{get;set;}
public string Value{get;set;}
public override string ToString() { return this.Name;}
}
Then, add as many language to the combobox that you want:
yourCombobox.Items.Add(new Language{Name="English",Value="En"});
Okay so ideal permissions look like this
For ssh directory (You can get this by typing ls -ld ~/.ssh/
)
drwx------ 2 oroborus oroborus 4096 Nov 28 12:05 /home/oroborus/.ssh/
d means directory, rwx means the user oroborus has read write and execute permission. Here oroborus is my computer name, you can find yours by echoing $USER. The second oroborus is actually the group. You can read more about what does each field mean here. It is very important to learn this because if you are working on ubuntu/osx or any Linux distro chances are you will encounter it again.
Now to make your permission look like this, you need to type
sudo chmod 700 ~/.ssh
7 in binary is 111 which means read 1 write 1 and execute 1, you can decode 6 by similar logic means only read-write permissions
You have given your user read write and execute permissions. Make sure your file permissions look like this.
total 20
-rw------- 1 oroborus oroborus 418 Nov 8 2014 authorized_keys
-rw------- 1 oroborus oroborus 34 Oct 19 14:25 config
-rw------- 1 oroborus oroborus 1679 Nov 15 2015 id_rsa
-rw------- 1 oroborus oroborus 418 Nov 15 2015 id_rsa.pub
-rw-r--r-- 1 oroborus root 222 Nov 28 12:12 known_hosts
You have given here read-write permission to your user here for all files.
You can see this by typing ls -l ~/.ssh/
This issue occurs because ssh is a program is trying to write to a file called known_hosts in its folder. While writing if it knows that it doesn't have sufficient permissions it will not write in that file and hence fail. This is my understanding of the issue, more knowledgeable people can throw more light in this. Hope it helps
First, checkout to your Branch3:
git checkout Branch3
Then merge the Branch1:
git merge Branch1
And if you want the updated commits of Branch1 on Branch2, you are probaly looking for git rebase
git checkout Branch2
git rebase Branch1
This will update your Branch2 with the latest updates of Branch1.
Here is a universal approach for registering cells in UITableView
:
protocol Reusable {
static var reuseID: String { get }
}
extension Reusable {
static var reuseID: String {
return String(describing: self)
}
}
extension UITableViewCell: Reusable { }
extension UITableView {
func register<T: UITableViewCell>(cellClass: T.Type = T.self) {
let bundle = Bundle(for: cellClass.self)
if bundle.path(forResource: cellClass.reuseID, ofType: "nib") != nil {
let nib = UINib(nibName: cellClass.reuseID, bundle: bundle)
register(nib, forCellReuseIdentifier: cellClass.reuseID)
} else {
register(cellClass.self, forCellReuseIdentifier: cellClass.reuseID)
}
}
Explanation:
Reusable
protocol generates cell ID from its class name. Make sure you follow the convention: cell ID == class name == nib name
.UITableViewCell
conforms to Reusable
protocol.UITableView
extension abstracts away the difference in registering cells via nib or class.Usage example:
override func viewDidLoad() {
super.viewDidLoad()
let tableView = UITableView()
let cellClasses: [UITableViewCell.Type] = [PostCell.self, ProfileCell.self, CommentCell.self]
cellClasses.forEach(tableView.register)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: PostCell.self.reuseID) as? PostCell
...
return cell
}
I had the same problem. My issue was that I have to change to the Node.js project directory on the command line before installing express.
cd /Users/feelexit/WebstormProjects/learnnode/node_modules/
Here you go: Here you go: Create a System Restore Point. Log on under an admin account. Delete the folder C:\SomeUser. Move the folder c:\Users\SomeUser so that it becomes c:\SomeUser. Open the registry editor. Navigate to HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList. Search for "ProfileImagePath" until you find the one that points at c:\Users\SomeUser. Modify it so that it points at c:\SomeUser. Use System Restore in case things go wrong.
I ran into the same issue. I had created another component with the same name under a different folder. so in my app module I had to import both components but with a trick
import {DuplicateComponent as AdminDuplicateComponent} from '/the/path/to/the/component';
Then in declarations I could add AdminDuplicateComponent instead.
Just thought that I would leave that there for future reference.
It can be complicated to compute a diff in your head from the different sections in $MERGED and apply that. In my setup, meld helps by showing you these diffs visually, using:
[merge]
tool = mymeld
conflictstyle = diff3
[mergetool "mymeld"]
cmd = meld --diff $BASE $REMOTE --diff $REMOTE $LOCAL --diff $LOCAL $MERGED
It looks strange but offers a very convenient work-flow, using three tabs:
in tab 1 you see (from left to right) the change that you should make in tab 2 to solve the merge conflict.
in the right side of tab 2 you apply the "change that you should make" and copy the entire file contents to the clipboard (using ctrl-a and ctrl-c).
in tab 3 replace the right side with the clipboard contents. If everything is correct, you will now see - from left to right - the same change as shown in tab 1 (but with different contexts). Save the changes made in this tab.
Notes:
Use DecimalFormat
NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
DecimalFormat decimalFormatter = (DecimalFormat) nf;
decimalFormatter.applyPattern("#,###,###.##");
String fString = decimalFormatter.format(myDouble);
System.out.println(fString);
I solved this problem by first verifying the that remote did not have anything checked out (it really was not supposed to), and then made it bare with:
$ git config --bool core.bare true
After that git push worked fine.
Just in case you're using bootstrap 4, you can add px-0
(set left/right padding to 0) and mx-0
(set left/right margin to 0) CSS class to body tag, like below:
<body class="px-0; mx-0">
<!--your body HTML-->
</body>
Change the REGEXP
to Like
SELECT * FROM table_name WHERE column_name like '%[^a-zA-Z0-9]%'
this one works fine
JFrame.setIconImage(Image image)
pretty standard.
run configuration -> arguments -> vm arguments
(can also be placed in the debug configuration under Debug Configuration->Arguments->VM Arguments)
Yes, you can do it with such a code:
l = [[float(y) for y in x] for x in l]
/* The algorithm is from the book "Discrete Mathematics and Its
Applications 5th Edition" by Kenneth H. Rosen.
(base^exp)%mod
*/
int modular(int base, unsigned int exp, unsigned int mod)
{
int x = 1;
int power = base % mod;
for (int i = 0; i < sizeof(int) * 8; i++) {
int least_sig_bit = 0x00000001 & (exp >> i);
if (least_sig_bit)
x = (x * power) % mod;
power = (power * power) % mod;
}
return x;
}
Select the block of code that you want indented.
Right-click (or, on Mac, Ctrl-click).
Structure → Re-indent
Edit: As described in this answer, newer versions of MacOS now have native support for rebinding Caps Lock to Escape. Thus it is no longer necessary to install third-party software to achieve this.
Here's my attempt at a comprehensive, visual walk-through answer (with links) of how to achieve this using Seil (formerly known as PCKeyboardHack
).
In the popup dialog set Caps Lock Key to No Action
:
2) Now, click here to download Seil and install it:
3) After the installation you will have a new Application installed ( Mountain Lion and newer ) and if you are on an older OS you may have to check for a new System Preferences pane:
4) Check the box that says "Change Caps Lock" and enter "53" as the code for the escape key:
And you're done! If it doesn't work immediately, you may need to restart your machine.
You may also want to check out KeyRemap4MacBook which is actually the flagship keyboard remapping tool from pqrs.org
- it's also free.
If you like these tools you can make a donation. I have no affiliation with them but I've been using these tools for a long time and have to say the guys over there have been doing an excellent job maintaining these, adding features and fixing bugs.
Here's a screenshot to show a few of the (hundreds of) pre-selectable options:
PQRS also has a great utility called NoEjectDelay that you can use in combination with KeyRemap4MacBook for reprogramming the Eject key. After a little tweaking I have mine set to toggle the AirPort Wifi.
These utilities offer unlimited flexibility when remapping the Mac keyboard. Have fun!
You want to read raw lines to avoid problems with backslashes in the input (use -r
):
while read -r line; do
printf "<%s>\n" "$line"
done < file.txt
This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in
while IFS= read -r line; do
printf "%s\n" "$line"
done < file.txt
This now is an equivalent of cat < file.txt
as long as file.txt
ends with a newline.
Note that you must double quote "$line"
in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.
Well, if you're reading the data in as a list, just do np.array(map(float, list_of_strings))
(or equivalently, use a list comprehension). (In Python 3, you'll need to call list
on the map
return value if you use map
, since map
returns an iterator now.)
However, if it's already a numpy array of strings, there's a better way. Use astype()
.
import numpy as np
x = np.array(['1.1', '2.2', '3.3'])
y = x.astype(np.float)
Cohesion is an indication of the relative functional strength of a module.
?Conventional view:
the “single-mindedness” of a module
?OO view:
?cohesion implies that a component or class encapsulates only attributes and operations that are closely related to one another and to the class or component itself
?Levels of cohesion
?Functional
?Layer
?Communicational
?Sequential
?Procedural
?Temporal
?utility
Coupling is an indication of the relative interdependence among modules.
Coupling depends on the interface complexity between modules, the point at which entry or reference is made to a module, and what data pass across the interface.
Conventional View : The degree to which a component is connected to other components and to the external world
OO view: a qualitative measure of the degree to which classes are connected to one another
Level of coupling
?Content
?Common
?Control
?Stamp
?Data
?Routine call
?Type use
?Inclusion or import
?External #
It may be easier to use XPath to locate the nodes that you wish to delete. This stackoverflow thread might give you some ideas.
In your case you will find the four nodes that you want using this expression:
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
Huffman Coding might help, but only if you have a lot of frequent characters in your small String
Select "all project" and right click
Maven-> Update project
You can use Files#readAllLines()
to get all lines of a text file into a List<String>
.
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
// ...
}
Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files
You can use String#split()
to split a String
in parts based on a regular expression.
for (String part : line.split("\\s+")) {
// ...
}
Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String
You can use Integer#valueOf()
to convert a String
into an Integer
.
Integer i = Integer.valueOf(part);
Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings
You can use List#add()
to add an element to a List
.
numbers.add(i);
Tutorial: Interfaces > The List Interface
So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).
List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
for (String part : line.split("\\s+")) {
Integer i = Integer.valueOf(part);
numbers.add(i);
}
}
If you happen to be at Java 8 already, then you can even use Stream API for this, starting with Files#lines()
.
List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
.map(line -> line.split("\\s+")).flatMap(Arrays::stream)
.map(Integer::valueOf)
.collect(Collectors.toList());
Tutorial: Processing data with Java 8 streams
One way around this problem is to use stored procedures with an output parameter.
exec sp_mysprocname @returnvalue output, @firstparam = 1, @secondparam=2
values you do not pass in default to the defaults set in the stored procedure itself. And you can get the results from your output variable.
I prefer using the following code to generate a decimal number up to fist decimal point. you can copy paste the 3rd line to add more numbers after decimal point by appending that number in string "combined". You can set the minimum and maximum value by changing the 0 and 9 to your preferred value.
Random r = new Random();
string beforePoint = r.Next(0, 9).ToString();//number before decimal point
string afterPoint = r.Next(0,9).ToString();//1st decimal point
//string secondDP = r.Next(0, 9).ToString();//2nd decimal point
string combined = beforePoint+"."+afterPoint;
decimalNumber= float.Parse(combined);
Console.WriteLine(decimalNumber);
I hope that it helped you.
Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.
For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.
IntelliJ IDEA 14+
Show diagram popup
Right click on a type/class/package > Diagrams > Show Diagram Popup...
or
Ctrl+Alt+U
Show diagram (opens a new tab)
Right click on a type/class/package > Diagrams > Show Diagram...
or
Ctrl+Alt+Shift+U
By default, you see only the classes/interfaces names. If you want to see more details, go to File > Settings... > Tools > Diagrams and check what you want (E.g.: Fields, Methods, etc.)
P.S.: You need IntelliJ IDEA Ultimate, because this feature is not supported in Community Edition. If you go to File > Settings... > Plugins, you can see that there is not UML Support plugin in Community Edition.
Now you must have API key. You can generate that in google developer console. Here is LINK to the explanation.
If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:
Dictionary<string, ArrayList> result = target.GetComponents()
.ToDictionary(x => x.Key, x => x.Value);
There's no such thing as an IEnumerable<T1, T2>
but a KeyValuePair<TKey, TValue>
is fine.
You can also use the getJSON function:
$.getJSON('/your/script.php', function(data) {
$.each(data, function(index) {
alert(data[index].TEST1);
alert(data[index].TEST2);
});
});
This is really just a rewording of ifesdjeen's answer, but I thought it might be helpful to people.
You need to use the val()
function to get the textbox value. text
does not exist as a property only as a function and even then its not the correct function to use in this situation.
var from = $("input#fromAddress").val()
val()
is the standard function for getting the value of an input.
The problem is the location of the index file (index.php).You must create a symbolic link in the root of the project to public/index.php with the command "ln-s public/index.php index.php"
SQL Server does not have literal true or false values. You'll need to use the 1=1
method (or similar) in the rare cases this is needed.
One option is to create your own named variables for true and false
DECLARE @TRUE bit
DECLARE @FALSE bit
SET @TRUE = 1
SET @FALSE = 0
select * from SomeTable where @TRUE = @TRUE
But these will only exist within the scope of the batch (you'll have to redeclare them in every batch in which you want to use them)
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
In a Batch File you MUST use %%
instead of %
: (Type help for
)
for /F "tokens=1,2,3" %%i in (myfile.txt) do call :process %%i %%j %%k
goto thenextstep
:process
set VAR1=%1
set VAR2=%2
set VAR3=%3
COMMANDS TO PROCESS INFORMATION
goto :EOF
What this does: The "do call :process %%i %%j %%k" at the end of the for command passes the information acquired in the for command from myfile.txt to the "process" 'subroutine'.
When you're using the for command in a batch program, you need to use double % signs for the variables.
The following lines pass those variables from the for command to the process 'sub routine' and allow you to process this information.
set VAR1=%1
set VAR2=%2
set VAR3=%3
I have some pretty advanced uses of this exact setup that I would be willing to share if further examples are needed. Add in your EOL or Delims as needed of course.
%timeit
is an ipython magic function, which can be used to time a particular piece of code (A single execution statement, or a single method).
From the docs:
%timeit
Time execution of a Python statement or expression Usage, in line mode: %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
To use it, for example if we want to find out whether using xrange
is any faster than using range
, you can simply do:
In [1]: %timeit for _ in range(1000): True
10000 loops, best of 3: 37.8 µs per loop
In [2]: %timeit for _ in xrange(1000): True
10000 loops, best of 3: 29.6 µs per loop
And you will get the timings for them.
The major advantage of %timeit
are:
that you don't have to import timeit.timeit
from the standard library, and run the code multiple times to figure out which is the better approach.
%timeit will automatically calculate number of runs required for your code based on a total of 2 seconds execution window.
You can also make use of current console variables without passing the whole code snippet as in case of timeit.timeit
to built the variable that is built in an another environment that timeit works.
If you can save the workbook then you have the option to use ADO and Jet/ACE to treat the workbook as a database, and execute SQL against the sheet.
The MSDN information on how to hit Excel using ADO can be found here.
jQuery <1.9
$('#inputId').attr('readonly', true);
jQuery 1.9+
$('#inputId').prop('readonly', true);
Read more about difference between prop and attr
By combining all the given answers, this method should work on all environments:
public static void clearConsole() {
try {
if (System.getProperty("os.name").contains("Windows")) {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
else {
System.out.print("\033\143");
}
} catch (IOException | InterruptedException ex) {}
}
If you're already using the tidyverse, there are a few solution depending on the exact situation.
Basic if you know it's all numbers and doesn't have NAs
library(dplyr)
# solution
dataset %>% mutate_if(is.character,as.numeric)
Test cases
df <- data.frame(
x1 = c('1','2','3'),
x2 = c('4','5','6'),
x3 = c('1','a','x'), # vector with alpha characters
x4 = c('1',NA,'6'), # numeric and NA
x5 = c('1',NA,'x'), # alpha and NA
stringsAsFactors = F)
# display starting structure
df %>% str()
Convert all character vectors to numeric (could fail if not numeric)
df %>%
select(-x3) %>% # this removes the alpha column if all your character columns need converted to numeric
mutate_if(is.character,as.numeric) %>%
str()
Check if each column can be converted. This can be an anonymous function. It returns FALSE
if there is a non-numeric or non-NA character somewhere. It also checks if it's a character vector to ignore factors. na.omit removes original NAs before creating "bad" NAs.
is_all_numeric <- function(x) {
!any(is.na(suppressWarnings(as.numeric(na.omit(x))))) & is.character(x)
}
df %>%
mutate_if(is_all_numeric,as.numeric) %>%
str()
If you want to convert specific named columns, then mutate_at is better.
df %>% mutate_at('x1', as.numeric) %>% str()