Ok, for @AndrewS solution to work with v7 appCompat library:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:someNamespace="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/saved_badge"
someNamespace:showAsAction="always"
android:icon="@drawable/shape_notification" />
</menu>
.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.saved_badge);
MenuItemCompat.setActionView(item, R.layout.feed_update_count);
View view = MenuItemCompat.getActionView(item);
notifCount = (Button)view.findViewById(R.id.notif_count);
notifCount.setText(String.valueOf(mNotifCount));
}
private void setNotifCount(int count){
mNotifCount = count;
supportInvalidateOptionsMenu();
}
The rest of the code is the same.
One idiom is:
cd some_dir && ./configure --some-flags && make && make install
I realize that can get long, but for larger scripts you could break it into logical functions.
@SETLOCAL ENABLEDELAYEDEXPANSION
@REM Use WMIC to retrieve date and time
@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF NOT "%%~F"=="" (
SET /A SortDate = 10000 * %%F + 100 * %%D + %%A
set YEAR=!SortDate:~0,4!
set MON=!SortDate:~4,2!
set DAY=!SortDate:~6,2!
@REM Add 1000000 so as to force a prepended 0 if hours less than 10
SET /A SortTime = 1000000 + 10000 * %%B + 100 * %%C + %%E
set HOUR=!SortTime:~1,2!
set MIN=!SortTime:~3,2!
set SEC=!SortTime:~5,2!
)
)
@echo on
@echo DATE=%DATE%, TIME=%TIME%
@echo HOUR=!HOUR! MIN=!MIN! SEC=!SEC!
@echo YR=!YEAR! MON=!MON! DAY=!DAY!
@echo DATECODE= '!YEAR!!MON!!DAY!!HOUR!!MIN!'
Output:
DATE=2015-05-20, TIME= 1:30:38.59
HOUR=01 MIN=30 SEC=38
YR=2015 MON=05 DAY=20
DATECODE= '201505200130'
For Java 8 the following method works:
Refer, below code snippet
String fileURiString="file:///D:/etc/MySQL.txt";
URI fileURI=new URI(fileURiString);
File file=new File(fileURI);//File file=new File(fileURiString) - will generate exception
FileInputStream fis=new FileInputStream(file);
fis.close();
Having read above that svg is inline by default, I just added the following to the div:
<div style="text-align:center;">
and it did the trick for me.
Purists may not like it (it’s an image, not text) but in my opinion HTML and CSS screwed up over centring, so I think it’s justified.
I leave this function if you want to get multiples fields:
/// <summary>
/// Get properties separated by , (Ex: to invoke 'd => new { d.FirstName, d.LastName }')
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="exp"></param>
/// <returns></returns>
public static string GetFields<T>(Expression<Func<T, object>> exp)
{
MemberExpression body = exp.Body as MemberExpression;
var fields = new List<string>();
if (body == null)
{
NewExpression ubody = exp.Body as NewExpression;
if (ubody != null)
foreach (var arg in ubody.Arguments)
{
fields.Add((arg as MemberExpression).Member.Name);
}
}
return string.Join(",", fields);
}
If you are using React.js, you could do this:
render() {
// ...
<img
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}
src={item.src} key={item.key}
ref={item.key} />
// ... }
Where:
Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below
import 'package:jiffy/jiffy.dart';
var now = Jiffy().format("yyyy-MM-dd HH:mm:ss");
You can also do the following
var a = Jiffy().yMMMMd; // October 18, 2019
And you can also pass in your DateTime object, A string and an array
var a = Jiffy(DateTime(2019, 10, 18)).yMMMMd; // October 18, 2019
var a = Jiffy("2019-10-18").yMMMMd; // October 18, 2019
var a = Jiffy([2019, 10, 18]).yMMMMd; // October 18, 2019
If you have created dynamic Web project and have placed the required image in WebContent then you can access the image by using below mentioned code in Spring MVC:
<img src="Refresh.png" alt="Refresh" height="50" width="50">
You can also create folder named img and place the image inside the folder img and place that img folder inside WebContent then you can access the image by using below mentioned code:
<img src="img/Refresh.png" alt="Refresh" height="50" width="50">
You define a DELIMITER to tell the mysql client to treat the statements, functions, stored procedures or triggers as an entire statement. Normally in a .sql file you set a different DELIMITER like $$. The DELIMITER command is used to change the standard delimiter of MySQL commands (i.e. ;). As the statements within the routines (functions, stored procedures or triggers) end with a semi-colon (;), to treat them as a compound statement we use DELIMITER. If not defined when using different routines in the same file or command line, it will give syntax error.
Note that you can use a variety of non-reserved characters to make your own custom delimiter. You should avoid the use of the backslash (\) character because that is the escape character for MySQL.
DELIMITER isn't really a MySQL language command, it's a client command.
DELIMITER $$
/*This is treated as a single statement as it ends with $$ */
DROP PROCEDURE IF EXISTS `get_count_for_department`$$
/*This routine is a compound statement. It ends with $$ to let the mysql client know to execute it as a single statement.*/
CREATE DEFINER=`student`@`localhost` PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN
SELECT COUNT(*) INTO the_count FROM employees where department=the_department;
END$$
/*DELIMITER is set to it's default*/
DELIMITER ;
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.
It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.
Building on Billy Jakes awnser, I made a fully dynamic mock method with an out parameter. I'm posting this here for anyone who finds it usefull.
// Define a delegate with the params of the method that returns void.
delegate void methodDelegate(int x, out string output);
// Define a variable to store the return value.
bool returnValue;
// Mock the method:
// Do all logic in .Callback and store the return value.
// Then return the return value in the .Returns
mockHighlighter.Setup(h => h.SomeMethod(It.IsAny<int>(), out It.Ref<int>.IsAny))
.Callback(new methodDelegate((int x, out int output) =>
{
// do some logic to set the output and return value.
output = ...
returnValue = ...
}))
.Returns(() => returnValue);
From http://www.coderanch.com/t/236675/java-programmer-SCJP/certification/xff
The hex literal 0xFF is an equal int(255). Java represents int as 32 bits. It look like this in binary:
00000000 00000000 00000000 11111111
When you do a bit wise AND with this value(255) on any number, it is going to mask(make ZEROs) all but the lowest 8 bits of the number (will be as-is).
... 01100100 00000101 & ...00000000 11111111 = 00000000 00000101
& is something like % but not really.
And why 0xff? this in ((power of 2) - 1). All ((power of 2) - 1) (e.g 7, 255...) will behave something like % operator.
Then
In binary, 0 is, all zeros, and 255 looks like this:
00000000 00000000 00000000 11111111
And -1 looks like this
11111111 11111111 11111111 11111111
When you do a bitwise AND of 0xFF and any value from 0 to 255, the result is the exact same as the value. And if any value higher than 255 still the result will be within 0-255.
However, if you do:
-1 & 0xFF
you get
00000000 00000000 00000000 11111111
, which does NOT equal the original value of -1 (11111111
is 255 in decimal).
Few more bit manipulation: (Not related to the question)
X >> 1 = X/2
X << 1 = 2X
Check any particular bit is set(1) or not (0) then
int thirdBitTobeChecked = 1 << 2 (...0000100)
int onWhichThisHasTobeTested = 5 (.......101)
int isBitSet = onWhichThisHasTobeTested & thirdBitTobeChecked;
if(isBitSet > 0) {
//Third Bit is set to 1
}
Set(1) a particular bit
int thirdBitTobeSet = 1 << 2 (...0000100)
int onWhichThisHasTobeSet = 2 (.......010)
onWhichThisHasTobeSet |= thirdBitTobeSet;
ReSet(0) a particular bit
int thirdBitTobeReSet = ~(1 << 2) ; //(...1111011)
int onWhichThisHasTobeReSet = 6 ;//(.....000110)
onWhichThisHasTobeReSet &= thirdBitTobeReSet;
XOR
Just note that if you perform XOR operation twice, will results the same value.
byte toBeEncrypted = 0010 0110
byte salt = 0100 1011
byte encryptedVal = toBeEncrypted ^ salt == 0110 1101
byte decryptedVal = encryptedVal ^ salt == 0010 0110 == toBeEncrypted :)
One more logic with XOR is
if A (XOR) B == C (salt)
then C (XOR) B == A
C (XOR) A == B
The above is useful to swap two variables without temp like below
a = a ^ b; b = a ^ b; a = a ^ b;
OR
a ^= b ^= a ^= b;
.length
is a field, containing the capacity (NOT the number of elements the array contains at the moment) of arrays.
length()
is a method used by Strings (amongst others), it returns the number of chars in the String; with Strings, capacity and number of containing elements (chars) have the same value.
size()
is a method implemented by all members of Collection (lists, sets, stacks,...). It returns the number of elements (NOT the capacity; some collections even don´t have a defined capacity) the collection contains.'data' should be a stringified JavaScript object:
data: JSON.stringify({ "userName": userName, "password" : password })
To send your formData
, pass it to stringify
:
data: JSON.stringify(formData)
Some servers also require the application/json
content type:
contentType: 'application/json'
There's also a more detailed answer to a similar question here: Jquery Ajax Posting json to webservice
This works to sign the user out of the application, but not Google.
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
Source: https://developers.google.com/identity/sign-in/web/sign-in
I tried out solution suggested by Russ Bateman Here in the post
http://localhost:8080/Myapp
to http://localhost:8080/somepath/Myapp
But Didnt worked for me as I needed to have a *.war file that can hold the config and not the individual instance of server on my localmachine.
In order to do that I need jboss-web.xml placed in WEB-INF
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2008 Object Computing, Inc.
All rights reserved.
-->
<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 4.2//EN"
"http://www.jboss.org/j2ee/dtd/jboss-web_4_2.dtd">
<jboss-web>
<context-root>somepath/Myapp</context-root>
</jboss-web>
To watch out the runtime changes in value of a custom directive, use $observe
method of attrs
object, instead of putting $watch
inside a custom directive.
Here is the documentation for the same ... $observe docs
First off:
public class ProfileCollection implements Iterable<Profile> {
Second:
return m_Profiles.get(m_ActiveProfile);
For those who are still looking for a solution , the best way of doing it is to bind the event on the document itself and not to bind with the event "on ready" For e.g :
$(function ajaxform_reload() {
$(document).on("submit", ".ajax_forms", function (e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type: 'post',
url: url,
data: $(this).serialize(),
success: function (data) {
// DO WHAT YOU WANT WITH THE RESPONSE
}
});
});
});
Kibana is also a good solution. It is a data visualization platform for Elastic.If installed it runs by default on port 5601.
Out of the many things it provides. It has "Dev Tools" where we can do your debugging.
For example you can check your available indexes here using the command
GET /_cat/indices
Working for me only after installing Python 2.7.x (not 3.x) and then npm uninstall node-sass && npm install node-sass
like @Quinn Comendant said.
There is no trigger to perform code when the app is deleted from the device. Access to the keychain is dependant on the provisioning profile that is used to sign the application. Therefore no other applications would be able to access this information in the keychain.
It does not help with you aim to remove the password in the keychain when the user deletes application from the device but it should give you some comfort that the password is not accessible (only from a re-install of the original application).
Use this to cut off the non needed characters:
String.substring(0, maxLength);
Example:
String aString ="123456789";
String cutString = aString.substring(0, 4);
// Output is: "1234"
To ensure you are not getting an IndexOutOfBoundsException when the input string is less than the expected length do the following instead:
int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);
If you want your integers and doubles to have a certain length then I suggest you use NumberFormat to format your numbers instead of cutting off their string representation.
I just needed a simple testing button for react.js. Here is what I did and it worked.
function Testing(){
var f=function testing(){
console.log("Testing Mode activated");
UserData.authenticated=true;
UserData.userId='123';
};
console.log("Testing Mode");
return (<div><button onClick={f}>testing</button></div>);
}
This trick worked for me in Eclipse Luna (4.4.2): For a jar file I am using (htsjdk), I packed the source in a separate jar file (named htsjdk-2.0.1-src.jar; I could do this since htsjdk is open source) and stored it in the lib-src folder of my project. In my own Java source I selected an element I was using from the jar and hit F3 (Open declaration). Eclipse opened the class file and showed the button "Attach source". I clicked the button and pointed to the src jar file I had just put into the lib-src folder. Now I get the Javadoc when hovering over anything I’m using from the jar.
You can do it like this:
<input type="hidden" name="result" value="<?php foreach($postvalue as $value) echo $postvalue.","; ?>">
Firstly, a code block that looks like (function(){})()
is merely a function that is executed in place. Let's break it down a little.
1. (
2. function(){}
3. )
4. ()
Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help
1. function(){ .. }
2. (1)
3. 2()
You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.
An example of how it would be used.
(function(doc){
doc.location = '/';
})(document);//This is passed into the function above
As for the other questions about the plugins:
Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.
Type 2: This is again not a plugin as it does not extend the $.fn
object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.
Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.
There is a possible way to avoid a if-branch in the loop.
s.append("[ "); // there is a space after the left bracket
for (i = 0; i < 5; ++i) {
s.appendF("\"%d\",", i); // always add comma
}
s.back() = ']'; // modify last comma (or the space) to right bracket
select name, price
from (
select name, price,
row_number() over (order by price) r
from items
)
where r between 1 and 5;
public static bool IsPropertyExist(dynamic settings, string name)
{
if (settings is ExpandoObject)
return ((IDictionary<string, object>)settings).ContainsKey(name);
return settings.GetType().GetProperty(name) != null;
}
var settings = new {Filename = @"c:\temp\q.txt"};
Console.WriteLine(IsPropertyExist(settings, "Filename"));
Console.WriteLine(IsPropertyExist(settings, "Size"));
Output:
True
False
This doesn't work for a fact:
$table->timestamp('created_at')->default('CURRENT_TIMESTAMP');
It doesn't remove the 'default 0' that seems to come with selecting timestamp and it just appends the custom default. But we kind of need it without the quotes. Not everything that manipulates a DB is coming from Laravel4. That's his point. He wants custom defaults on certain columns like:
$table->timestamps()->default('CURRENT_TIMESTAMP');
I don't think it's possible with Laravel. I've been searching for an hour now to see whether it's possible.
Update: Paulos Freita's answer shows that it is possible, but the syntax isn't straightforward.
You can load the work book and then use lapply
, getSheets
and readWorksheet
and do something like this.
wb.mtcars <- loadWorkbook(system.file("demoFiles/mtcars.xlsx",
package = "XLConnect"))
sheet_names <- getSheets(wb.mtcars)
names(sheet_names) <- sheet_names
sheet_list <- lapply(sheet_names, function(.sheet){
readWorksheet(object=wb.mtcars, .sheet)})
I'm not quite sure what a "good way" of copying a file is, but assuming "good" means "fast", I could broaden the subject a little.
Current operating systems have long been optimized to deal with run of the mill file copy. No clever bit of code will beat that. It is possible that some variant of your copy techniques will prove faster in some test scenario, but they most likely would fare worse in other cases.
Typically, the sendfile
function probably returns before the write has been committed, thus giving the impression of being faster than the rest. I haven't read the code, but it is most certainly because it allocates its own dedicated buffer, trading memory for time. And the reason why it won't work for files bigger than 2Gb.
As long as you're dealing with a small number of files, everything occurs inside various buffers (the C++ runtime's first if you use iostream
, the OS internal ones, apparently a file-sized extra buffer in the case of sendfile
). Actual storage media is only accessed once enough data has been moved around to be worth the trouble of spinning a hard disk.
I suppose you could slightly improve performances in specific cases. Off the top of my head:
copy_file
sequentially (though you'll hardly notice the difference as long as the file fits in the OS cache)But all that is outside the scope of a general purpose file copy function.
So in my arguably seasoned programmer's opinion, a C++ file copy should just use the C++17 file_copy
dedicated function, unless more is known about the context where the file copy occurs and some clever strategies can be devised to outsmart the OS.
filter_by
uses keyword arguments, whereas filter
allows pythonic filtering arguments like filter(User.name=="john")
After trying everything that's out there without success, I found out, by accident, a functional and very easy way to get the action bar's default height.
Only tested in API 25 and 24
C#
Resources.GetDimensionPixelSize(Resource.Dimension.abc_action_bar_default_height_material);
Java
getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);
wget is capable of doing what you are asking. Just try the following:
wget -p -k http://www.example.com/
The -p
will get you all the required elements to view the site correctly (css, images, etc).
The -k
will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.
From the Wget docs:
‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.
Each link will be changed in one of the two ways:
The links to files that have been downloaded by Wget will be changed to refer
to the file they point to as a relative link.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
downloaded, then the link in doc.html will be modified to point to
‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
combinations of directories.
The links to files that have not been downloaded by Wget will be changed to
include host name and absolute path of the location they point to.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
../bar/img.gif), then the link in doc.html will be modified to point to
http://hostname/bar/img.gif.
Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.
Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads.
For those trying to make a UWP (Universal Windows) application, file permissions are much more restricted, and in general is deny by default. It also supersedes the system user permissions. You will basically only have access to files in either
You can read more here for details => https://docs.microsoft.com/en-us/windows/uwp/files/file-access-permissions
In Project Navigator
in the folder Pods
I had a Pods.framework
in there which was red. It was also present in Linked Frameworks and Libraries
. I removed both references and the error disappeared.
TL;DR
Remove Pods.framework
in:
Pods
Linked Frameworks and Libraries
You might have disabled the exec privileges, most of the LAMP packages have those disabled. Check your php.ini for this line:
disable_functions = exec
And remove the exec, shell_exec entries if there are there.
Good Luck!
Run these commands for Beyond Compare 2:
git config --global diff.tool bc2
git config --global difftool.bc2.cmd "\"c:/program files (x86)/beyond compare 2/bc2.exe\" \"$LOCAL\" \"$REMOTE\""
git config --global difftool.prompt false
Run these commands for Beyond Compare 3:
git config --global diff.tool bc3
git config --global difftool.bc3.cmd "\"c:/program files (x86)/beyond compare 3/bcomp.exe\" \"$LOCAL\" \"$REMOTE\""
git config --global difftool.prompt false
Then use git difftool
I have found the answer by @Slauma here very useful for speeding things up. I used the same sort of pattern for both inserts and updates - and performance rocketed.
What i think you do is while you change domain names, the sql dump file that you have you can replace all instances of old domain name with new one. This is only option available as there are no plugins that will help you do this.
This is quickest way ..
An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new
), whereas a class variable is a member of the class itself.
Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.
What’s the difference between a class variable and an instance variable?
This test class illustrates the difference:
public class Test {
public static String classVariable = "I am associated with the class";
public String instanceVariable = "I am associated with the instance";
public void setText(String string){
this.instanceVariable = string;
}
public static void setClassText(String string){
classVariable = string;
}
public static void main(String[] args) {
Test test1 = new Test();
Test test2 = new Test();
// Change test1's instance variable
test1.setText("Changed");
System.out.println(test1.instanceVariable); // Prints "Changed"
// test2 is unaffected
System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
// Change class variable (associated with the class itself)
Test.setClassText("Changed class text");
System.out.println(Test.classVariable); // Prints "Changed class text"
// Can access static fields through an instance, but there still is only one
// (not best practice to access static variables through instance)
System.out.println(test1.classVariable); // Prints "Changed class text"
System.out.println(test2.classVariable); // Prints "Changed class text"
}
}
Use @title
in your controllers when you want your variable to be available in your views.
The explanation is that @title
is an instance variable while title
is a local variable. Rails makes instance variables from controllers available to views because the template code (erb, haml, etc) is executed within the scope of the current controller instance.
(Expanding upon ????'s answer)
Style the canvas to fill the body. When rendering to the canvas take its size into account.
http://jsfiddle.net/mqFdk/356/
<!DOCTYPE html>
<html>
<head>
<title>aj</title>
</head>
<body>
<canvas id="c"></canvas>
</body>
</html>
CSS:
body {
margin: 0;
padding: 0
}
#c {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden
}
Javascript:
function redraw() {
var cc = c.getContext("2d");
c.width = c.clientWidth;
c.height = c.clientHeight;
cc.scale(c.width, c.height);
// Draw a circle filling the canvas.
cc.beginPath();
cc.arc(0.5, 0.5, .5, 0, 2*Math.PI);
cc.fill();
}
// update on any window size change.
window.addEventListener("resize", redraw);
// first draw
redraw();
You dont need one, you can just use:
if not number == 0:
sig = number/abs(number)
else:
sig = 0
Or create a function as described by others:
sign = lambda x: bool(x > 0) - bool(x < 0)
def sign(x):
return bool(x > 0) - bool(x < 0)
Because you imported scipy, not sparse. Try from scipy import sparse
?
In order for TypeScript Compiler to use all visible Type Definitions during compilation, types
option should be removed completely from compilerOptions
field in tsconfig.json
file.
This problem arises when there exists some types
entries in compilerOptions
field, where at the same time jest
entry is missing.
So in order to fix the problem, compilerOptions
field in your tscongfig.json
should either include jest
in types
area or get rid of types
comnpletely:
{
"compilerOptions": {
"esModuleInterop": true,
"target": "es6",
"module": "commonjs",
"outDir": "dist",
"types": ["reflect-metadata", "jest"], //<-- add jest or remove completely
"moduleResolution": "node",
"sourceMap": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
There is also a shorthand of doing this:
NSArray *persons = @[person1, person2, person3];
It's equivalent to
NSArray *persons = [NSArray arrayWithObjects:person1, person2, person3, nil];
As iiFreeman said, you still need to do proper memory management if you're not using ARC.
Below code will look for last used row in sheet1 and copy the entire range from A1 upto last used row in column A to Sheet2 at exact same location.
Sub test()
Dim lastRow As Long
lastRow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
Sheets("Sheet2").Range("A1:A" & lastRow).Value = Sheets("Sheet1").Range("A1:A" & lastRow).Value
End Sub
Which specific index? If you want 'Add New' to be first on the dropdownlist you can add it though the code like this:
<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server">
<asp:ListItem Text="Add New" Value="0" />
</asp:DropDownList>
If you want to add it at a different index, maybe the last then try:
ListItem lst = new ListItem ( "Add New" , "0" );
DropDownList1.Items.Insert( DropDownList1.Items.Count-1 ,lst);
1.- Remember the name you gave to the file and instead of using hdfs dfs -put. Use 'get' instead. See below.
$hdfs dfs -get /output-fileFolderName-In-hdfs
You could try doing
document.getElementById(id).innerHTML = ajax_response
os.chdir(r"D:\Folder1\Folder2")
os.rename(src,dst)
#src and dst should be inside Folder2
I came upon this post, and while it has already been answered, felt I should post some information that helped me with this problem specific to IE 10, and might help others arriving at this post with a similar problem.
I was baffled how animated gifs were just not displaying in IE 10 and then found this gem.
Tools→Internet Options→Advanced→MultiMedia→Play animations in webpages
hope this helps.
The difference between Response.Write()
and Response.Output.Write()
in ASP.NET. The short answer is that the latter gives you String.Format-style
output and the former doesn't. The long answer follows.
In ASP.NET the Response
object is of type HttpResponse
and when you say Response.Write
you're really saying (basically) HttpContext.Current.Response.Write
and calling one of the many overloaded Write
methods of HttpResponse
.
Response.Write
then calls .Write()
on it's internal TextWriter
object:
public void Write(object obj){ this._writer.Write(obj);}
HttpResponse
also has a Property called Output
that is of type, yes, TextWriter
, so:
public TextWriter get_Output(){ return this._writer; }
Which means you can do the Response
whatever a TextWriter
will let you. Now, TextWriters support a Write()
method aka String.Format
, so you can do this:
Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);
But internally, of course, this is happening:
public virtual void Write(string format, params object[] arg)
{
this.Write(string.Format(format, arg));
}
For me, now in 2018. The only thing that fixed my problem (a white glitchy-flicker line running through an image on hover) was applying this to my link element holding the image element that has transform: scale(1.05)
a {
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-transform: translateZ(0) scale(1.0, 1.0);
transform: translateZ(0) scale(1.0, 1.0);
-webkit-filter: blur(0);
filter: blur(0);
}
a > .imageElement {
transition: transform 3s ease-in-out;
}
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
Yes, this can be done via javascript feature detection ( or browser detection , e.g. Modernizr ) . Then, use yepnope.js to load required resources ( JS and/or CSS )
Just to that :)
$('#form-edit').trigger("reset");
$('#form-edit').find('select').each(function(){
$(this).change();
});
The simplest way would be to first replace
infs to NaN:
df.replace([np.inf, -np.inf], np.nan)
and then use the dropna
:
df.replace([np.inf, -np.inf], np.nan).dropna(subset=["col1", "col2"], how="all")
For example:
In [11]: df = pd.DataFrame([1, 2, np.inf, -np.inf])
In [12]: df.replace([np.inf, -np.inf], np.nan)
Out[12]:
0
0 1
1 2
2 NaN
3 NaN
The same method would work for a Series.
Window ? Preferences ? General ? Editors ? Text Editors ? Show line numbers.
Edit: I wrote this long ago but as @ArtOfWarfar and @voidstate mentioned you can now simply:
Right click the gutter and select "Show Line Numbers":
Notepad++ v6.5
Search menu -> Find... -> Mark tab -> Find what: your search text, check Bookmark Line, then Mark All. This will bookmark all the lines with the search term, you'll see the blue circles in the margin.
Then Search menu -> Bookmark -> Remove Bookmarked Lines. This will delete all the bookmarked lines.
You can also use a regex to search. This method won't result in a blank line like John's and will actually delete the line.
Older Versions
my friend by this u are not getting height of image stored in db.but you are getting view height.for getting height of image u have to create bitmap from db,s image.and than u can fetch height and width of imageview
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
ECMAScript ES6 added a new operator that lets you do this in a more practical way: ...Spread Operator.
Example without using the apply
method:
function a(...args){_x000D_
b(...args);_x000D_
b(6, ...args, 8) // You can even add more elements_x000D_
}_x000D_
function b(){_x000D_
console.log(arguments)_x000D_
}_x000D_
_x000D_
a(1, 2, 3)
_x000D_
Note This snippet returns a syntax error if your browser still uses ES5.
Editor's note: Since the snippet uses console.log()
, you must open your browser's JS console to see the result - there will be no in-page result.
It will display this result:
In short, the spread operator can be used for different purposes if you're using arrays, so it can also be used for function arguments, you can see a similar example explained in the official docs: Rest parameters
easy and simple code xD
void strrev (char s[]) {
int i;
int dim = strlen (s);
char l;
for (i = 0; i < dim / 2; i++) {
l = s[i];
s[i] = s[dim-i-1];
s[dim-i-1] = l;
}
}
If you're using docker you can use COMPOSER_PROCESS_TIMEOUT
environment:
COMPOSER_MEMORY_LIMIT: -1
COMPOSER_PROCESS_TIMEOUT: 2000 #seconds
I could not get any of these answers to work. Here's what I ended up putting at the very top of my Vagrantfile, before the Vagrant::Config.run do
block:
Vagrant.configure("2") do |config|
config.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", "1024"]
end
end
I noticed that the shortcut accessor style, "vb.memory = 1024", didn't seem to work.
import datetime
begin = datetime.date(2008, 8, 15)
end = datetime.date(2008, 9, 15)
next_day = begin
while True:
if next_day > end:
break
print next_day
next_day += datetime.timedelta(days=1)
You must ";" separator, CSV => Comma Separator Value
ofstream Morison_File ("linear_wave_loading.csv"); //Opening file to print info to
Morison_File << "'Time'; 'Force(N/m)' " << endl; //Headings for file
for (t = 0; t <= 20; t++) {
u = sin(omega * t);
du = cos(omega * t);
F = (0.5 * rho * C_d * D * u * fabs(u)) + rho * Area * C_m * du;
cout << "t = " << t << "\t\tF = " << F << endl;
Morison_File << t << ";" << F;
}
Morison_File.close();
If all other options have failed, trying recreating the data import task and/or the connection manager. If you've made any changes since the task was originally created, this can sometimes do the trick. I know it's the equivalent of rebooting, but, hey, if it works, it works.
Yes. In Windows Ctrl+V and in Linux pressing both mouse buttons nearly simultaneously.
In Windows I think this line in my _vimrc probably does it:
source $VIMRUNTIME/mswin.vim
In Linux I don't remember how I did it. It looks like I probably deleted some line from the default .vimrc file.
This is a guess. Generally recursion probably doesn't beat looping often or ever on problems of decent size if both are using really good algorithms(not counting implementation difficulty) , it may be different if used with a language w/ tail call recursion(and a tail recursive algorithm and with loops also as part of the language)-which would probably have very similar and possibly even prefer recursion some of the time.
Use expression(delta)
where 'delta' for lowercase d
and 'Delta' to get capital ?
.
Here's full list of Greek characters:
? a alpha
? ß beta
G ? gamma
? d delta
? e epsilon
? ? zeta
? ? eta
T ? theta
? ? iota
? ? kappa
? ? lambda
? µ mu
? ? nu
? ? xi
? ? omicron
? p pi
? ? rho
S s sigma
? t tau
? ? upsilon
F f phi
? ? chi
? ? psi
O ? omega
EDIT: Copied from comments, when using in conjunction with other words use like: expression(Delta*"price")
In the first case, the data are passed to the script via GET, in the second via POST.
http://docs.jquery.com/Ajax/load#urldatacallback
I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.
Function MySheet()
' uncomment the below line to make it Volatile
'Application.Volatile
MySheet = Application.Caller.Worksheet.Name
End Function
This should be the function you are looking for
Diagrams are back as of the June 11 2019 release
as stated:
Yes, we’ve heard the feedback; Database Diagrams is back.
SQL Server Management Studio (SSMS) 18.1 is now generally available
?? Latest Version Does Not Included It ??
Sadly, the last version of SSMS to have database diagrams as a feature was version v17.9.
Since that version, the newer preview versions starting at v18.* have, in their words "...feature has been deprecated".
Hope is not lost though, for one can still download and use v17.9 to use database diagrams which as an aside for this question is technically not a ER diagramming tool.
As of this writing it is unclear if the release version of 18 will have the feature, I hope so because it is a feature I use extensively.
JUnit since 5.5 allows @TestMethodOrder(OrderAnnotation.class)
on class and @Order(1)
on test-methods.
JUnit old versions allow test methods run ordering using class annotations:
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@FixMethodOrder(MethodSorters.JVM)
@FixMethodOrder(MethodSorters.DEFAULT)
By default test methods are run in alphabetical order. So, to set specific methods order you can name them like:
a_TestWorkUnit_WithCertainState_ShouldDoSomething b_TestWorkUnit_WithCertainState_ShouldDoSomething c_TestWorkUnit_WithCertainState_ShouldDoSomething
Or
_1_TestWorkUnit_WithCertainState_ShouldDoSomething _2_TestWorkUnit_WithCertainState_ShouldDoSomething _3_TestWorkUnit_WithCertainState_ShouldDoSomething
You can find examples here.
Since awk and perl are closely related...
Perl equivalents of @Dennis's awk solutions:
To print the second line:
perl -ne 'print if $. == 2' file
To print the second field:
perl -lane 'print $F[1]' file
To print the third field of the fifth line:
perl -lane 'print $F[2] if $. == 5' file
Perl equivalent of @Glenn's solution:
Print the j'th field of the i'th line
perl -lanse 'print $F[$j-1] if $. == $i' -- -i=5 -j=3 file
Perl equivalents of @Hai's solutions:
if you are looking for second columns that contains abc:
perl -lane 'print if $F[1] =~ /abc/' foo
... and if you want to print only a particular column:
perl -lane 'print $F[2] if $F[1] =~ /abc/' foo
... and for a particular line number:
perl -lane 'print $F[2] if $F[1] =~ /abc/ && $. == 5' foo
-l
removes newlines, and adds them back in when printing
-a
autosplits the input line into array @F
, using whitespace as the delimiter
-n
loop over each line of the input file
-e
execute the code within quotes
$F[1]
is the second element of the array, since Perl starts at 0
$.
is the line number
Use mysql row instead
mysql_fetch_row($r)
Meanwhile consider using mysqli or PDO
?>
If try to print the f object, then you will see that there is f.object that can be probed for getting the selected item (applicable for all rails version > 2.3)
logger.warn("f #{f.object.inspect}")
so, use the following script to get the proper selected option:
:selected => f.object.your_field
Or second solution
you can try to connect using Direct not TNS by providing host and port in the connect screen of Toad
I installed the JDK 32 bit because of that I am getting the errors. After installing JDK 64 bit http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html jdk-8u131-linux-x64.tar.gz(please download the 64 version) and download 64 bit "eclipse-inst-linux64.tar.gz".
I suggest Oj as it is waaaaaay faster than the standard JSON library.
In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:
sc.exe config Service obj= user password= pass
Specyfying the .exe extension, PowerShell bypasses the alias lookup.
HTH
Use:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= TRUNC(SYSDATE) - 30
SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date
that is 30 days previous including the current time.
Depending on your needs, you could also look at using ADD_MONTHS:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)
This error can happen because some MFC library (eg. mfc120.dll) from which the DLL is dependent is missing in windows/system32 folder.
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directive’s value: it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}
Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.
You can easily create a timer functionality by using setInterval.Below is the code which you can use it to create the timer.
http://jsfiddle.net/ayyadurai/GXzhZ/1/
window.onload = function() {_x000D_
var minute = 5;_x000D_
var sec = 60;_x000D_
setInterval(function() {_x000D_
document.getElementById("timer").innerHTML = minute + " : " + sec;_x000D_
sec--;_x000D_
if (sec == 00) {_x000D_
minute --;_x000D_
sec = 60;_x000D_
if (minute == 0) {_x000D_
minute = 5;_x000D_
}_x000D_
}_x000D_
}, 1000);_x000D_
}
_x000D_
Registration closes in <span id="timer">05:00<span> minutes!
_x000D_
Both are the same thing but many of the databases are not providing the varying char mainly postgreSQL is providing. So for the multi database like Oracle Postgre and DB2 it is good to use the Varchar
Use %0D%0A
for a line break in your body
Example (Demo):
<a href="mailto:[email protected]?subject=Suggestions&body=name:%0D%0Aemail:">test</a>?
^^^^^^
To mock static method you should use a Powermock look at: https://github.com/powermock/powermock/wiki/MockStatic. Mockito doesn't provide this functionality.
You can read nice a article about mockito: http://refcardz.dzone.com/refcardz/mockito
Try to create a new key store and replace with old one, then rebuild a new signed APK.
Update: Note that if you're using a http connection with server ,you should use SSL.
Take a look at: https://developer.android.com/distribute/best-practices/develop/understand-play-policies
I got rid of my issue by changing File > Workspace and then, after the restart, reset the Workspace again.
Like all other had said above, you need to add path. But not sure for what reason if I add C:\xampp\php
in path of System Variable won't work but if I add it in path of User Variable work fine.
Although I had added and using other command line tools by adding in system variables work fine
So just in case if someone had same problem as me. Windows 10
In .NET 3.0 and later you can use the ISOWeek.GetWeekOfDate
-Method.
Note that the year in the year + week number format might differ from the year of the DateTime
because of weeks that cross the year boundary.
echo You must invoke st from within branch directory
SvnUrl=`svn info | grep URL | sed 's/URL: //'`
SvnVer=`svn info | grep Revision | sed 's/Revision: //'`
svn diff -r $SvnVer --summarize $SvnUrl
The best way to avoid mathematical imprecision is to convert to a string, but ensure that it is in the "dot" format you expect by using toLocaleString:
function getDecimals(n) {
// Note that maximumSignificantDigits defaults to 3 so your decimals will be rounded if not changed.
const parts = n.toLocaleString('en-US', { maximumSignificantDigits: 18 }).split('.')
return parts.length > 1 ? Number('0.' + parts[1]) : 0
}
console.log(getDecimals(10.58))
_x000D_
I ran into this issue only to discover a disconnect in one of my library objects. For some reason the project was copying the dll from the old path and not from my development path with the changes. Keep an eye on what dll's are being copied when you compile.
Product Version
may be preferred if you're using versioning via GitVersion or other versioning software.
To get this from within your class library you can call System.Diagnostics.FileVersionInfo.ProductVersion
:
using System.Diagnostics;
using System.Reflection;
//...
var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion
static block is used for any technology to initialize static data member in dynamic way,or we can say for the dynamic initialization of static data member static block is being used..Because for non static data member initialization we have constructor but we do not have any place where we can dynamically initialize static data member
Eg:-class Solution{
// static int x=10;
static int x;
static{
try{
x=System.out.println();
}
catch(Exception e){}
}
}
class Solution1{
public static void main(String a[]){
System.out.println(Solution.x);
}
}
Now my static int x will initialize dynamically ..Bcoz when compiler will go to Solution.x it will load Solution Class and static block load at class loading time..So we can able to dynamically initialize that static data member..
}
To list all of the packages in the active environment, use:
conda list
To list all of the packages in a deactivated environment, use:
conda list -n myenv
I always use Gliffy works perfectly and does lots of things including class diagrams.
You can make use of variable NF
which is set to the total number of fields in the input record:
awk '{print $(NF-1),"\t",$NF}' file
this assumes that you have at least 2 fields.
As in any unix-based environment, you can use the sudo
command:
$ sudo script-name
It will ask for your password (your own, not a separate root
password).
You can only select columns that are in the group or used in an aggregate function. You can use a join to get this working
select s1.*
from sensorTable s1
inner join
(
SELECT sensorID, max(timestamp) as mts
FROM sensorTable
GROUP BY sensorID
) s2 on s2.sensorID = s1.sensorID and s1.timestamp = s2.mts
You can do that with a grid:
article {
display: grid;
}
.one {
grid-area: 1 / 1 / 2 / 2;
}
.two {
grid-area: 1 / 1 / 2 / 2;
}
a=5; i=++a + ++a + a++;
is
i = 7 + 6 + 7
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6
. then a=7
is provided to post increment => 7 + 6 + 7 =20
and a =8
.
a=5; i=a++ + ++a + ++a;
is
i=7 + 7 + 6
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6
.then a=7
is provided to post increment => 7 + 7 + 6 =20
and a =8
.
A while ago I was in a similar situation (allthough I had a little WPF knowledge already), so I started a community wiki. There are a lot of great ressources there:
What applications could I study to understand (Data)Model-View-ViewModel?
The pg_ctl status
command suggested in other answers checks that the postmaster process exists and if so reports that it's running. That doesn't necessarily mean it is ready to accept connections or execute queries.
It is better to use another method like using psql
to run a simple query and checking the exit code, e.g. psql -c 'SELECT 1'
, or use pg_isready
to check the connection status.
As Maciej Jonczyk mentioned, you may also need to increase margins
par(las=2)
par(mar=c(8,8,1,1)) # adjust as needed
plot(...)
check this
list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
list[0:10]
Outputs:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If anybody still looking at this question, the currently accepted answer is now outdated:
Since Python 3.7* the dictionaries are order-preserving, that is they now behave exactly as collections.OrderedDict
s used to. Unfortunately, there is still no dedicated method to index into keys()
/ values()
of the dictionary, so getting the first key / value in the dictionary can be done as
first_key = list(colors)[0]
first_val = list(colors.values())[0]
or alternatively (this avoids instantiating the keys view into a list):
def get_first_key(dictionary):
for key in dictionary:
return key
raise IndexError
first_key = get_first_key(colors)
first_val = colors[first_key]
If you need an n
-th key, then similarly
def get_nth_key(dictionary, n=0):
if n < 0:
n += len(dictionary)
for i, key in enumerate(dictionary.keys()):
if i == n:
return key
raise IndexError("dictionary index out of range")
(*CPython 3.6 already included ordered dicts, but this was only an implementation detail. The language specification includes ordered dicts from 3.7 onwards.)
A boilerplate is a unit of writing that can be reused over and over without change. By extension, the idea is sometimes applied to reusable programming, as in “boilerplate code
Have you tried (from a command line)
java -jar jbpm-installer-3.2.7.jar
or double clicking it with the mouse ?
Found this and this by googling.
Hope it helps
make interface into custom adapter class and handling click event on recycler view..
onItemClickListner onItemClickListner;
public void setOnItemClickListner(CommentsAdapter.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(Contact contact);//pass your object types.
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
// below code handle click event on recycler view item.
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onItemClickListner.onClick(mContectList.get(position));
}
});
}
after define adapter and bind into recycler view called below code..
adapter.setOnItemClickListner(new CommentsAdapter.onItemClickListner() {
@Override
public void onClick(Contact contact) {
contectList.remove(contectList.get(contectList.indexOf(contact)));
adapter.notifyDataSetChanged();
}
});
}
Break enter Keyword line in Textarea using CSS:
white-space: pre-wrap;
You need to initialise bin, e.g.
bin = malloc(1);
bin[0] = '\0';
or use calloc:
bin = calloc(1, 1);
You also have a bug here:
bin = (char *)realloc(bin, sizeof(char) * (sizeof(bin)+1));
this needs to be:
bin = (char *)realloc(bin, sizeof(char) * (strlen(bin)+1));
(i.e. use strlen
, not sizeof
).
And you should increase the size before calling strcat.
And you're not freeing bin, so you have a memory leak.
And you need to convert 0, 1 to '0', '1'.
And you can't strcat a char to a string.
So apart from that, it's close, but the code should probably be more like this (warning, untested !):
int int_to_bin(int k)
{
char *bin;
int tmp;
bin = calloc(1, 1);
while (k > 0)
{
bin = realloc(bin, strlen(bin) + 2);
bin[strlen(bin) - 1] = (k % 2) + '0';
bin[strlen(bin)] = '\0';
k = k / 2;
}
tmp = atoi(bin);
free(bin);
return tmp;
}
In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializable from the fxml library.
import javafx.fxml.Initializable;
class MyController implements Initializable {
@FXML private TableView<MyModel> tableView;
@Override
public void initialize(URL location, ResourceBundle resources) {
tableView.getItems().addAll(getDataFromSource());
}
}
Parameters:
location - The location used to resolve relative paths for the root object, or null if the location is not known.
resources - The resources used to localize the root object, or null if the root object was not localized.
And the note of the docs why the simple way of using @FXML public void initialize()
works:
NOTE
This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.
I just came across this as a really nice and elegant solution:
Math.random().toString(36).slice(2)
Notes on this implementation:
Math.random()
, the output may be predictable and therefore not necessarily unique.synchronous / asynchronous is to describe the relation between two modules.
blocking / non-blocking is to describe the situation of one module.
An example:
Module X: "I".
Module Y: "bookstore".
X asks Y: do you have a book named "c++ primer"?
blocking: before Y answers X, X keeps waiting there for the answer. Now X (one module) is blocking. X and Y are two threads or two processes or one thread or one process? we DON'T know.
non-blocking: before Y answers X, X just leaves there and do other things. X may come back every two minutes to check if Y has finished its job? Or X won't come back until Y calls him? We don't know. We only know that X can do other things before Y finishes its job. Here X (one module) is non-blocking. X and Y are two threads or two processes or one process? we DON'T know. BUT we are sure that X and Y couldn't be one thread.
synchronous: before Y answers X, X keeps waiting there for the answer. It means that X can't continue until Y finishes its job. Now we say: X and Y (two modules) are synchronous. X and Y are two threads or two processes or one thread or one process? we DON'T know.
asynchronous: before Y answers X, X leaves there and X can do other jobs. X won't come back until Y calls him. Now we say: X and Y (two modules) are asynchronous. X and Y are two threads or two processes or one process? we DON'T know. BUT we are sure that X and Y couldn't be one thread.
Please pay attention on the two bold-sentences above. Why does the bold-sentence in the 2) contain two cases whereas the bold-sentence in the 4) contains only one case? This is a key of the difference between non-blocking and asynchronous.
Here is a typical example about non-blocking & synchronous:
// thread X
while (true)
{
msg = recv(Y, NON_BLOCKING_FLAG);
if (msg is not empty)
{
break;
}
else
{
sleep(2000); // 2 sec
}
}
// thread Y
// prepare the book for X
send(X, book);
You can see that this design is non-blocking (you can say that most of time this loop does something nonsense but in CPU's eyes, X is running, which means that X is non-blocking) whereas X and Y are synchronous because X can't continue to do any other things(X can't jump out of the loop) until it gets the book from Y.
Normally in this case, make X blocking is much better because non-blocking spends much resource for a stupid loop. But this example is good to help you understand the fact: non-blocking doesn't mean asynchronous.
The four words do make us confused easily, what we should remember is that the four words serve for the design of architecture. Learning about how to design a good architecture is the only way to distinguish them.
For example, we may design such a kind of architecture:
// Module X = Module X1 + Module X2
// Module X1
while (true)
{
msg = recv(many_other_modules, NON_BLOCKING_FLAG);
if (msg is not null)
{
if (msg == "done")
{
break;
}
// create a thread to process msg
}
else
{
sleep(2000); // 2 sec
}
}
// Module X2
broadcast("I got the book from Y");
// Module Y
// prepare the book for X
send(X, book);
In the example here, we can say that
If you need, you can also describe those threads created in X1 with the four words.
The more important things are: when do we use synchronous instead of asynchronous? when do we use blocking instead of non-blocking? Is making X1 blocking better than non-blocking? Is making X and Y synchronous better than asynchronous? Why is Nginx non-blocking? Why is Apache blocking? These questions are what you must figure out.
To make a good choice, you must analyze your need and test the performance of different architectures. There is no such an architecture that is suitable for various of needs.
FUNCTIONAL REQUIREMENTS the activities the system must perform
brew switch to python3 by default, so if you want to still set python2 as default bin python, running:
brew unlink python && brew link python2 --force
I also had same problem then I found this on there documentation page
So if you want to create a project by name of test_laravel
in directory /Applications/MAMP/htdocs/
then what you need to do is
go to your project parent directory
cd /Applications/MAMP/htdocs
and fire this command
composer create-project laravel/laravel test_laravel --prefer-dist
that's it, this is really easy and it also creates Application Key automatically for you
If you want to provide a timeout for a particular query, then CommandTimeout is the way forward.
Its usage is:
command.CommandTimeout = 60; //The time in seconds to wait for the command to execute. The default is 30 seconds.
First step is to find out which ruby is being called:
$ which ruby
Your system says:
/usr/bin/ruby
This is NOT the shim used by rbenv, which (on MacOS) should look like:
/Users/<username>/.rbenv/shims/ruby
The shim is actually a script that acts like a redirect to the version of ruby you set.
I recommend that for trouble shooting you unset the project specific "local" version, and the shell specific "shell" version and just test using the "global" version setting which is determined in a plain text file in ~/.rbenv/version which will just be the version number "1.9.3" in your case.
$ rbenv global 1.9.3
$ rbenv local --unset
$ rbenv shell --unset
You can do ls -laG
in the root of your project folder (not the home folder) to make sure there is no longer a ".ruby-version" file there.
You can use rbenv versions
to identify which version rbenv is set to use (and the location and name of the file that is setting that):
$ rbenv versions
NONE OF THAT MATTERS until you set the path correctly.
Use this to make sure your *MacOS will obey you:
$ rbenv init -
Followed by:
$ which ruby
To make sure it looks like:
/Users/<username>/.rbenv/shims/ruby
Then run this to add the line to your profile so it runs each time you open a new terminal window:
$ echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
There are other ways to modify the path, feel free to substitute any of them instead of running the rbenv init.
NOTE: reinstall Rails with:
$ gem install rails
If you were trying to run Ruby on Rails, then you need to have this all working first, then install the rails gem again. A previous install of Rails will use a hard coded path to the wrong ruby and several other things will be in the wrong place, so just install the gem again.
P. S. If your MacOS won't obey you (*mentioned above) then you may have to find another way to modify your path, but that's unlikely to be a problem because "Macs just work" ;)
Goto
I found that if the chosen perspective doesn't match the type of the current file, then "go to matching brace" doesn't work. However, changing perspectives makes it work again. So, for example, when I have a PHP file open, but, say, the Java perspective active, pressing Ctrl + Shift + P does nothing. For the same file with the PHP perspective active, pressing Ctrl + Shift + P does exactly what you'd expect and puts my cursor beside the closing brace relative to the one it started at.
You can use a subquery. The subquery will get the Max(CompletedDate)
. You then take this value and join on your table again to retrieve the note associate with that date:
select ET1.TrainingID,
ET1.CompletedDate,
ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
select Max(CompletedDate) CompletedDate, TrainingID
from HR_EmployeeTrainings
--where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
group by TrainingID
) ET2
on ET1.TrainingID = ET2.TrainingID
and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID
I was setting MIME type from .NET code as below -
File(generatedFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
My application generates excel using OpenXML SDK. This MIME type worked -
vnd.openxmlformats-officedocument.spreadsheetml.sheet
Give this a go:
<option onclick="parent.location='#5.2'">Bookmark 2</option>
You don't really need to do it all in jQuery to do that smoothly. Do it like this:
$(".nextbutton").click(function() {
document.forms["form1"].submit();
});
$(".btncancel").button({ disabled: true });
Here 'btncancel' is the class name of the button.
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
You do not need to parse every single line and then concatenate them again...
Source.fromFile(path)(Codec.UTF8).mkString
I prefer to use this:
import scala.io.{BufferedSource, Codec, Source}
import scala.util.Try
def readFileUtf8(path: String): Try[String] = Try {
val source: BufferedSource = Source.fromFile(path)(Codec.UTF8)
val content = source.mkString
source.close()
content
}
You can set display attribute as none to hide a label.
<label id="excel-data-div" style="display: none;"></label>
You did forget to include stdafx.h
in your source (as I cannot see it your code). If you didn't, then make sure #include "stdafx.h"
is the first line in your .cpp
file, otherwise you will see the same error even if you've included "stdafx.h"
in your source file (but not in the very beginning of the file).
I have the same problem right now but this article helps me. Updates for the year 2020!
I got the solution from this article:
https://dev.to/imamcu07/embed-or-display-image-to-html-page-from-google-drive-3ign
These are the steps from the article:
After Replace ID: https://drive.google.com/thumbnail?id=14hz3ySPn-zBd4Tu3NtY1F05LSGdFfWvp
<img>
tag.And now it should work.
or sometimes it's very easy just type Process.Start("http://www.example.com/")
then change the http://www.example.com/")
to me, i just do this :
rm -rf ~/.ssh/known_hosts
then :
i just ssh to the target host and all will be okay. This only if you dont know, what permission and the default owner of "known_hosts" file.
From a pipe
# This Is a cat
'This', 'Is', 'a', 'cat' | & {"$input"}
# This-Is-a-cat
'This', 'Is', 'a', 'cat' | & {$ofs='-';"$input"}
Write-Host
# This Is a cat
Write-Host 'This', 'Is', 'a', 'cat'
# This-Is-a-cat
Write-Host -Separator '-' 'This', 'Is', 'a', 'cat'
select * from information_schema.TRIGGERS;
That's because you have the Date in American format in line[i]
and UK format in the FormatString
.
11/20/2011
M / d/yyyy
I'm guessing you might need to change the FormatString to:
"M/d/yyyy h:mm"
git rm --cached *.FileExtension
This must ignore all files from this extension
maybe you want ifelse
:
a <- c(1,1,1,1,0,0,0,0,2,2)
ifelse(a>0,a/sum(a),1)
[1] 0.125 0.125 0.125 0.125 1.000 1.000 1.000 1.000
[9] 0.250 0.250
General case, not just for value types:
static class ExtensionsThatWillAppearOnEverything
{
public static T IfDefaultGiveMe<T>(this T value, T alternate)
{
if (value.Equals(default(T))) return alternate;
return value;
}
}
var result = query.FirstOrDefault().IfDefaultGiveMe(otherDefaultValue);
Again, this can't really tell if there was anything in your sequence, or if the first value was the default.
If you care about this, you could do something like
static class ExtensionsThatWillAppearOnIEnumerables
{
public static T FirstOr<T>(this IEnumerable<T> source, T alternate)
{
foreach(T t in source)
return t;
return alternate;
}
}
and use as
var result = query.FirstOr(otherDefaultValue);
although as Mr. Steak points out this could be done just as well by .DefaultIfEmpty(...).First()
.
The easiest way to do this is just to add zero to your result.
i.e.
$A=($row['SUM'Price']+0);
echo $A;
hope this helps!!
My solution:
//Object forEachDone
Object.defineProperty(Array.prototype, "forEachDone", {
enumerable: false,
value: function(task, cb){
var counter = 0;
this.forEach(function(item, index, array){
task(item, index, array);
if(array.length === ++counter){
if(cb) cb();
}
});
}
});
//Array forEachDone
Object.defineProperty(Object.prototype, "forEachDone", {
enumerable: false,
value: function(task, cb){
var obj = this;
var counter = 0;
Object.keys(obj).forEach(function(key, index, array){
task(obj[key], key, obj);
if(array.length === ++counter){
if(cb) cb();
}
});
}
});
Example:
var arr = ['a', 'b', 'c'];
arr.forEachDone(function(item){
console.log(item);
}, function(){
console.log('done');
});
// out: a b c done
Many times the problem comes because php
does not support short open tags in php.ini
file, i.e:
<?
phpinfo();
?>
You must use:
<?php
phpinfo();
?>
Object
is more restrictive than any
. For example:
let a: any;
let b: Object;
a.nomethod(); // Transpiles just fine
b.nomethod(); // Error: Property 'nomethod' does not exist on type 'Object'.
The Object
class does not have a nomethod()
function, therefore the transpiler will generate an error telling you exactly that. If you use any
instead you are basically telling the transpiler that anything goes, you are providing no information about what is stored in a
- it can be anything! And therefore the transpiler will allow you to do whatever you want with something defined as any
.
So in short
any
can be anything (you can call any method etc on it without compilation errors)Object
exposes the functions and properties defined in the Object
class.I got this error in mysql command line using this query:
source `db.sql`;
I changed the above to the following to make it work:
source db.sql;
Link your custom.css file as the last entry below the bootstrap.css. Custom.css style definitions will override bootstrap.css
Html
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/custom.css" rel="stylesheet">
Copy all style definitions of legend in custom.css and make changes in it (like margin-bottom:5px; -- This will overrider margin-bottom:20px; )
If you installed opencv 2.4.2 then you need to change the -lopencv_core240
to -lopencv_core242
I made the same mistake.
I would say that J2EE experience = in-depth experience with a few J2EE technologies, general knowledge about most J2EE technologies, and general experience with enterprise software in general.
Start by adding a regular matInput to your template. Let's assume you're using the formControl directive from ReactiveFormsModule to track the value of the input.
Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a simple form control, progress to using multiple controls in a group, validate form values, and implement more advanced forms.
import { FormsModule, ReactiveFormsModule } from "@angular/forms"; //this to use ngModule
...
imports: [
BrowserModule,
AppRoutingModule,
HttpModule,
FormsModule,
RouterModule,
ReactiveFormsModule,
BrowserAnimationsModule,
MaterialModule],
use
:%s/pattern/\0/g
when pattern string is too long and you don't like to type it all again.
In my case it was www
and non-www
URL. Actual site had www
URL and the Authorized Redirect URIs in Google Developer Console had non-www
URL. Hence, there was mismatch in redirect URI. I solved it by updating Authorized Redirect URIs
in Google Developer Console to www
URL.
Other common URI mismatch are:
http://
in Authorized Redirect URIs and https://
as actual URL, or vice-versahttp://example.com/
) in Authorized Redirect URIs and not using trailing slash (http://example.com
) as actual URL, or vice-versaHere are the step-by-step screenshots of Google Developer Console so that it would be helpful for those who are getting it difficult to locate the developer console page to update redirect URIs.
Select your Project
- Click on the menu icon
- Click on
API Manager
menu
- Click on
Credentials
menu. And underOAuth 2.0 Client IDs
, you will find your client name. In my case, it isWeb Client 1
. Click on it and a popup will appear where you can edit Authorized Javascript Origin and Authorized redirect URIs.
Here is a Google article on creating project and client ID.
For column types Rails supports out of the box - like the string in this question - the best approach is to set the column default in the database itself as Daniel Kristensen indicates. Rails will introspect on the DB and initialize the object accordingly. Plus, that makes your DB safe from somebody adding a row outside of your Rails app and forgetting to initialize that column.
For column types Rails doesn't support out of the box - e.g. ENUM columns - Rails won't be able to introspect the column default. For these cases you do not want to use after_initialize (it is called every time an object is loaded from the DB as well as every time an object is created using .new), before_create (because it occurs after validation), or before_save (because it occurs upon update too, which is usually not what you want).
Rather, you want to set the attribute in a before_validation on: create, like so:
before_validation :set_status_because_rails_cannot, on: :create
def set_status_because_rails_cannot
self.status ||= 'P'
end
Ok, this is actually four different question. I'll address them one by one:
are both equals for the compiler? (speed, perf...)
Yes. The pointer dereferenciation and decay from type int (*)[100][280]
to int (*)[280]
is always a noop to your CPU. I wouldn't put it past a bad compiler to generate bogus code anyways, but a good optimizing compiler should compile both examples to the exact same code.
is one of these solutions eating more memory than the other?
As a corollary to my first answer, no.
what is the more frequently used by developers?
Definitely the variant without the extra (*pointer)
dereferenciation. For C programmers it is second nature to assume that any pointer may actually be a pointer to the first element of an array.
what is the best way, the 1st or the 2nd?
That depends on what you optimize for:
Idiomatic code uses variant 1. The declaration is missing the outer dimension, but all uses are exactly as a C programmer expects them to be.
If you want to make it explicit that you are pointing to an array, you can use variant 2. However, many seasoned C programmers will think that there's a third dimension hidden behind the innermost *
. Having no array dimension there will feel weird to most programmers.
Add a 'class' constraint (or more detailed, like a base class or interface of your exepected T objects):
private static T ReadData<T>(XmlReader reader, string value) where T : class
{
reader.MoveToAttribute(value);
object readData = reader.ReadContentAsObject();
return (T)readData;
}
or where T : IMyInterface
or where T : new()
, etc
Using regex:
str = 'string'
n = 1 #to remove first n characters
str[/.{#{str.size-n}}\z/] #=> "tring"
While Nakilon's solution works, at least as far as getting past the error, in my case, I had this weird f-ed up character originating from Microsoft Excel converted to CSV that was registering in ruby as a (get this) cyrillic K which in ruby was a bolded K. To fix this I used 'iso-8859-1' viz. CSV.parse(f, :encoding => "iso-8859-1")
, which turned my freaky deaky cyrillic K's into a much more manageable /\xCA/
, which I could then remove with string.gsub!(/\xCA/, '')
The problem with other answers is they either use a global, which can be overwritten when several functions are in a call chain, or echo
which means your function cannot output diagnostic info (you will forget your function does this and the "result", i.e. return value, will contain more info than your caller expects, leading to weird bug), or eval
which is way too heavy and hacky.
The proper way to do this is to put the top level stuff in a function and use a local
with bash's dynamic scoping rule. Example:
func1()
{
ret_val=hi
}
func2()
{
ret_val=bye
}
func3()
{
local ret_val=nothing
echo $ret_val
func1
echo $ret_val
func2
echo $ret_val
}
func3
This outputs
nothing
hi
bye
Dynamic scoping means that ret_val
points to a different object depending on the caller! This is different from lexical scoping, which is what most programming languages use. This is actually a documented feature, just easy to miss, and not very well explained, here is the documentation for it (emphasis is mine):
Variables local to the function may be declared with the local builtin. These variables are visible only to the function and the commands it invokes.
For someone with a C/C++/Python/Java/C#/javascript background, this is probably the biggest hurdle: functions in bash are not functions, they are commands, and behave as such: they can output to stdout
/stderr
, they can pipe in/out, they can return an exit code. Basically there is no difference between defining a command in a script and creating an executable that can be called from the command line.
So instead of writing your script like this:
top-level code
bunch of functions
more top-level code
write it like this:
# define your main, containing all top-level code
main()
bunch of functions
# call main
main
where main()
declares ret_val
as local
and all other functions return values via ret_val
.
See also the following Unix & Linux question: Scope of Local Variables in Shell Functions.
Another, perhaps even better solution depending on situation, is the one posted by ya.teck which uses local -n
.
Even if there are tools that allow you to mock your database in one way or another (e.g. jOOQ's MockConnection
, which can be seen in this answer - disclaimer, I work for jOOQ's vendor), I would advise not to mock larger databases with complex queries.
Even if you just want to integration-test your ORM, beware that an ORM issues a very complex series of queries to your database, that may vary in
Mocking all that to produce sensible dummy data is quite hard, unless you're actually building a little database inside your mock, which interprets the transmitted SQL statements. Having said so, use a well-known integration-test database that you can easily reset with well-known data, against which you can run your integration tests.
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
On Ganymede, check the configuration of the Problem view:
('Configure content') It can be set on 'any element in the same project' and you might currently select an element from the project.
Or it might be set on a working set, and this working set has been modified
Make sure that 'Match any configuration' is selected.
Newer versions of MongoDB support bulk operations:
var col = db.collection('people');
var batch = col.initializeUnorderedBulkOp();
batch.insert({name: "John"});
batch.insert({name: "Jane"});
batch.insert({name: "Jason"});
batch.insert({name: "Joanne"});
batch.execute(function(err, result) {
if (err) console.error(err);
console.log('Inserted ' + result.nInserted + ' row(s).');
}
You can see a working example here:
http://codepen.io/anon/pen/GJzBxo
and
http://codepen.io/anon/pen/LVqBQo
Same div, same text, different "spaces"
<div style="width: 500px; background: red"> [loooong text with spaces]</div>
vs
<div style="width: 500px; background: red"> [loooong text with ]</div>
To install your service manually
To install or uninstall windows service manually (which was created using .NET Framework) use utility InstallUtil.exe
. This tool can be found in the following path (use appropriate framework version number).
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe
To install
installutil yourproject.exe
To uninstall
installutil /u yourproject.exe
See: How to: Install and Uninstall Services (Microsoft)
Install service programmatically
To install service programmatically using C# see the following class ServiceInstaller (c-sharpcorner).
When you want to use an anchor tag simply as a link without the added styling (such as the underline on hover or blue color) add class="no-style"
to the anchor tag. Then in your global stylesheet create the class "no-style".
.no-style {
text-decoration: none !important;
}
This has two advantages.
For inversion from 0 to 1 and back you can use this library InvertImages, which provides support for IE 10. I also tested with IE 11 and it should work.
It works fine. I am trying it here with functions as list objects:
from random import shuffle
def foo1():
print "foo1",
def foo2():
print "foo2",
def foo3():
print "foo3",
A=[foo1,foo2,foo3]
for x in A:
x()
print "\r"
shuffle(A)
for y in A:
y()
It prints out: foo1 foo2 foo3 foo2 foo3 foo1 (the foos in the last row have a random order)
Consider the case x = n**(1.0/m), where n=10**5, m=5. In Python, x will be 10.000000000000002, which is only not integer because of floating point arithmetic operations.
So I'd check
if str(float(x)).endswith('.0'): print "It's an integer."
I've tested it with this code:
for a in range(2,100):
for b in range(2,100):
x = (a**b)**(1.0/b)
print a,b, x, str(float(x)).endswith('.0')
It outputs True for all a and b.
kubectl describe pods <name of pod>
will give you some information including the IP
You can use the splice
method on an array to remove the elements.
for example if you have an array with the name arr
use the following:
arr.splice(2, 1);
so here the element with index 2 will be the starting point and the argument 2 will determine how many elements to be deleted.
If you want to delete the last element of the array named arr
then do this:
arr.splice(arr.length-1, 1);
This will return arr with the last element deleted.
Example:
var arr = ["orange", "mango", "banana", "sugar", "tea"];
arr.splice(arr.length-1, 1)
console.log(arr); // return ["orange", "mango", "banana", "sugar"]
You can access values in the $_POST
array by their key. $_POST is an associative array, so to access taskOption
you would use $_POST['taskOption'];
.
Make sure to check if it exists in the $_POST array before proceeding though.
<form method="post" action="process.php">
<select name="taskOption">
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
</select>
<input type="submit" value="Submit the form"/>
</form>
process.php
<?php
$option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
if ($option) {
echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
} else {
echo "task option is required";
exit;
}
Based on my experience with AngularJS modals so far I believe that the most elegant approach is a dedicated service to which we can provide a partial (HTML) template to be displayed in a modal.
When we think about it modals are kind of AngularJS routes but just displayed in modal popup.
The AngularUI bootstrap project (http://angular-ui.github.com/bootstrap/) has an excellent $modal
service (used to be called $dialog prior to version 0.6.0) that is an implementation of a service to display partial's content as a modal popup.
I know this is an old question but I just found a solution which creates a user defined function using LTRIM and RTRIM. It does not handle double spaces in the middle of a string.
The solution is however straight forward:
Here is my solution to split a file called patch6.txt (about 32,000 lines) into separate files of 1000 lines each. Its not quick, but it does the job.
$infile = "D:\Malcolm\Test\patch6.txt"
$path = "D:\Malcolm\Test\"
$lineCount = 1
$fileCount = 1
foreach ($computername in get-content $infile)
{
write $computername | out-file -Append $path_$fileCount".txt"
$lineCount++
if ($lineCount -eq 1000)
{
$fileCount++
$lineCount = 1
}
}
While you did specifically ask for .xls, implying the older file formats, for the OpenXML formats (e.g. xlsx) I highly recommend the OpenXML SDK (http://msdn.microsoft.com/en-us/library/bb448854.aspx)
Note: No, this isn't true. At some point there was a comment on this answer from Dan Piponi himself saying that the cause and effect here was exactly the opposite, that he wrote his article in response to James Iry's quip. But it seems to have been removed, perhaps by some compulsive tidier.
Below is my original answer.
It's quite possible that Iry had read From Monoids to Monads, a post in which Dan Piponi (sigfpe) derives monads from monoids in Haskell, with much discussion of category theory and explicit mention of "the category of endofunctors on Hask" . In any case, anyone who wonders what it means for a monad to be a monoid in the category of endofunctors might benefit from reading this derivation.
This usually appears when you want to use UIActivityViewController
in iPad.
Add below, before you present the controller to mark the arrow.
activityViewController.popoverPresentationController?.sourceRect = senderView.frame // senderView can be your button/view you tapped to call this VC
I assume you already have below, if not, add together:
activityViewController.popoverPresentationController?.sourceView = self.view
per your advice, i am using handle and runnables to switch/change the content of the TextView using a "timer". for some reason, when running, the app always skips the second step ("Step Two: fry egg"), and only show the last (third) step ("Step three: serve egg").
TextView t;
private String sText;
private Handler mHandler = new Handler();
private Runnable mWaitRunnable = new Runnable() {
public void run() {
t.setText(sText);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMonster = BitmapFactory.decodeResource(getResources(),
R.drawable.monster1);
t=new TextView(this);
t=(TextView)findViewById(R.id.TextView01);
sText = "Step One: unpack egg";
t.setText(sText);
sText = "Step Two: fry egg";
mHandler.postDelayed(mWaitRunnable, 3000);
sText = "Step three: serve egg";
mHandler.postDelayed(mWaitRunnable, 4000);
...
}
The simplest way to get stage object in controller is:
Add an extra method in own created controller class like (it will be a setter method to set the stage in controller class),
private Stage myStage;
public void setStage(Stage stage) {
myStage = stage;
}
Get controller in start method and set stage
FXMLLoader loader = new FXMLLoader(getClass().getResource("MyFXML.fxml"));
OwnController controller = loader.getController();
controller.setStage(this.stage);
Now you can access the stage in controller
I'm going to put in a vote for np.vectorize. It allows you to just shoot over x number of columns and not deal with the dataframe in the function, so it's great for functions you don't control or doing something like sending 2 columns and a constant into a function (i.e. col_1, col_2, 'foo').
import numpy as np
import pandas as pd
df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']
def get_sublist(sta,end):
return mylist[sta:end+1]
#df['col_3'] = df[['col_1','col_2']].apply(get_sublist,axis=1)
# expect above to output df as below
df.loc[:,'col_3'] = np.vectorize(get_sublist, otypes=["O"]) (df['col_1'], df['col_2'])
df
ID col_1 col_2 col_3
0 1 0 1 [a, b]
1 2 2 4 [c, d, e]
2 3 3 5 [d, e, f]
Also, if nothing else from given solutions doesn't work, check if you imported "FormsModule" inside of "AppModule", that was a key for me.
jQuery now supports .data();
, so if you have
<div id='author' data-content='stuff!'>
use
var author = $('#author').data("content"); // author = 'stuff!'
This is as simple I think the solution that should solve all your problems:
<input name="myvalue" id="valueText" type="text" value="ENTER VALUE">
This is your submit button:
<input type="submit" id= "submitBtn" value="Submit">
then put this small jQuery in a js file:
//this will submit only if the value is not default
$("#submitBtn").click(function () {
if ($("#valueText").val() === "ENTER VALUE")
{
alert("please insert a valid value");
return false;
}
});
//this will put default value if the field is empty
$("#valueText").blur(function () {
if(this.value == ''){
this.value = 'ENTER VALUE';
}
});
//this will empty the field is the value is the default one
$("#valueText").focus(function () {
if (this.value == 'ENTER VALUE') {
this.value = '';
}
});
And it works also in older browsers. Plus it can easily be converted to normal javascript if you need.
Try Out with this:
firstMax = arr[0];
for (int i = 0; i<n; i++) {
if (firstMax < arr[i] ) {
secondMax = firstMax;
firstMax = arr[i];
}
}
Ok, so this is what I have done:
$(document).on('change','#birthday',function(){
if($('#birthday').val()!==''){
$('#birthday').addClass('hasValue');
}else{
$('#birthday').removeClass('hasValue');
}
})
This is to remove the placeholder when a value is given.
input[type="date"]:before {
content: attr(placeholder) !important;
color: #5C5C5C;
margin-right: 0.5em;
}
input[type="date"]:focus:before,
input[type="date"].hasValue:before {
content: "" !important;
margin-right: 0;
}
On focus or if .hasValue, remove the placeholder and its margin.
I foolishly had a wrapper div which had a width measured in pixels. The other browsers seemed to be intelligent enough to deal with this. Once I had converted the width to a percentage value, it worked fine on Safari mobile as well. Very annoying.
.page{width: 960px;}
to
.page{width:93.75%}
<div id="divPage" class="page">
</div>