I am talking here from a theoretical point of view; I have not tried BitLocker.
BitLocker uses AES encryption with a 128-bit key. On a Core2 machine, clocked at 2.53 GHz, encryption speed should be about 110 MB/s, using one core. The two cores could process about 220 MB/s, assuming perfect data transfer and core synchronization with no overhead, and that nothing requires the CPU in the same time (that one hell of an assumption, actually). The X25-M G2 is announced at 250 MB/s read bandwidth (that's what the specs say), so, in "ideal" conditions, BitLocker necessarily involves a bit of a slowdown.
However read bandwidth is not that important. It matters when you copy huge files, which is not something that you do very often. In everyday work, access time is much more important: as a developer, you create, write, read and delete many files, but they are all small (most of them are much smaller than one megabyte). This is what makes SSD "snappy". Encryption does not impact access time. So my guess is that any performance degradation will be negligible(*).
(*) Here I assume that Microsoft's developers did their job properly.
To change your app font follow the following steps:
res
directory create a new directory and name it font
.res
-> values
-> styles.xml
inside <resources>
-> <style>
add your font <item name="android:fontFamily">@font/font_name</item>
.Now all your app text should be in the font that you add.
Adding manifest.file=manifest.mf into project.properties and creating manifest.mf file in the project directory works fine in NB 6.9 and should work also in NB 6.8.
You can use the v$sql_monitor view to find queries that are running longer than 5 seconds. This may only be available in Enterprise versions of Oracle. For example this query will identify slow running queries from my TEST_APP service:
select to_char(sql_exec_start, 'dd-Mon hh24:mi'), (elapsed_time / 1000000) run_time,
cpu_time, sql_id, sql_text
from v$sql_monitor
where service_name = 'TEST_APP'
order by 1 desc;
Note elapsed_time is in microseconds so / 1000000 to get something more readable
When you define a as unicode, the chars a and á are equal. Otherwise á counts as two chars. Try len(a) and len(au). In addition to that, you may need to have the encoding when you work with other environments. For example if you use md5, you get different values for a and ua
Just go to your fragment Activity and remove all method.....instead on on createview method.
your fragment has only on method oncreateview that's it.
//only this method implement other method delete
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
and make sure your layout it is demo for u.
I agree with @Lukasz Rzanek that we can use git plugin
But, I use option: checkout to a sub-direction what is enable as follow:
In Source Code Management, tick Git
click add button, choose checkout to a sub-directory
I've forgot to add the PostgreSQL JDBC Driver into my project (Mvnrepository).
Gradle:
// http://mvnrepository.com/artifact/postgresql/postgresql
compile group: 'postgresql', name: 'postgresql', version: '9.0-801.jdbc4'
Maven:
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.0-801.jdbc4</version>
</dependency>
You can also download the JAR and import to your project manually.
If the week number is in A1
and the year in A2
, you can try:
A1*7+DATE(A2,1,1)
The well-established "pattern" for reverse-iterating through closed-open ranges looks as follows
// Iterate over [begin, end) range in reverse
for (iterator = end; iterator-- != begin; ) {
// Process `*iterator`
}
or, if you prefer,
// Iterate over [begin, end) range in reverse
for (iterator = end; iterator != begin; ) {
--iterator;
// Process `*iterator`
}
This pattern is useful, for example, for reverse-indexing an array using an unsigned index
int array[N];
...
// Iterate over [0, N) range in reverse
for (unsigned i = N; i-- != 0; ) {
array[i]; // <- process it
}
(People unfamiliar with this pattern often insist on using signed integer types for array indexing specifically because they incorrectly believe that unsigned types are somehow "unusable" for reverse indexing)
It can be used for iterating over an array using a "sliding pointer" technique
// Iterate over [array, array + N) range in reverse
for (int *p = array + N; p-- != array; ) {
*p; // <- process it
}
or it can be used for reverse-iteration over a vector using an ordinary (not reverse) iterator
for (vector<my_class>::iterator i = my_vector.end(); i-- != my_vector.begin(); ) {
*i; // <- process it
}
I think .myi you can repair from inside mysql.
If you see these type of error messages from MySQL: Database failed to execute query (query) 1016: Can't open file: 'sometable.MYI'. (errno: 145) Error Msg: 1034: Incorrect key file for table: 'sometable'. Try to repair it thenb you probably have a crashed or corrupt table.
You can check and repair the table from a mysql prompt like this:
check table sometable;
+------------------+-------+----------+----------------------------+
| Table | Op | Msg_type | Msg_text |
+------------------+-------+----------+----------------------------+
| yourdb.sometable | check | warning | Table is marked as crashed |
| yourdb.sometable | check | status | OK |
+------------------+-------+----------+----------------------------+
repair table sometable;
+------------------+--------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+------------------+--------+----------+----------+
| yourdb.sometable | repair | status | OK |
+------------------+--------+----------+----------+
and now your table should be fine:
check table sometable;
+------------------+-------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+------------------+-------+----------+----------+
| yourdb.sometable | check | status | OK |
+------------------+-------+----------+----------+
One can also receive this error if using the new (so far webkit only) notification feature before getting permission.
First run:
<!-- Get permission -->
<button onclick="webkitNotifications.requestPermission();">Enable Notifications</button>
Later run:
// Display Notification:
window.webkitNotifications.createNotification('image', 'Title', 'Body').show();
The request permission functions needs to be triggered from an event caused by the user, otherwise it won't be displayed.
echo $(($(date +%s) / 60 / 60 / 24))
You can use filter .
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
HttpServletRequest test1= (HttpServletRequest) arg0;
test1.getRequestURL()); it gives http://localhost:8081/applicationName/menu/index.action
test1.getRequestURI()); it gives applicationName/menu/index.action
String pathname = test1.getServletPath()); it gives //menu/index.action
if(pathname.equals("//menu/index.action")){
arg2.doFilter(arg0, arg1); // call to urs servlet or frameowrk managed controller method
// in resposne
HttpServletResponse httpResp = (HttpServletResponse) arg1;
RequestDispatcher rd = arg0.getRequestDispatcher("another.jsp");
rd.forward(arg0, arg1);
}
donot forget to put <dispatcher>FORWARD</dispatcher>
in filter mapping in web.xml
You can check all value items are true or false by compare your array with the other boolean array via Arrays.equal
method like below example :
private boolean isCheckedAnswer(List<Answer> array) {
boolean[] isSelectedChecks = new boolean[array.size()];
for (int i = 0; i < array.size(); i++) {
isSelectedChecks[i] = array.get(i).isChecked();
}
boolean[] isAllFalse = new boolean[array.size()];
for (int i = 0; i < array.size(); i++) {
isAllFalse[i] = false;
}
return !Arrays.equals(isSelectedChecks, isAllFalse);
}
Never trust user data.
function clean_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
The trim()
function removes whitespace and other predefined characters from both sides of a string.
The stripslashes()
function removes backslashes
The htmlspecialchars()
function converts some predefined characters to HTML entities.
The predefined characters are:
& (ampersand) becomes &
" (double quote) becomes "
' (single quote) becomes '
< (less than) becomes <
> (greater than) becomes >
TRY
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings
EnableAutoProxyResultCache = dword: 0
The main consideration that others are neglecting is that OP has stated that they cannot modify the HTML.
You can target what you need in the DOM then add classes dynamically with javascript. Then style as you need.
In an example that I made, I targeted all <p>
elements with jQuery and wrapped it with a div with a class of "colored"
$( "p" ).wrap( "<div class='colored'></div>" );
Then in my CSS i targeted the <p>
and gave it the background color and changed to display: inline
.colored p {
display: inline;
background: green;
}
By setting the display to inline you lose some of the styling that it would normally inherit. So make sure that you target the most specific element and style the container to fit the rest of your design. This is just meant as a working starting point. Use carefully. Working demo on CodePen
Do you have a yellow icon like this [_] at the bottom of the main window? It is a "type-aware highlighting" switch which could be disabled accidentally. You should re-enable it by clicking on the icon.
How about something like
;WITH DistinctVals AS (
SELECT distinct id
FROM table
where fid = 64
)
SELECT id,
ROW_NUMBER() OVER (ORDER BY id) AS RowNum
FROM DistinctVals
You could also try
SELECT distinct id, DENSE_RANK() OVER (ORDER BY id) AS RowNum
FROM @mytable
where fid = 64
A Scala version based on Zaz's answer.
case class DocumentEx(document: Document) {
def toXmlString(pretty: Boolean = false):Try[String] = {
getStringFromDocument(document, pretty)
}
}
implicit def documentToDocumentEx(document: Document):DocumentEx = {
DocumentEx(document)
}
def getStringFromDocument(doc: Document, pretty:Boolean): Try[String] = {
try
{
val domSource= new DOMSource(doc)
val writer = new StringWriter()
val result = new StreamResult(writer)
val tf = TransformerFactory.newInstance()
val transformer = tf.newTransformer()
if (pretty)
transformer.setOutputProperty(OutputKeys.INDENT, "yes")
transformer.transform(domSource, result)
Success(writer.toString);
}
catch {
case ex: TransformerException =>
Failure(ex)
}
}
With that, you can do either doc.toXmlString()
or call the getStringFromDocument(doc)
function.
Convert the Date to String and do it with SimpleDateFormat.
SimpleDateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
readFormat.setTimeZone(TimeZone.getTimeZone("GMT" + timezoneOffset));
String dateStr = readFormat.format(date);
SimpleDateFormat writeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = writeFormat.parse(dateStr);
assume series s
s = pd.Series(np.arange(100))
Get quantiles for [.1, .2, .3, .4, .5, .6, .7, .8, .9]
s.quantile(np.linspace(.1, 1, 9, 0))
0.1 9.9
0.2 19.8
0.3 29.7
0.4 39.6
0.5 49.5
0.6 59.4
0.7 69.3
0.8 79.2
0.9 89.1
dtype: float64
OR
s.quantile(np.linspace(.1, 1, 9, 0), 'lower')
0.1 9
0.2 19
0.3 29
0.4 39
0.5 49
0.6 59
0.7 69
0.8 79
0.9 89
dtype: int32
I can recommend using Obfuscator.
In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.
If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line
git config core.autocrlf true
If you want to make an intelligent decision how git should handle this, read the documentation
Here is a snippet
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:
$ git config --global core.autocrlf true
If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
$ git config --global core.autocrlf input
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:
$ git config --global core.autocrlf false
As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:
<p>Hello</p>
<p><?= _("World"); ?></p>
First Method: (Tested)
Code in .aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
if (!Page.IsPostBack)
{
ddl.Attributes.Add("onchange", "CalcTotalAmt();");
}
}
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
//Your Code
}
JavaScript function: return true from your JS function
function CalcTotalAmt()
{
//Your Code
}
.aspx code:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true">
<asp:ListItem Text="a" Value="a"></asp:ListItem>
<asp:ListItem Text="b" Value="b"></asp:ListItem>
</asp:DropDownList>
Second Method: (Tested)
Code in .aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["__EVENTARGUMENT"] != null && Request.Params["__EVENTARGUMENT"].Equals("ddlchange"))
ddl_SelectedIndexChanged(sender, e);
if (!Page.IsPostBack)
{
ddl.Attributes.Add("onchange", "CalcTotalAmt();");
}
}
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
//Your Code
}
JavaScript function: return true from your JS function
function CalcTotalAmt() {
//Your Code
__doPostBack("ctl00$MainContent$ddl","ddlchange");
}
.aspx code:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true">
<asp:ListItem Text="a" Value="a"></asp:ListItem>
<asp:ListItem Text="b" Value="b"></asp:ListItem>
</asp:DropDownList>
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/***
*
* @author Vaquar khan
*
*
*/
public class AES {
private static SecretKeySpec secretKey;
private static final String VK_secretKey = "VaquarKhan-secrate-key!!!!";
private static byte[] key;
/**
*
* @param myKey
*/
public static void setKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* encrypt
* @param strToEncrypt
* @param secret
* @return
*/
public static String encrypt(String strToEncrypt, String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
/**
* decrypt
* @param strToDecrypt
* @param secret
* @return
*/
public static String decrypt(String strToDecrypt, String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
public static void main(String[] args) {
final String secretKey = VK_secretKey;
String password = "VKhan@12";
//
String encryptedString = AES.encrypt(password, secretKey);
String decryptedString = AES.decrypt(encryptedString, secretKey);
//
System.out.println(password);
System.out.println(encryptedString);
System.out.println(decryptedString);
}
}
When you install python for Windows, use the standard option or install everything it asks. I got the error because I deselected tcl.
You can consider using a very small, dependency-free library like Not. Solves all problems:
// at the basic level it supports primitives
let number = 10
let array = []
not('number', 10) // returns false
not('number', []) // throws error
// so you need to define your own:
let not = Object.create(Not)
not.defineType({
primitive: 'number',
type: 'integer',
pass: function(candidate) {
// pre-ECMA6
return candidate.toFixed(0) === candidate.toString()
// ECMA6
return Number.isInteger(candidate)
}
})
not.not('integer', 4.4) // gives error message
not.is('integer', 4.4) // returns false
not.is('integer', 8) // returns true
If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.
function test (string, boolean) {
// any of these below will throw errors to protect you
not('string', string)
not('boolean', boolean)
// continue with your code.
}
It's been a while since I posted this question, but considering the views this still seems to get, here's another solution I've come upon during these last few months:
$scope.safeApply = function( fn ) {
var phase = this.$root.$$phase;
if(phase == '$apply' || phase == '$digest') {
if(fn) {
fn();
}
} else {
this.$apply(fn);
}
};
The above code basically creates a function called safeApply
that calles the $apply
function (as stated in Arun's answer) if and only Angular currently isn't going through the $digest
stage. On the other hand, if Angular is currently digesting things, it will just execute the function as it is, since that will be enough to signal to Angular to make the changes.
Numerous errors occur when trying to use the $apply
function while AngularJs is currently in its $digest
stage. The safeApply
code above is a safe wrapper to prevent such errors.
(note: I personally like to chuck in safeApply
as a function of $rootScope
for convenience purposes)
Example:
function change() {
alert("a");
var scope = angular.element($("#outer")).scope();
scope.safeApply(function(){
scope.msg = 'Superhero';
})
}
HTML:
<button onclick="render()">Render</button>
<canvas id="myCanvas" height="100" width="100" style="object-fit:contain;"></canvas>
CSS:
canvas {
width: 400px;
height: 200px;
border: 1px solid red;
display: block;
}
Javascript:
const myCanvas = document.getElementById("myCanvas");
const originalHeight = myCanvas.height;
const originalWidth = myCanvas.width;
render();
function render() {
let dimensions = getObjectFitSize(
true,
myCanvas.clientWidth,
myCanvas.clientHeight,
myCanvas.width,
myCanvas.height
);
myCanvas.width = dimensions.width;
myCanvas.height = dimensions.height;
let ctx = myCanvas.getContext("2d");
let ratio = Math.min(
myCanvas.clientWidth / originalWidth,
myCanvas.clientHeight / originalHeight
);
ctx.scale(ratio, ratio); //adjust this!
ctx.beginPath();
ctx.arc(50, 50, 50, 0, 2 * Math.PI);
ctx.stroke();
}
// adapted from: https://www.npmjs.com/package/intrinsic-scale
function getObjectFitSize(
contains /* true = contain, false = cover */,
containerWidth,
containerHeight,
width,
height
) {
var doRatio = width / height;
var cRatio = containerWidth / containerHeight;
var targetWidth = 0;
var targetHeight = 0;
var test = contains ? doRatio > cRatio : doRatio < cRatio;
if (test) {
targetWidth = containerWidth;
targetHeight = targetWidth / doRatio;
} else {
targetHeight = containerHeight;
targetWidth = targetHeight * doRatio;
}
return {
width: targetWidth,
height: targetHeight,
x: (containerWidth - targetWidth) / 2,
y: (containerHeight - targetHeight) / 2
};
}
Basically, canvas.height/width sets the size of the bitmap you are rendering to. The CSS height/width then scales the bitmap to fit the layout space (often warping it as it scales it). The context can then modify it's scale to draw, using vector operations, at different sizes.
Heres's a solution in ES6/ES2015 using a functional-style approach:
const typeOf = x =>
({}).toString
.call(x)
.match(/\[object (\w+)\]/)[1]
function areSimilar(a, b) {
const everyKey = f => Object.keys(a).every(f)
switch(typeOf(a)) {
case 'Array':
return a.length === b.length &&
everyKey(k => areSimilar(a.sort()[k], b.sort()[k]));
case 'Object':
return Object.keys(a).length === Object.keys(b).length &&
everyKey(k => areSimilar(a[k], b[k]));
default:
return a === b;
}
}
Without more detail of what you are trying to accomplish, we are kinda guessing. But you might be able to get away with using object notation to do something like this...
var myFuncs = {
firstFunc: function(string) {
// do something
},
secondFunc: function(string) {
// do something
},
thirdFunc: function(string) {
// do something
}
}
and to call one of them...
myFuncs.firstFunc('a string')
Sun just likes changing the names of things for no apparent reason. Look at the three different numbering schemes for SunOS/Solaris, or the two numbering schemes for Java. Is is Java 1.6, Java 2 Version 6, or Java 6?
I think I have a way where you may not get exactly get what you want, but you can integrate Morgan's logging with log4js -- in other words, all your logging activity can go to the same place. I hope this digest from an Express server is more or less self-explanatory:
var express = require("express");
var log4js = require("log4js");
var morgan = require("morgan");
...
var theAppLog = log4js.getLogger();
var theHTTPLog = morgan({
"format": "default",
"stream": {
write: function(str) { theAppLog.debug(str); }
}
});
....
var theServer = express();
theServer.use(theHTTPLog);
Now you can write whatever you want to theAppLog and Morgan will write what it wants to the same place, using the same appenders etc etc. Of course, you can call info() or whatever you like in the stream wrapper instead of debug() -- that just reflects the logging level you want to give to Morgan's req/res logging.
There is another issue you have to take care of it when you try mapping column which is string length,
for example TK_NO nvarchar(50)
you will have to map to
the same length as the destination field.
map()
doesn't return a list, it returns a map
object.
You need to call list(map)
if you want it to be a list again.
Even better,
from itertools import imap
payIntList = list(imap(int, payList))
Won't take up a bunch of memory creating an intermediate object, it will just pass the ints
out as it creates them.
Also, you can do if choice.lower() == 'n':
so you don't have to do it twice.
Python supports +=
: you can do payIntList[i] += 1000
and numElements += 1
if you want.
If you really want to be tricky:
from itertools import count
for numElements in count(1):
payList.append(raw_input("Enter the pay amount: "))
if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
break
and / or
for payInt in payIntList:
payInt += 1000
print payInt
Also, four spaces is the standard indent amount in Python.
people.OrderBy(person => person.lastname).ToList();
To know the react version, Open package.json file in root folder, search the keywork react. You will see like "react": "^16.4.0",
To expand on the existing great answers, a very simple way to get a great looking terminal is to use the open source Dotfiles project.
https://github.com/mathiasbynens/dotfiles
Installation is dead simple on OSX and Linux. Run the following command in Terminal.
git clone https://github.com/mathiasbynens/dotfiles.git && cd dotfiles && source bootstrap.sh
This is going to:
cd
into the folder.I apologize for resurecting this old thread, but I just wanted to let everyone know there is a very close Bootstrap like CSS framework specifically created for email styling, here is the link: http://zurb.com/ink/
Hope it helps someone.
Ninja edit: It has since been renamed to Foundation for Emails
and the new link is: https://foundation.zurb.com/emails.html
Silent but deadly edit: New link https://get.foundation/emails.html
Just use a related field without setting many=True
.
Note that also because you want the output named category_name
, but the actual field is category
, you need to use the source
argument on the serializer field.
The following should give you the output you need...
class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.RelatedField(source='category', read_only=True)
class Meta:
model = Item
fields = ('id', 'name', 'category_name')
Real example:
var trackList = Model.TrackingHistory.GroupBy(x => x.ShipmentStatusId).Select(x => x.Last()).Reverse();
List<int> done_step1 = new List<int>() {2,3,4,5,6,7,8,9,10,11,14,18,21,22,23,24,25,26 };
bool isExists = trackList.Where(x => done_step1.Contains(x.ShipmentStatusId.Value)).FirstOrDefault() != null;
Using List<T>
you can prevent casting errors. It is very useful to avoid a runtime casting error.
Example:
Here (using ArrayList
) you can compile this code but you will see an execution error later.
ArrayList array1 = new ArrayList();
array1.Add(1);
array1.Add("Pony"); //No error at compile process
int total = 0;
foreach (int num in array1)
{
total += num; //-->Runtime Error
}
If you use List
, you avoid these errors:
List<int> list1 = new List<int>();
list1.Add(1);
//list1.Add("Pony"); //<-- Error at compile process
int total = 0;
foreach (int num in list1 )
{
total += num;
}
Reference: MSDN
try this:
In [110]: (df.groupby('Company Name')
.....: .agg({'Organisation Name':'count', 'Amount': 'sum'})
.....: .reset_index()
.....: .rename(columns={'Organisation Name':'Organisation Count'})
.....: )
Out[110]:
Company Name Amount Organisation Count
0 Vifor Pharma UK Ltd 4207.93 5
or if you don't want to reset index:
df.groupby('Company Name')['Amount'].agg(['sum','count'])
or
df.groupby('Company Name').agg({'Amount': ['sum','count']})
Demo:
In [98]: df.groupby('Company Name')['Amount'].agg(['sum','count'])
Out[98]:
sum count
Company Name
Vifor Pharma UK Ltd 4207.93 5
In [99]: df.groupby('Company Name').agg({'Amount': ['sum','count']})
Out[99]:
Amount
sum count
Company Name
Vifor Pharma UK Ltd 4207.93 5
Why not using the grid system?
The bootstrap grid system consist of 12 columns, so if you use the "Medium" columns it will have a 970px width size.
Then you can divide it to 3 columns (12/3=4) so use 3 divs with "col-md-4" class:
<div class="col-md-4"></div>
<div class="col-md-4"></div>
<div class="col-md-4"></div>
Each one will have 323px max width size. Keep the first and the last empty and use the middle one to get your content centerd:
<div class="col-md-4"></div>
<div class="col-md-4">
<p>Centered content.</p>
</div>
<div class="col-md-4"></div>
Use CHAR
:
=Char(34)&"This is in quotes"&Char(34)
Should evaluate to:
"This is in quotes"
This might be due to the fact that you are trying to add a ListBoxItem with a same name to the page.
If you want to refresh the content of the listbox with the newly retrieved values you will have to first manually remove the content of the listbox other wise your loop will try to create lb_1 again and add it to the same list.
Look at here for a similar problem that occured Silverlight: Value does not fall within the expected range exception
Cheers,
The PictureBox.SizeMode options are missing a "fill" or "cover" mode which would be like zoom except with cropping to ensure you're filling the picture box. In CSS it's the "cover" option.
This code should enable that:
static public void fillPictureBox(PictureBox pbox, Bitmap bmp)
{
pbox.SizeMode = PictureBoxSizeMode.Normal;
bool source_is_wider = (float)bmp.Width / bmp.Height > (float)pbox.Width / pbox.Height;
var resized = new Bitmap(pbox.Width, pbox.Height);
var g = Graphics.FromImage(resized);
var dest_rect = new Rectangle(0, 0, pbox.Width, pbox.Height);
Rectangle src_rect;
if (source_is_wider)
{
float size_ratio = (float)pbox.Height / bmp.Height;
int sample_width = (int)(pbox.Width / size_ratio);
src_rect = new Rectangle((bmp.Width - sample_width) / 2, 0, sample_width, bmp.Height);
}
else
{
float size_ratio = (float)pbox.Width / bmp.Width;
int sample_height = (int)(pbox.Height / size_ratio);
src_rect = new Rectangle(0, (bmp.Height - sample_height) / 2, bmp.Width, sample_height);
}
g.DrawImage(bmp, dest_rect, src_rect, GraphicsUnit.Pixel);
g.Dispose();
pbox.Image = resized;
}
string[] result = new string[table.Columns.Count];
DataRow dr = table.Rows[0];
for (int i = 0; i < dr.ItemArray.Length; i++)
{
result[i] = dr[i].ToString();
}
foreach (string str in result)
Console.WriteLine(str);
Besides iftop and iptraf, also check:
bwm-ng
(Bandwidth Monitor Next Generation)and/or
cbm
(Color Bandwidth Meter)ref: http://www.powercram.com/2010/01/bandwidth-monitoring-tools-for-ubuntu.html
I did some research on what happens if you pass a non-string and non-empty/null value to a tester function. As many know, (0 == "") is true in JavaScript, but since 0 is a value and not empty or null, you may want to test for it.
The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, Boolean, objects, expressions, etc.
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this:
String.IsNullOrEmpty = function (value) { ... }
You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // Could be set
myvar.IsNullOrEmpty(); // Throws error
I tested with the following value array. You can loop it through to test your functions if in doubt.
// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
['undefined', undefined],
['(var) z', z],
['null', null],
['empty', ''],
['space', ' '],
['tab', '\t'],
['newline', '\n'],
['carriage return', '\r'],
['"\\r\\n"', '\r\n'],
['"\\n\\r"', '\n\r'],
['" \\t \\n "', ' \t \n '],
['" txt \\t test \\n"', ' txt \t test \n'],
['"txt"', "txt"],
['"undefined"', 'undefined'],
['"null"', 'null'],
['"0"', '0'],
['"1"', '1'],
['"1.5"', '1.5'],
['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript
['comma', ','],
['dot', '.'],
['".5"', '.5'],
['0', 0],
['0.0', 0.0],
['1', 1],
['1.5', 1.5],
['NaN', NaN],
['/\S/', /\S/],
['true', true],
['false', false],
['function, returns true', function () { return true; } ],
['function, returns false', function () { return false; } ],
['function, returns null', function () { return null; } ],
['function, returns string', function () { return "test"; } ],
['function, returns undefined', function () { } ],
['MyClass', MyClass],
['new MyClass', new MyClass()],
['empty object', {}],
['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];
It's possible using the button
element.
<button name="name" value="value" type="submit">Sök</button>
From the W3C page on button
:
Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content.
For Apache 2 on Linux Mint 17.3 Cinnamon 64-bit, the following works:
In /etc/apache2/sites-available/
open the 000-default.conf
file, and change the Document Root to the absolute path of your directory.
sudo vim /etc/apache2/sites-available/000-default.conf
In folder /etc/apache2/
open file httpd.conf
, and add a <Directory>
tag referencing your directory and containing the exact same settings as the tag for var/www
.
sudo vim /etc/apache2/apache2.conf
On my machine it looked like this:
<Directory /home/my_user_name/php/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
Note: In the first step you probably want to change Document Root in the default-ssl.conf
file as well for SSL purposes. But as far as I can tell, this isn't required to get a general development environment running.
Well, Even I tried to log in with the admin/password which was failed. So I created my own user like this.
Android Home Key handled by the framework layer you can't able to handle this in the application layer level. Because the home button action is already defined in the below level. But If you are developing your custom ROM, then It might be possible. Google restricted the HOME BUTTON override functions because of security reasons.
The difference is the value returned to the environment is 0
in the former case and 1
in the latter case:
$ ./prog_with_exit_0
$ echo $?
0
$
and
$ ./prog_with_exit_1
$ echo $?
1
$
Also note that the macros value EXIT_SUCCESS
and EXIT_FAILURE
used as an argument to exit
function are implementation defined but are usually set to respectively 0
and a non-zero number. (POSIX requires EXIT_SUCCESS
to be 0). So usually exit(0)
means a success and exit(1)
a failure.
An exit
function call with an argument in main
function is equivalent to the statement return
with the same argument.
A slight variation on Cocoanuts answer (that helped me solve this) when the button was in the footer of a table (which prevents you from finding the 'clicked cell':
-(IBAction) buttonAction:(id)sender;
{
id parent1 = [sender superview]; // UiTableViewCellContentView
id parent2 = [parent1 superview]; // custom cell containing the content view
id parent3 = [parent2 superview]; // UITableView containing the cell
id parent4 = [parent3 superview]; // UIView containing the table
UIView *myContentView = (UIView *)parent1;
UITableViewCell *myTableCell = (UITableViewCell *)parent2;
UITableView *myTable = (UITableView *)parent3;
UIView *mainView = (UIView *)parent4;
CGRect footerViewRect = myTableCell.frame;
CGRect rect3 = [myTable convertRect:footerViewRect toView:mainView];
[cc doSomethingOnScreenAtY:rect3.origin.y];
}
There's these exciting new properties in CSS3:
font-smooth:always;
-webkit-font-smoothing: antialiased;
Still not done much testing with them myself though, and they almost definitely won't be any good for IE. Could be useful for Chrome on Windows or maybe Firefox though. Last time I checked, they didn't antialias small stuff automatically like they do in OSX.
UPDATE
These are not supported in IE or Firefox. The font-smooth property is only available in iOS safari as far as I remember
http://jsbeautifier.org/ is helpful to indent your minified JS code.
Also, with Google Chrome you can use "pretty print". See the example screenshot below showing jquery.min.js
from Stack Overflow nicely indented right from my browser :)
Same as any other language, just pass index number of element that you want to retrieve.
#!/usr/bin/env python
x = [2,3,4,5,6,7]
print(x[5])
There is an interesting discussion here: http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/307d658a-f677-40f2-bdef-e6352b0bfe9e/ My understanding of this thread is that freeing small allocations are not reflected in Private Bytes or Working Set.
Long story short:
if I call
p=malloc(1000);
free(p);
then the Private Bytes reflect only the allocation, not the deallocation.
if I call
p=malloc(>512k);
free(p);
then the Private Bytes correctly reflect the allocation and the deallocation.
I run into the same error maybe you have already imported the module by using only import datetime
so change form datetime import datetime
to only import datetime
. It worked for me after I changed it back.
The main difference between the two is where it is stored and how it is accessed.
$.fn.attr
stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.
$.fn.data
stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user
which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.
Data set with attr()
$(element).attr('data-name')
element.getAttribute('data-name')
,data-name
also accessible from $(element).data(name)
and element.dataset['name']
and element.dataset.name
Data set with .data()
.data(name)
.attr()
or anywhere elseAnother possibility is to use the textwrap module. This also avoids the problem of "string just sitting in the middle of nowhere" as mentioned in the question.
import textwrap
mystr = """\
Why, hello there
wonderful stackoverfow people"""
print (textwrap.fill(textwrap.dedent(mystr)))
This is probably old news by now, but the magic seems to be:
With those pieces in place, a GET request is successful.
For a HTTP POST
and on the client side (assuming your webmethod is called MethodName, and it takes a single parameter called searchString):
$.ajax({
url: "MyWebService.asmx/MethodName",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ searchString: q }),
success: function (response) {
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ": " + jqXHR.responseText);
}
});
I have used unique_ptr<char[]>
to implement a preallocated memory pools used in a game engine. The idea is to provide preallocated memory pools used instead of dynamic allocations for returning collision requests results and other stuff like particle physics without having to allocate / free memory at each frame. It's pretty convenient for this kind of scenarios where you need memory pools to allocate objects with limited life time (typically one, 2 or 3 frames) that do not require destruction logic (only memory deallocation).
I've found using cmd works well as an alternative, especially when you need to pipe the output from the called application (espeically when it doesn't have built in logging, unlike msbuild)
cmd /C "$msbuild $args" >> $outputfile
Use .valid()
from the jQuery Validation plugin:
$("#form_id").valid();
Checks whether the selected form is valid or whether all selected elements are valid. validate() needs to be called on the form before checking it using this method.
Where the form with id='form_id'
is a form that has already had .validate()
called on it.
AFAIK GrantedAuthority and roles are same in spring security. GrantedAuthority's getAuthority() string is the role (as per default implementation SimpleGrantedAuthority).
For your case may be you can use Hierarchical Roles
<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
<constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
<property name="hierarchy">
<value>
ROLE_ADMIN > ROLE_createSubUsers
ROLE_ADMIN > ROLE_deleteAccounts
ROLE_USER > ROLE_viewAccounts
</value>
</property>
</bean>
Not the exact sol you looking for, but hope it helps
Edit: Reply to your comment
Role is like a permission in spring-security. using intercept-url with hasRole provides a very fine grained control of what operation is allowed for which role/permission.
The way we handle in our application is, we define permission (i.e. role) for each operation (or rest url) for e.g. view_account, delete_account, add_account etc. Then we create logical profiles for each user like admin, guest_user, normal_user. The profiles are just logical grouping of permissions, independent of spring-security. When a new user is added, a profile is assigned to it (having all permissible permissions). Now when ever user try to perform some action, permission/role for that action is checked against user grantedAuthorities.
Also the defaultn RoleVoter uses prefix ROLE_, so any authority starting with ROLE_ is considered as role, you can change this default behavior by using a custom RolePrefix in role voter and using it in spring security.
i had same issue and did a pip upgrade using following and now it works fine.
python -m pip install --upgrade pip
WINDOWS FIX: Ive' Fixed it by downloading a new VMbox installer from the Official Website Here.
Dont worry about your VM's they will not disappear if you override your current installation.
NOTE: If you already have the latest version, you need to export all your VM's, unninstall your current VMBox and install it from new installer.
Let's create the dataframe in question
df_test = spark.createDataFrame(
[
(1, 5),
(2, 9),
(3, 3),
(4, 1),
],
['mvv', 'count']
)
df_test.show()
Which gives
+---+-----+
|mvv|count|
+---+-----+
| 1| 5|
| 2| 9|
| 3| 3|
| 4| 1|
+---+-----+
and then apply rdd.flatMap(f).collect() to get the list
test_list = df_test.select("mvv").rdd.flatMap(list).collect()
print(type(test_list))
print(test_list)
which gives
<type 'list'>
[1, 2, 3, 4]
Relatively-position your content div within a parent div having overflow:hidden. Make your up/down arrows move the top value of the content div. The following jQuery is untested. Let me know if you require any further assistance with it as a concept.
div.container {
overflow:hidden;
width:200px;
height:200px;
}
div.content {
position:relative;
top:0;
}
<div class="container">
<p>
<a href="enablejs.html" class="up">Up</a> /
<a href="enablejs.html" class="dn">Down</a>
</p>
<div class="content">
<p>Hello World</p>
</div>
</div>
$(function(){
$(".container a.up").bind("click", function(){
var topVal = $(this).parents(".container").find(".content").css("top");
$(this).parents(".container").find(".content").css("top", topVal-10);
});
$(".container a.dn").bind("click", function(){
var topVal = $(this).parents(".container").find(".content").css("top");
$(this).parents(".container").find(".content").css("top", topVal+10);
});
});
how about this:
string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");
Option 1 Each div is specifically identified, so any other div (without the specific IDs) on the page will not obey the :hover pseudo-class.
<style type="text/css">
#div1, #div2, #div3{
display:none;
}
#div1:hover, #div2:hover, #div3:hover{
display:block;
}
</style>
Option 2 All divs on the page, regardless of IDs, have the hover effect.
<style type="text/css">
div{
display:none;
}
div:hover{
display:block;
}
</style>
if you running docker under docker-machine?
execute to get ip:
docker-machine ip <machine>
returns the ip for the machine and try connect mysql:
mysql -h<docker-machine-ip>
The fact that you're getting an error from the Names Pipes Provider tells us that you're not using the TCP/IP protocol when you're trying to establish the connection. Try adding the "tcp" prefix and specifying the port number:
tcp:name.cloudapp.net,1433
You need to define the width of the element you are centering, not the parent element.
#header ul {
margin: 0 auto;
width: 90%;
}
Edit: Ok, I've seen the testpage now, and here is how I think you want it:
#header ul {
list-style:none;
margin:0 auto;
width:90%;
}
/* Remove the float: left; property, it interferes with display: inline and
* causes problems. (float: left; makes the element implicitly a block-level
* element. It is still good to use display: inline on it to overcome a bug
* in IE6 and below that doubles horizontal margins for floated elements)
* The styles below is the full style for the list-items.
*/
#header ul li {
color:#CCCCCC;
display:inline;
font-size:20px;
padding-right:20px;
}
If you have the url pattern, you should be able to search for it in your string. Just make sure that the pattern doesnt have ^
and $
marking beginning and end of the url string. So if P is the pattern for URL, look for matches for P.
Would I just override the drawRect method?
Yes:
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, rect);
CGContextSetFillColor(ctx, CGColorGetComponents([[UIColor blueColor] CGColor]));
CGContextFillPath(ctx);
}
Also, would it be okay to change the frame of that view within the class itself?
Ideally not, but you could.
Or do I need to change the frame from a different class?
I'd let the parent control that.
YOU JUST CAN'T. There's no exact code to use for setting a forever cookie but an old trick will do, like current time + 10 years
.
Just a note that any dates beyond January 2038
will doomed you for the cookies (32-bit int) will be deleted instantly. Wish for a miracle that that will be fixed in the near future. For 64-bit int, years around 2110
will be safe. As time goes by, software and hardware will change and may never adapt to older ones (the things we have now) so prepare the now for the future.
Since Java doesn't have an intersect function (really!?) you can do collision detection by simply comparying the X and Y, Width and Height values of the bounding boxes (rectangle) for each of the objects that could potentially collide.
So... in the base object of each colliding object... i.e. if your player and enemy have a common base you can put a simple Rectangle object called something like BoundingBox. If the common base is a built in Java class then you'll need to create a class that extends the build in class and have the player and enemy objects extend your new class or are instances of that class.
At creation (and each tick or update) you'll need to set the BoundingBox paremeters for both your player and enemy. I don't have the Rectangle class infront of me but its most likely something like X, Y, Width and finally Height. X and Y are that objects location in your game world. The width and height are self explanatory I think. They'll most likely come out from the right of the players location though so, if the X and Y were bothe at 0 and your Width and Height were both at 256 you wouldn't see anything because the character would be at the top left outside of the screen.
Anyways... to detect a collision, you'll want to compare the attributes of the player and enemy BoundingBoxes. So something like this...
if( Player.BoundingBox.X = Enemy.BoundingBox.X && If( Player.BoundingBox.Y = Enemy.BoundingBox.Y )
{
//Oh noes! The enemy and player are on top of eachother.
}
The logic can get sort of complicated but you'll need to compare the distances between each BoundingBox and compare locations.
Using requests and json makes it simple.
json.loads
functionRequests module provides you useful function to loop for success and failure.
if(Response.ok)
: will help help you determine if your API call is successful (Response code - 200)
Response.raise_for_status()
will help you fetch the http code that is returned from the API.
Below is a sample code for making such API calls. Also can be found in github. The code assumes that the API makes use of digest authentication. You can either skip this or use other appropriate authentication modules to authenticate the client invoking the API.
#Python 2.7.6
#RestfulClient.py
import requests
from requests.auth import HTTPDigestAuth
import json
# Replace with the correct URL
url = "http://api_url"
# It is a good practice not to hardcode the credentials. So ask the user to enter credentials at runtime
myResponse = requests.get(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True)
#print (myResponse.status_code)
# For successful API call, response code will be 200 (OK)
if(myResponse.ok):
# Loading the response data into a dict variable
# json.loads takes in only binary or string variables so using content to fetch binary content
# Loads (Load String) takes a Json file and converts into python data structure (dict or list, depending on JSON)
jData = json.loads(myResponse.content)
print("The response contains {0} properties".format(len(jData)))
print("\n")
for key in jData:
print key + " : " + jData[key]
else:
# If response code is not ok (200), print the resulting http error code with description
myResponse.raise_for_status()
I got this exception when I set url in query like "example.com/files/text.txt". Ive changed url to "http://example.com/files/text.txt" and this exception dissapeared.
You reference a Linux distribution, so you need to install the readline development libraries
On Debian based platforms, like Ubuntu, you can run:
sudo apt-get install libreadline-dev
and that should install the correct headers in the correct places,.
If you use a platform with yum
, like SUSE, then the command should be:
yum install readline-devel
Use this code very simple solution
@Override
public void onBackPressed() {
super.onBackPressed(); // this line close the app on backpress
}
I had this same issue while trying to test a very similar function that uses a SELECT statement to decide if a INSERT or an UPDATE should be done. This function was a re-write of a T-SQL stored procedure.
When I tested the function from the query window I got the error "query has no destination for result data". I finally figured out that because I used a SELECT statement inside the function that I could not test the function from the query window until I assigned the results of the SELECT to a local variable using an INTO statement. This fixed the problem.
If the original function in this thread was changed to the following it would work when called from the query window,
$BODY$
DECLARE
v_temp integer;
BEGIN
SELECT 1 INTO v_temp
FROM "USERS"
WHERE "userID" = $1;
Bitcode makes crash reporting harder. Here is a quote from HockeyApp (which also true for any other crash reporting solutions):
When uploading an app to the App Store and leaving the "Bitcode" checkbox enabled, Apple will use that Bitcode build and re-compile it on their end before distributing it to devices. This will result in the binary getting a new UUID and there is an option to download a corresponding dSYM through Xcode.
Note: the answer was edited on Jan 2016 to reflect most recent changes
SELECT DATEDIFF(NOW(),pickup_date) AS noofday
FROM cir_order
WHERE DATEDIFF(NOW(),pickup_date)>2;
or
SELECT *
FROM cir_order
WHERE cir_order.`cir_date` >= DATE_ADD( CURDATE(), INTERVAL -10 DAY )
As now in swift 3 / xcode 8 text property is optional you can do it like this:
if ((textField.text ?? "").isEmpty) {
// is empty
}
or:
if (textField.text?.isEmpty ?? true) {
// is empty
}
Alternatively you could make an extenstion such as below and use it instead:
extension UITextField {
var isEmpty: Bool {
return text?.isEmpty ?? true
}
}
...
if (textField.isEmpty) {
// is empty
}
Here is a unique way of setting Authorization token in axios. Setting configuration to every axios call is not a good idea and you can change the default Authorization token by:
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:1010/'
axios.defaults.headers.common = {'Authorization': `bearer ${token}`}
export default axios;
Edit, Thanks to Jason Norwood-Young.
Some API require bearer to be written as Bearer, so you can do:
axios.defaults.headers.common = {'Authorization': `Bearer ${token}`}
Now you don't need to set configuration to every API call. Now Authorization token is set to every axios call.
Create a dummy tag that is not going to rendered on the page but it will work as holder for ng-repeat:
<dummyTag ng-repeat="featureItem in item.features">{{featureItem.feature}}</br> </dummyTag>
while (i > 10)
{
i = (Int32)Math.Floor((Decimal)i / 10);
}
// i is now the first int
How about:
mySwitchFunction = (param) => {
switch (param) {
case 'A':
return ([
<div />,
]);
// etc...
}
}
render() {
return (
<div>
<div>
// removed for brevity
</div>
{ this.mySwitchFunction(param) }
<div>
// removed for brevity
</div>
</div>
);
}
If you want to append a value to myList, use myList.append(s)
.
Strings are immutable -- you can't append to them.
You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ...
, it's not recommended. Take a closer look here
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if #available(iOS 10, *) {
//Notifications get posted to the function (delegate): func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)"
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
guard error == nil else {
//Display Error.. Handle Error.. etc..
return
}
if granted {
//Do stuff here..
//Register for RemoteNotifications. Your Remote Notifications can display alerts now :)
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
else {
//Handle user denying permissions..
}
}
//Register for remote notifications.. If permission above is NOT granted, all notifications are delivered silently to AppDelegate.
application.registerForRemoteNotifications()
}
else {
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
return true
}
You can try this line of code:
pdDataFrame = pd.DataFrame([np.nan] * 7)
This will create a pandas dataframe of size 7 with NaN of type float:
if you print pdDataFrame
the output will be:
0
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
Also the output for pdDataFrame.dtypes
is:
0 float64
dtype: object
No, how you are doing it is correct.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.2
Padding aligns structure members to "natural" address boundaries - say, int
members would have offsets, which are mod(4) == 0
on 32-bit platform. Padding is on by default. It inserts the following "gaps" into your first structure:
struct mystruct_A {
char a;
char gap_0[3]; /* inserted by compiler: for alignment of b */
int b;
char c;
char gap_1[3]; /* -"-: for alignment of the whole struct in an array */
} x;
Packing, on the other hand prevents compiler from doing padding - this has to be explicitly requested - under GCC it's __attribute__((__packed__))
, so the following:
struct __attribute__((__packed__)) mystruct_A {
char a;
int b;
char c;
};
would produce structure of size 6
on a 32-bit architecture.
A note though - unaligned memory access is slower on architectures that allow it (like x86 and amd64), and is explicitly prohibited on strict alignment architectures like SPARC.
Here is a simple way. Reflector is not needed.
public static string GetQueryStringWithOutParameter(string parameter)
{
var nameValueCollection = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.QueryString.ToString());
nameValueCollection.Remove(parameter);
string url = HttpContext.Current.Request.Path + "?" + nameValueCollection;
return url;
}
Here QueryString.ToString()
is required because Request.QueryString
collection is read only.
You have to declare your functions before main()
(or declare the function prototypes before main()
)
As it is, the compiler sees my_print (my_string);
in main()
as a function declaration.
Move your functions above main()
in the file, or put:
void my_print (char *);
void my_print2 (char *);
Above main()
in the file.
It's simple, go to this folder:
~/Library/MobileDevice/Provisioning\ Profiles/
Open finder on your mac, and click on Go -> Go to Folder ... Just paste this into the search bar and hit Open. It will show the list of provisioning profiles present in Xcode. Delete all provisioning profiles.
You can use code like this:
char *MyFunction(some arguments...)
{
char *pointer = malloc(size for the new array);
if (!pointer)
An error occurred, abort or do something about the error.
return pointer; // Return address of memory to the caller.
}
When you do this, the memory should later be freed, by passing the address to free.
There are other options. A routine might return a pointer to an array (or portion of an array) that is part of some existing structure. The caller might pass an array, and the routine merely writes into the array, rather than allocating space for a new array.
If you want to use the function std::max_element()
, the way you have to do it is:
double max = *max_element(vector.begin(), vector.end());
cout<<"Max value: "<<max<<endl;
I hope this can help.
I should be able to accomplish this through standard java string manipulation, nothing Android or TextView specific.
Something like:
String upperString = myString.substring(0, 1).toUpperCase() + myString.substring(1).toLowerCase();
Although there are probably a million ways to accomplish this. See String documentation.
EDITED
I added the .toLowerCase()
Try:
<table border="1">
<tr>
<td>
<table border="">
...
</table>
</td>
</tr>
</table>
An attribute is the actual thing that you use within your HTML tag like
<input type="checkbox" checked="checked" />
In this instance type and checked are attributes. The property though is the value of these attributes, which the browser saves inside the DOM element. Often the value of the attributes and the properties are equal, that's what makes it so confusing.
In this example the DOM element input
has the property type
with the value "checkbox"
and the property checked
with the value true
(notice how this value differs from the value inside the HTML attribute).
Using Firebug you can observe the behaviour of properties when clicking on an element and selecting the "DOM view".
You can iterate over the row data
$('#button').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
console.log(ids)
alert(table.rows('.selected').data().length + ' row(s) selected');
});
Demo: Fiddle
You can use dotPeek The only thing I have to say is that when using it, right-click on the class to select Decompiled Source instead of double-clicking, otherwise dotpeek will only display the contents of the local cs file, not the decompiled content. Option instance
The class.__stuff
naming convention lets the programmer know he isn't meant to access __stuff
from outside. The name mangling makes it unlikely anyone will do it by accident.
True, you still can work around this, it's even easier than in other languages (which BTW also let you do this), but no Python programmer would do this if he cares about encapsulation.
A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.
For example, say I have a Union like this:
type CatNames = "miffy" | "boris" | "mordred";
Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.
type CatList = Record<CatNames, {age: number}>
If I want to satisfy this CatList, I must create an object like this:
const cats:CatList = {
miffy: { age:99 },
boris: { age:16 },
mordred: { age:600 }
}
You get very strong type safety:
I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes
I had a union like this:
type Statuses = "failed" | "complete";
I used this to create an object like this:
const icons: Record<
Statuses,
{ iconType: IconTypes; iconColor: IconColors }
> = {
failed: {
iconType: "warning",
iconColor: "red"
},
complete: {
iconType: "check",
iconColor: "green"
};
I could then render by destructuring an element from the object into props, like so:
const Status = ({status}) => <Icon {...icons[status]} />
If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.
Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.
Here is a good introduction to logging in Java: http://www.javapractices.com/topic/TopicAction.do?Id=143
Java comes with a logging API since it's 1.4.2 version: http://download.oracle.com/javase/1.4.2/docs/guide/util/logging/overview.html
You can also use other logging frameworks like Apache Log4j which is the most popular one: http://logging.apache.org/log4j
I suggest you to use a logging abstraction framework which allows you to change your logging framework without re-factoring you code. So you can starts by using Jul (Java Util Logging) then swith to Log4j without changing you code. The most popular logging facade is slf4j: http://www.slf4j.org/
Regards,
You can easily auto-generate the C# code using: http://regexhero.net/tester/.
Its free.
Here is how I did it:
The website then auto-generates the .NET code:
string strRegex = @"\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @" {CD73FAD2-E226-4715-B6FA-14EDF0764162}.Debug|x64.ActiveCfg = Debug|x64";
string strReplace = @"""$0""";
return myRegex.Replace(strTargetString, strReplace);
Please make sure that you don't do any network access on UI Thread, instead do it in Async Task
The reason why your application crashes on Android versions 3.0 and above, but works fine on Android 2.x is because since HoneyComb are much stricter about abuse against the UI Thread. For example, when an Android device running HoneyComb or above detects a network access on the UI thread, a NetworkOnMainThreadException will be thrown.
See this
I would suggest creating your package structure by feature, and not by the implementation layer. A good write up on this is Java practices: Package by feature, not layer
The items with code "200 (cache)" were fulfilled directly from your browser cache, meaning that the original requests for the items were returned with headers indicating that the browser could cache them (e.g. future-dated Expires
or Cache-Control: max-age
headers), and that at the time you triggered the new request, those cached objects were still stored in local cache and had not yet expired.
304s, on the other hand, are the response of the server after the browser has checked if a file was modified since the last version it had cached (the answer being "no").
For most optimal web performance, you're best off setting a far-future Expires:
or Cache-Control: max-age
header for all assets, and then when an asset needs to be changed, changing the actual filename of the asset or appending a version string to requests for that asset. This eliminates the need for any request to be made unless the asset has definitely changed from the version in cache (no need for that 304 response). Google has more details on correct use of long-term caching.
SQL 2003 standard defines the format as follows:
<unquoted timestamp string> ::= <unquoted date string> <space> <unquoted time string>
<date value> ::= <years value> <minus sign> <months value> <minus sign> <days value>
<time value> ::= <hours value> <colon> <minutes value> <colon> <seconds value>
There are some definitions in between that just link back to these, but in short YYYY-MM-DD HH:MM:SS
with optional .mmm
milliseconds is required to work on all SQL databases.
I resolved that error by referencing the NetStandard.Library and the following app.config File in the NUnit-Project.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.1.0" newVersion="4.1.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Reflection" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.1.0" newVersion="4.1.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.InteropServices" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
Edit
If anything other than System.Runtime
, System.Reflection
or System.Runtime.InteropServices
is missing (e.g. System.Linq
), then just add a new dependentAssembly
node.
Edit 2
In new Visual Studio Versions (2017 15.8 I think) it's possible that Studio creates the app.config File. Just check the Auto-generate binding redirects Checkbox in Project-Properties - Application.
Edit 3
Auto-generate binding redirects does not work well with .NET Classlibraries. Adding the following lines to the csproj files solves this and a working .config file for the Classlibary will be generated.
<PropertyGroup>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>
If you're using Bash or zsh, use this:
type -a lshw
This will show whether the target is a builtin, a function, an alias or an external executable. If the latter, it will show each place it appears in your PATH
.
bash$ type -a lshw
lshw is /usr/bin/lshw
bash$ type -a ls
ls is aliased to `ls --color=auto'
ls is /bin/ls
bash$ zsh
zsh% type -a which
which is a shell builtin
which is /usr/bin/which
In Bash, for functions type -a
will also display the function definition. You can use declare -f functionname
to do the same thing (you have to use that for zsh, since type -a
doesn't).
I'm a little surprised it doesn't just do that. Could there another element inside the div that has a width set to something greater than 250?
The error is self-explanatory... doInBackground()
runs on a background thread which, since it is not intended to loop, is not connected to a Looper
.
You most likely don't want to directly instantiate a Handler at all... whatever data your doInBackground()
implementation returns will be passed to onPostExecute()
which runs on the UI thread.
mActivity = ThisActivity.this;
mActivity.runOnUiThread(new Runnable() {
public void run() {
new asyncCreateText().execute();
}
});
ADDED FOLLOWING THE STACKTRACE APPEARING IN QUESTION:
Looks like you're trying to start an AsyncTask
from a GL rendering thread... don't do that cos they won't ever Looper.loop()
either. AsyncTasks are really designed to be run from the UI thread only.
The least disruptive fix would probably be to call Activity.runOnUiThread()
with a Runnable
that kicks off your AsyncTask
.
Calculates the size of the java.sql.ResultSet:
int size = 0;
if (rs != null) {
rs.beforeFirst();
rs.last();
size = rs.getRow();
}
(Source)
How are you collecting user input in the first place? This question / answer may assist if you're using a FormController
:
A canvas element with some JavaScript would work great.
In fact, Signature Pad (a jQuery plugin) already has this implemented.
There is the JavaScriptSerializer class you can use too. That will let you deserialize the json to a .NET object. There's a generic Deserialize<T>
, though you will need the .NET object to have a similar signature as the javascript one. Additionally there is also a DeserializeObject
method that just makes a plain object
. You can then use reflection to get at the properties you need.
If your controller takes a FormCollection
, and you didn't add anything else to the data
the json should be in form[0]
:
public ActionResult Save(FormCollection forms) {
string json = forms[0];
// do your thing here.
}
I've implemented cross-browser compatible page to test browser's refresh behavior (here is the source code) and get results similar to @some, but for modern browsers:
In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.
If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.
From your snippet Your class AliceUniversity
seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate
and UniversityGraduate
.
Pure virtual functions are the ones with = 0;
at the end of declaration.
Example: virtual void doSomething() = 0;
For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.
You could use a PowerShell command. Stick this in your batch script and it'll create a shortcut to %~f0
in %userprofile%\Start Menu\Programs\Startup
:
powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Start Menu\Programs\Startup\%~n0.lnk');$s.TargetPath='%~f0';$s.Save()"
If you prefer not to use PowerShell, you could use mklink
to make a symbolic link. Syntax:
mklink saveShortcutAs targetOfShortcut
See mklink /?
in a console window for full syntax, and this web page for further information.
In your batch script, do:
mklink "%userprofile%\Start Menu\Programs\Startup\%~nx0" "%~f0"
The shortcut created isn't a traditional .lnk file, but it should work the same nevertheless. Be advised that this will only work if the .bat file is run from the same drive as your startup folder. Also, apparently admin rights are required to create symbolic links.
You are passing a reference to the list, but your aren't passing the list variable by reference - so when you call ChangeList
the value of the variable (i.e. the reference - think "pointer") is copied - and changes to the value of the parameter inside ChangeList
aren't seen by TestMethod
.
try:
private void ChangeList(ref List<int> myList) {...}
...
ChangeList(ref myList);
This then passes a reference to the local-variable myRef
(as declared in TestMethod
); now, if you reassign the parameter inside ChangeList
you are also reassigning the variable inside TestMethod
.
According to this article: https://medium.freecodecamp.org/a-realworld-comparison-of-front-end-frameworks-with-benchmarks-2019-update-4be0d3c78075
You better use MobX to manage the data in your app to get better performance, not Redux.
this is due to again and again creating view ,best option is clear cache before setting adapter
recyclerview.setItemViewCacheSize(your array.size());
Calling iterator()
on a Collection impl, probably would get a new Iterator on each call.
Thus, you can simply call iterator()
again to get a new one.
IteratorLearn.java
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
/**
* Iterator learn.
*
* @author eric
* @date 12/30/18 4:03 PM
*/
public class IteratorLearn {
@Test
public void test() {
Collection<Integer> c = new HashSet<>();
for (int i = 0; i < 10; i++) {
c.add(i);
}
Iterator it;
// iterate,
it = c.iterator();
System.out.println("\niterate:");
while (it.hasNext()) {
System.out.printf("\t%d\n", it.next());
}
Assert.assertFalse(it.hasNext());
// consume,
it = c.iterator();
System.out.println("\nconsume elements:");
it.forEachRemaining(ele -> System.out.printf("\t%d\n", ele));
Assert.assertFalse(it.hasNext());
}
}
Output:
iterate:
0
1
2
3
4
5
6
7
8
9
consume elements:
0
1
2
3
4
5
6
7
8
9
An absolutely positioned element is actually positioned regarding a relative
parent, or the nearest found relative parent. So the element with overflow: hidden
should be between relative
and absolute
positioned elements:
<div class="relative-parent">
<div class="hiding-parent">
<div class="child"></div>
</div>
</div>
.relative-parent {
position:relative;
}
.hiding-parent {
overflow:hidden;
}
.child {
position:absolute;
}
Also, the ternary operator enables a form of "optional" parameter. Java does not allow optional parameters in method signatures but the ternary operator enables you to easily inline a default choice when null
is supplied for a parameter value.
For example:
public void myMethod(int par1, String optionalPar2) {
String par2 = ((optionalPar2 == null) ? getDefaultString() : optionalPar2)
.trim()
.toUpperCase(getDefaultLocale());
}
In the above example, passing null
as the String
parameter value gets you a default string value instead of a NullPointerException
. It's short and sweet and, I would say, very readable. Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.
Moreover, this pattern enables you to make the String
parameter truly optional (if it is deemed useful to do so) by overloading the method as follows:
public void myMethod(int par1) {
return myMethod(par1, null);
}
After trying a couple of the suggestions on this page I ended up using the pngcrush solution. You can use the bash script below to recursively detect and fix bad png profiles. Just pass it the full path to the directory you want to search for png files.
fixpng "/path/to/png/folder"
The script:
#!/bin/bash
FILES=$(find "$1" -type f -iname '*.png')
FIXED=0
for f in $FILES; do
WARN=$(pngcrush -n -warn "$f" 2>&1)
if [[ "$WARN" == *"PCS illuminant is not D50"* ]] || [[ "$WARN" == *"known incorrect sRGB profile"* ]]; then
pngcrush -s -ow -rem allb -reduce "$f"
FIXED=$((FIXED + 1))
fi
done
echo "$FIXED errors fixed"
You can also use html to override the css locally. I was having a similar issue and this worked for me:
<html>
<body>
<h4>A nested List:</h4>
<ul style="PADDING-LEFT: 12px">
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>
</body>
</html>
You can also use array_column()
. It's available from PHP 5.5: php.net/manual/en/function.array-column.php
It returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.
print_r(array_column($myarray, 'email'));
You need to create an event source and a message file for it. Code looks something like this:
var data = new EventSourceCreationData("yourApp", "Application");
data.MessageResourceFile = pathToYourMessageFile;
EventLog.CreateEventSource(data);
Then you will need to create a message file. There is also this article that explains things (I did not read it all but it seems fairly complete).
Update your pip
first:
pip install --upgrade pip
for Python 3:
pip3 install --upgrade pip
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
p.stdin.write('one\n')
time.sleep(0.5)
p.stdin.write('two\n')
time.sleep(0.5)
p.stdin.write('three\n')
time.sleep(0.5)
testresult = p.communicate()[0]
time.sleep(0.5)
print(testresult)
You can do that by applying your rotate CSS to an inner element and then adjusting the height of the element to match its width since the element was rotated to fit it into the <td>
.
Also make sure you change your id
#rotate
to a class since you have multiple.
$(document).ready(function() {_x000D_
$('.rotate').css('height', $('.rotate').width());_x000D_
});
_x000D_
td {_x000D_
border-collapse: collapse;_x000D_
border: 1px black solid;_x000D_
}_x000D_
tr:nth-of-type(5) td:nth-of-type(1) {_x000D_
visibility: hidden;_x000D_
}_x000D_
.rotate {_x000D_
/* FF3.5+ */_x000D_
-moz-transform: rotate(-90.0deg);_x000D_
/* Opera 10.5 */_x000D_
-o-transform: rotate(-90.0deg);_x000D_
/* Saf3.1+, Chrome */_x000D_
-webkit-transform: rotate(-90.0deg);_x000D_
/* IE6,IE7 */_x000D_
filter: progid: DXImageTransform.Microsoft.BasicImage(rotation=0.083);_x000D_
/* IE8 */_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)";_x000D_
/* Standard */_x000D_
transform: rotate(-90.0deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>10kg</div>_x000D_
</td>_x000D_
<td>B</td>_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
<td>E</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>20kg</div>_x000D_
</td>_x000D_
<td>G</td>_x000D_
<td>H</td>_x000D_
<td>I</td>_x000D_
<td>J</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>30kg</div>_x000D_
</td>_x000D_
<td>L</td>_x000D_
<td>M</td>_x000D_
<td>N</td>_x000D_
<td>O</td>_x000D_
</tr>_x000D_
_x000D_
_x000D_
</table>
_x000D_
JavaScript
The equivalent to the above in pure JavaScript is as follows:
window.addEventListener('load', function () {
var rotates = document.getElementsByClassName('rotate');
for (var i = 0; i < rotates.length; i++) {
rotates[i].style.height = rotates[i].offsetWidth + 'px';
}
});
There is the nuclear approach which is in your App.css (or counterpart)
a{
text-decoration: none;
}
which prevents underline for all <a>
tags which is the root cause of this problem
// 2015/09/27 15:07:53
System.out.println( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()) );
// 15:07:53
System.out.println( new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()) );
// 09/28/2015
System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime()));
// 20150928_161823
System.out.println( new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) );
// Mon Sep 28 16:24:28 CEST 2015
System.out.println( Calendar.getInstance().getTime() );
// Mon Sep 28 16:24:51 CEST 2015
System.out.println( new Date(System.currentTimeMillis()) );
// Mon Sep 28
System.out.println( new Date().toString().substring(0, 10) );
// 2015-09-28
System.out.println( new java.sql.Date(System.currentTimeMillis()) );
// 14:32:26
Date d = new Date();
System.out.println( (d.getTime() / 1000 / 60 / 60) % 24 + ":" + (d.getTime() / 1000 / 60) % 60 + ":" + (d.getTime() / 1000) % 60 );
// 2015-09-28 17:12:35.584
System.out.println( new Timestamp(System.currentTimeMillis()) );
// Java 8
// 2015-09-28T16:16:23.308+02:00[Europe/Belgrade]
System.out.println( ZonedDateTime.now() );
// Mon, 28 Sep 2015 16:16:23 +0200
System.out.println( ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME) );
// 2015-09-28
System.out.println( LocalDate.now(ZoneId.of("Europe/Paris")) ); // rest zones id in ZoneId class
// 16
System.out.println( LocalTime.now().getHour() );
// 2015-09-28T16:16:23.315
System.out.println( LocalDateTime.now() );
string foo;
... foo.length() ...
.length and .size are synonymous, I just think that "length" is a slightly clearer word.
int base2(String bits) {
int ans = 0;
for (int i = bits.length() - 1, f = 1; i >= 0; i--) {
ans += f * (bits.charAt(i) - '0');
f <<= 1;
}
return ans;
}
If you would like to have the datetime,hours,minutes etc..you can use a static variable. Append the value of this variable to the filename. You can start the counter with 0 and increment when you have created a file. This way the filename will surely be unique since you have seconds also in the file.
You just need the $('button').prop('disabled', true);
part, the button will automatically take the disabled class.
You can use contains too:
element = findElement(By.xpath("//input[contains (@test-id,"test-username")]");
Im not the person to tell you about speed and memory usage, but looking at a switch statment is a hell of a lot easier to understand then a large if statement (especially 2-3 months down the line)
<select>
<option value="" disabled selected hidden>Select an Option</option>
<option value="one">Option 1</option>
<option value="two">Option 2</option>
</select>
here it's a simple:
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Add permission in manifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Thanks for all the responses! This is ace :)
Based on OneByOne's answer (which looked the simplest to me), I added some non-capturing groups (the '(?:' parts - thanks to VonC for introducing me to non-capturing groups!), so the groups that do capture only contain the digits or * character.
^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$
Many thanks everyone!
Let me expand a bit on a VonC's very comprehensive answer:
First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.
Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".
Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.
HTH
PIPESTATUS[@] must be copied to an array immediately after the pipe command returns. Any reads of PIPESTATUS[@] will erase the contents. Copy it to another array if you plan on checking the status of all pipe commands. "$?" is the same value as the last element of "${PIPESTATUS[@]}", and reading it seems to destroy "${PIPESTATUS[@]}", but I haven't absolutely verified this.
declare -a PSA
cmd1 | cmd2 | cmd3
PSA=( "${PIPESTATUS[@]}" )
This will not work if the pipe is in a sub-shell. For a solution to that problem,
see bash pipestatus in backticked command?
You could use the Microsoft-specific function _getch:
#include <iostream>
#include <conio.h>
// ...
// ...
// ...
cout << "Press any key to continue..." << endl;
_getch();
cout << "Something" << endl;
Things seems a little confused in the code in your question, so I am going to give you an example of what I think you are try to do.
First considerations are about mixing HTML, Javascript and CSS:
Why is using onClick() in HTML a bad practice?
I will be removing inline content and splitting these into their appropriate files.
Next, I am going to go with the "click" event and displose of the "change" event, as it is not clear that you want or need both.
Your function changeBackground
sets both the backround color and the text color to the same value (your text will not be seen), so I am caching the color value as we don't need to look it up in the DOM twice.
CSS
#TheForm {
margin-left: 396px;
}
#submitColor {
margin-left: 48px;
margin-top: 5px;
}
HTML
<form id="TheForm">
<input id="color" type="text" />
<br/>
<input id="submitColor" value="Submit" type="button" />
</form>
<span id="coltext">This text should have the same color as you put in the text box</span>
Javascript
function changeBackground() {
var color = document.getElementById("color").value; // cached
// The working function for changing background color.
document.bgColor = color;
// The code I'd like to use for changing the text simultaneously - however it does not work.
document.getElementById("coltext").style.color = color;
}
document.getElementById("submitColor").addEventListener("click", changeBackground, false);
On jsfiddle
Source: w3schools
CSS colors are defined using a hexadecimal (hex) notation for the combination of Red, Green, and Blue color values (RGB). The lowest value that can be given to one of the light sources is 0 (hex 00). The highest value is 255 (hex FF).
Hex values are written as 3 double digit numbers, starting with a # sign.
Update: as pointed out by @Ian
Hex can be either 3 or 6 characters long
Source: W3C
The format of an RGB value in hexadecimal notation is a ‘#’ immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.
Here is an alternative function that will check that your input is a valid CSS Hex Color, it will set the text color only or throw an alert if it is not valid.
For regex testing, I will use this pattern
/^#(?:[0-9a-f]{3}){1,2}$/i
but if you were regex matching and wanted to break the numbers into groups then you would require a different pattern
function changeBackground() {
var color = document.getElementById("color").value.trim(),
rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i;
if (rxValidHex.test(color)) {
document.getElementById("coltext").style.color = color;
} else {
alert("Invalid CSS Hex Color");
}
}
document.getElementById("submitColor").addEventListener("click", changeBackground, false);
On jsfiddle
Here is a further modification that will allow colours by name along with by hex.
function changeBackground() {
var names = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"],
color = document.getElementById("color").value.trim(),
rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i,
formattedName = color.charAt(0).toUpperCase() + color.slice(1).toLowerCase();
if (names.indexOf(formattedName) !== -1 || rxValidHex.test(color)) {
document.getElementById("coltext").style.color = color;
} else {
alert("Invalid CSS Color");
}
}
document.getElementById("submitColor").addEventListener("click", changeBackground, false);
On jsfiddle
You could register to the KeyDown-Event of the Textbox, look if the pressed key is Enter and then execute the EventHandler of the button:
private void buttonTest_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello World");
}
private void textBoxTest_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
buttonTest_Click(this, new EventArgs());
}
}
Just to add on @Lukas Eder answer.
An improvement to avoid creating tables and inserting values
(we could use select from dual
and unpivot
to achieve the same result "on the fly"):
with all_likes as
(select * from
(select '%val1%' like_1, '%val2%' like_2, '%val3%' like_3, '%val4%' as like_4, '%val5%' as like_5 from dual)
unpivot (
united_columns for subquery_column in ("LIKE_1", "LIKE_2", "LIKE_3", "LIKE_4", "LIKE_5"))
)
select * from tbl
where exists (select 1 from all_likes where tbl.my_col like all_likes.united_columns)
append([]int{1,2}, []int{3,4}...)
will work. Passing arguments to ...
parameters.
If f
is variadic with a final parameter p
of type ...T
, then within f
the type of p
is equivalent to type []T
.
If f
is invoked with no actual arguments for p
, the value passed to p
is nil
.
Otherwise, the value passed is a new slice of type []T
with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T
. The length and capacity of the slice is therefore the number of arguments bound to p
and may differ for each call site.
Given the function and calls
func Greeting(prefix string, who ...string)
Greeting("nobody")
Greeting("hello:", "Joe", "Anna", "Eileen")
Try
$('li.current_sub').prev('.par_cat').[do stuff];
ravgs = [sum(data[i:i+5])/5. for i in range(len(data)-4)]
This isn't the most efficient approach but it will give your answer and I'm unclear if your window is 5 points or 10. If its 10, replace each 5 with 10 and the 4 with 9.
Int cannot accept null but if developer are using int? then you store null in int like int i = null; // not accept int? i = null; // its working mostly use for pagination in MVC Pagelist
You have to do this to echo it:
echo $row['note'];
(The data is coming as an array)
Currently you can't access the arrays named name and country, because they are member variables of your Athelete class.
Based on what it looks like you're trying to do, this will not work.
These arrays belong in your main class.
I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.
Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!
Hope to help
You're going to have a hard time writing to the same file you're reading from. One quick way is to simply do this:
File.WriteAllText("test.txt", File.ReadAllText("test.txt").Replace("some text","some other text"));
You can lay that out better with
string str = File.ReadAllText("test.txt");
str = str.Replace("some text","some other text");
File.WriteAllText("test.txt", str);
Compiling with -source 1.5 -target 1.5 (in a JDK 6 environment) will honor only language elements that were in 1.5 and prior. Great. But there were no language changes in 6 anyway. Problem with this approach (on Mac with 1.6) is that using classes that came AFTER 1.5 will still compile because they exist in the rt.jar. So one could run in a 1.5 env and get a class not found exception with no prior warning when compiling. I found this out the hard way with javax.swing.event.RowSorterEvent/Listener. Both entered "Since 1.6" but are not caught with -source 1.5
Please check your app's build.gradle. I had the same problem, finally I found the problem was in my build.gradle file dependencies{}, it add extra .jar file which actually didn't exist in my project as dependency. So I delete this dependency, and the problem has gone.
Most of these answers seem crazy over complicated and super buggy, here's mine -- it works on any environment variable, no %CD%
or PUSHD
/POPD
, or for /f
nonsense -- just plain old batch functions. -- The directory & file don't even have to exist.
CALL :NORMALIZEPATH "..\..\..\foo\bar.txt"
SET BLAH=%RETVAL%
ECHO "%BLAH%"
:: ========== FUNCTIONS ==========
EXIT /B
:NORMALIZEPATH
SET RETVAL=%~f1
EXIT /B
Now you may have a better solution to resolve this scenario, but other way which i preferred.
const arr = [1,3,12]
if( arr.includes(foo)) { // it will return true if you `foo` is one of array values else false
// code here
}
I preferred above solution over the indexOf check where you need to check index as well.
if ( arr.indexOf( foo ) !== -1 ) { }
There are a number of approaches here- and though the position is that typically users should not be restricted when it comes to zooming for accessibility purposes, there may be incidences where is it required:
Render the page at the width of the device, dont scale:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Prevent scaling- and prevent the user from being able to zoom:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
Removing all zooming, all scaling
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
This below code will give selected row, you can parse the values from it and send to the AJAX call.
$(".selected").click(function () {
var row = $(this).parent().parent().parent().html();
});
You can use this
string x = "ABCGH"
char[] charX = x.ToCharArray();
Array.Sort(charX);
This will sort your string.
Just define your variables in global.js outside a function scope:
// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";
// other js-file
function testGlobal () {
alert(global1);
}
To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:
<html>
<head>
<!-- Include global.js first -->
<script src="/YOUR_PATH/global.js" type="text/javascript"></script>
<!-- Now we can reference variables, objects, functions etc.
defined in global.js -->
<script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>
</head>
[...]
</html>
You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.
<script type="text/javascript">
$(document).ready(function(){
$("#test").keypress(function(e){
if (e.which == 103)
{
alert('g');
};
});
});
</script>
<input type="text" id="test" />
this site says 71 = g but the jQuery code above thought otherwise
Capital G = 71, lowercase is 103
I also experienced np.array_split not working with Pandas DataFrame my solution was to only split the index of the DataFrame and then introduce a new column with the "group" label:
indexes = np.array_split(df.index,N, axis=0)
for i,index in enumerate(indexes):
df.loc[index,'group'] = i
This makes grouby operations very convenient for instance calculation of mean value of each group:
df.groupby(by='group').mean()
You must make Foo::comparator
static or wrap it in a std::mem_fun
class object. This is because lower_bounds()
expects the comparer to be a class of object that has a call operator, like a function pointer or a functor object. Also, if you are using C++11 or later, you can also do as dwcanillas suggests and use a lambda function. C++11 also has std::bind
too.
Examples:
// Binding:
std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2));
// Lambda:
std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; });
Not exactly sure why, but changing the inner CSS to
display: inline-block;
seems to work.
[Update Sept 2020] Although my original answer here, from many years ago, seems to be helpful and is still getting upvotes, I now use the GSON library from Google, which I find to be more intuitive.
I've got the following code:
public void testJackson() throws IOException {
ObjectMapper mapper = new ObjectMapper();
File from = new File("albumnList.txt");
TypeReference<HashMap<String,Object>> typeRef
= new TypeReference<HashMap<String,Object>>() {};
HashMap<String,Object> o = mapper.readValue(from, typeRef);
System.out.println("Got " + o);
}
It's reading from a file, but mapper.readValue()
will also accept an InputStream
and you can obtain an InputStream
from a string by using the following:
new ByteArrayInputStream(astring.getBytes("UTF-8"));
There's a bit more explanation about the mapper on my blog.
The key is calling the parent's method using super.methodName();
class A {
// A protected method
protected doStuff()
{
alert("Called from A");
}
// Expose the protected method as a public function
public callDoStuff()
{
this.doStuff();
}
}
class B extends A {
// Override the protected method
protected doStuff()
{
// If we want we can still explicitly call the initial method
super.doStuff();
alert("Called from B");
}
}
var a = new A();
a.callDoStuff(); // Will only alert "Called from A"
var b = new B()
b.callDoStuff(); // Will alert "Called from A" then "Called from B"
An expansion for those who did a bit of fiddling around like I did.
The following work (from W3):
<input type="text" autofocus />
<input type="text" autofocus="" />
<input type="text" autofocus="autofocus" />
<input type="text" autofocus="AuToFoCuS" />
It is important to note that this does not work in CSS though. I.e. you can't use:
.first-input {
autofocus:"autofocus"
}
At least it didn't work for me...
I think this is similar to kouton's answer, but this one just takes in a timeStamp and returns a timestamp SOMEWHERE in the next month. You could use date("m", $nextMonthDateN) from there.
function nextMonthTimeStamp($curDateN){
$nextMonthDateN = $curDateN;
while( date("m", $nextMonthDateN) == date("m", $curDateN) ){
$nextMonthDateN += 60*60*24*27;
}
return $nextMonthDateN; //or return date("m", $nextMonthDateN);
}
In c# or Xamarin.ios, this.NavigationItem.HidesBackButton = true;
You could use *ngIf="teamMembers != 0"
to check whether data is present
This answer is for similar cases if the top answer by Alasdair does not help. (E.g. if the unwanted migration is created soon again with every new migration or if it is in a bigger migration that can not be reverted or the table has been removed manually.)
...delete the migration, without creating a new migration?
TL;DR: You can delete a few last reverted (confused) migrations and make a new one after fixing models. You can also use other methods to configure it to not create a table by migrate command. The last migration must be created so that it match the current models.
Cases why anyone do not want to create a table for a Model that must exist:
A) No such table should exist in no database on no machine and no conditions
class Meta: abstract = True
B) The table is created rarely, by something else or manually in a special way.
class Meta: managed = False
C) The table is used only on some machine (e.g. in development).
class Meta: managed = some_switch
.D) The project uses multiple databases in settings.DATABASES
allow_migrate
in order to differentiate the databases where the table should be created and where not.The migration is created in all cases A), B), C), D) with Django 1.9+ (and only in cases B, C, D with Django 1.8), but applied to the database only in appropriate cases or maybe never if required so. Migrations have been necessary for running tests since Django 1.8. The complete relevant current state is recorded by migrations even for models with managed=False in Django 1.9+ to be possible to create a ForeignKey between managed/unmanaged models or to can make the model managed=True later. (This question has been written at the time of Django 1.8. Everything here should be valid for versions between 1.8 to the current 2.2.)
If the last migration is (are) not easily revertible then it is possible to cautiously (after database backup) do a fake revert ./manage.py migrate --fake my_app 0010_previous_migration
, delete the table manually.
If necessary, create a fixed migration from the fixed model and apply it without changing the database structure ./manage.py migrate --fake my_app 0011_fixed_migration
.
white-space: nowrap
is the correct solution but it will prevent any break in a line. If you only want to prevent line breaks between two elements it gets a bit more complicated:
<p>
<span class="text">Some text</span>
<span class="icon"></span>
</p>
To prevent breaks between the spans but to allow breaks between "Some" and "text" can be done by:
p {
white-space: nowrap;
}
.text {
white-space: normal;
}
That's good enough for Firefox. In Chrome you additionally need to replace the whitespace between the spans with an
. (Removing the whitespace doesn't work.)
You may not have any collation issues in your database whatsoever, but if you restored a copy of your database from a backup on a server with a different collation than the origin, and your code is creating temporary tables, those temporary tables would inherit collation from the server and there would be conflicts with your database.
Ya Mahdi aj---for RelativeLayout
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<gradient
android:startColor="#7d000000"
android:endColor="@android:color/transparent"
android:angle="90" >
</gradient>
<corners android:radius="2dp" />
</shape>
</item>
<item
android:left="0dp"
android:right="3dp"
android:top="0dp"
android:bottom="3dp">
<shape android:shape="rectangle">
<padding
android:bottom="40dp"
android:top="40dp"
android:right="10dp"
android:left="10dp"
>
</padding>
<solid android:color="@color/Whitetransparent"/>
<corners android:radius="2dp" />
</shape>
</item>
</layer-list>
I have been banging my head against my monitor on this until a young-hip intern told me the secret is to "python setup.py install" inside the module directory.
For some reason, running the setup from there makes it just work.
To be clear, if your module's name is "foo":
[burnc7 (2016-06-21 15:28:49) git]# ls -l
total 1
drwxr-xr-x 7 root root 118 Jun 21 15:22 foo
[burnc7 (2016-06-21 15:28:51) git]# cd foo
[burnc7 (2016-06-21 15:28:53) foo]# ls -l
total 2
drwxr-xr-x 2 root root 93 Jun 21 15:23 foo
-rw-r--r-- 1 root root 416 May 31 12:26 setup.py
[burnc7 (2016-06-21 15:28:54) foo]# python setup.py install
<--snip-->
If you try to run setup.py from any other directory by calling out its path, you end up with a borked install.
DOES NOT WORK:
python /root/foo/setup.py install
DOES WORK:
cd /root/foo
python setup.py install
Not gonna happen with CSS only
Inline javascript
<a href='index.html'
onmouseover='this.style.textDecoration="none"'
onmouseout='this.style.textDecoration="underline"'>
Click Me
</a>
In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:
<a href="http://www.w3.org/Style/CSS"
style="{color: blue; background: white} /* a+=0 b+=0 c+=0 */
:visited {color: green} /* a+=0 b+=1 c+=0 */
:hover {background: yellow} /* a+=0 b+=1 c+=0 */
:visited:hover {color: purple} /* a+=0 b+=2 c+=0 */
">
</a>
but it was never implemented in the release of the spec as far as I know.
http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules
So the simplest way is,
alter table table_name change column_name column_name int(11) NULL;
Add the css styling text-align: center
to the control.
Ideally you would do this through a css class assigned to the control, but if you must do it directly, here is an example:
<asp:TextBox ID="myTextBox" runat="server" style="text-align: center"></asp:TextBox>
With python 3 you can use list_a[filter]
to get True
values. To get False
values use list_a[~filter]
One more example but using this keyword when setting value in constructor:
#include <iostream>
using namespace std;
struct Node {
int value;
Node(int value) {
this->value = value;
}
void print()
{
cout << this->value << endl;
}
};
int main() {
Node n = Node(10);
n.print();
return 0;
}
Compiled with GCC 8.1.0.
strtotime will convert your date string to a unix time stamp. (seconds since the unix epoch.
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$seconds_diff = $ts2 - $ts1;
Note: Due to changes made to jQuery 1.9 and jQuery UI, this answer is no longer the correct one. Please see @stankovski's answer below.
You need to find the tab's index first (which is just its position in a list) and then specifically select the tab using jQuery UI's provided select event (tabs->select).
var index = $('#tabs ul').index($('#tabId'));
$('#tabs ul').tabs('select', index);
Update: BTW - I do realize that this is (ultimately) still selecting by index. But, it doesn't require that you know the specific position of the tabs (particularly when they are dynamically generated as asked in the question).