It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.
4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.
If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.
I found this official tool from facebook developer page, this page will you following information related to access token - App ID, Type, App-Scoped,User last installed this app via, Issued, Expires, Data Access Expires, Valid, Origin, Scopes. Just need access token.
Just try " gcc filename.c -lm" while compiling the program ...it worked for me
Using jQuery 1.9 and above:
$("#mySelect :selected").prop('selected', false);
If unsure, you might use the 'cols' request on the terminal, and forget COLUMNS:
COLS=$(tput cols)
Instead of isset()
you can use something shorter getting errors muted, it is @$_POST['field']
. Then, if the field is not set, you'll get no error printed on a page.
In cpp, you need to pay special attention to string types when using execvp
:
#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;
const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());
// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
string arg;
cin >> arg;
if (arg.empty()) {
argv[arg_i] = nullptr;
break;
} else {
argv[arg_i] = strdup(arg.c_str());
}
++arg_i;
}
// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
// Print error if command not found
cerr << "command '" << command << "' not found\n";
}
Reference: execlp?execvp?????
this don't work, do like me:
swift:
customTextField.clearButtonMode = UITextField.ViewMode.Always
customTextField.clearsOnBeginEditing = true;
func textFieldShouldClear(textField: UITextField) -> Bool {
return true
}
This worked perfectly fine for me. Add the annotation @JsonIgnore on the child class where you mention the reference to the parent class.
@ManyToOne
@JoinColumn(name = "ID", nullable = false, updatable = false)
@JsonIgnore
private Member member;
CREATE TABLE `voting` (
`QuestionID` int(10) unsigned NOT NULL,
`MemberId` int(10) unsigned NOT NULL,
`vote` int(10) unsigned NOT NULL,
PRIMARY KEY (`QuestionID`,`MemberId`)
);
You could use Visual Studio Immediate Window
Just paste this (change actual
to your object name obviously):
Newtonsoft.Json.JsonConvert.SerializeObject(actual);
It should print object in JSON
You should be able to copy it over textmechanic text tool or notepad++ and replace escaped quotes (\"
) with "
and newlines (\r\n
) with empty space, then remove double quotes ("
) from beginning and end and paste it to jsbeautifier to make it more readable.
UPDATE to OP's comment
public static class Dumper
{
public static void Dump(this object obj)
{
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(obj)); // your logger
}
}
this should allow you to dump any object.
Hope this saves you some time.
You can use a Java COM bridge like JACOB. If it is from client side, another option would be to use Javascript.
I'm guessing this will help.
When passed as functions arguments, arrays act the same way as pointers. So you don't need to reference them. Simply type:
int x[]
or
int x[a]
. Both ways will work. I guess its the same thing Konrad Rudolf was saying, figured as much.
If there is something that is throwing off your Distinct query, you might want to look at MoreLinq and use the DistinctBy operator and select distinct objects by id.
var distinct = items.DistinctBy( i => i.Id );
Here's another way you could try, that doesn't need that ID field.
select some_column, min(another_column)
from i_have_a_table
group by some_column
Still I agree with lfagundes that you should add some primary key ..
Also beware that by doing this, you cannot (easily) get at the other values is the same row as the resulting some_colum, another_column pair! You'd need lfagundes apprach and a PK to do that!
Mostly the image is not displayed because you URL contains spaces. In your case you almost did everything correct. Except one thing - you have not added single quotes like you do if you specify background-image in css I.e.
.bg-img { \/ \/
background-image: url('http://...');
}
To do so escape quot character in HTML via \'
\/ \/
<div [ngStyle]="{'background-image': 'url(\''+ item.color.catalogImageLink + '\')'}"></div>
If you give your table a unique id, its easier:
<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
onmouseup="checkMultipleSelection(this,event);">
<table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table"
cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="width:50px; text-align:left;">09:15 AM</td>
<td style="width:50px; text-align:left;">Item001</td>
<td style="width:50px; text-align:left;">10</td>
<td style="width:50px; text-align:left;">Address1</td>
<td style="width:50px; text-align:left;">46545465</td>
<td style="width:50px; text-align:left;">ref1</td>
</tr>
</table>
</div>
var multiselect =
document.getElementById(
'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
).rows[0].cells,
timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];
//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];
I know it is a very old question, but better update it with new information.
You can install service by using sc command:
InstallService.bat:
@echo OFF
echo Stopping old service version...
net stop "[YOUR SERVICE NAME]"
echo Uninstalling old service version...
sc delete "[YOUR SERVICE NAME]"
echo Installing service...
rem DO NOT remove the space after "binpath="!
sc create "[YOUR SERVICE NAME]" binpath= "[PATH_TO_YOUR_SERVICE_EXE]" start= auto
echo Starting server complete
pause
With SC, you can do a lot more things as well: uninstalling the old service (if you already installed it before), checking if service with same name exists... even set your service to autostart.
One of many references: creating a service with sc.exe; how to pass in context parameters
I have done by both this way & InstallUtil
. Personally I feel that using SC is cleaner and better for your health.
You could also use:
List<int> codes = new List<int>();
codes.add(1);
codes.add(2);
var foo = from codeData in channel.AsQueryable<CodeData>()
where codes.Any(code => codeData.CodeID.Equals(code))
select codeData;
New in C# 8.0 you can use the so-called "hat" (^) operator! This is useful for when you want to do something in one line!
var mystr = "Hello World!";
var lastword = mystr.Split(" ")[^1];
Console.WriteLine(lastword);
// World!
instead of the old way:
var mystr = "Hello World";
var split = mystr.Split(" ");
var lastword = split[split.Length - 1];
Console.WriteLine(lastword);
// World!
It doesn't save much space, but it looks much clearer (maybe I only think this because I came from python?). This is also much better than calling a method like .Last()
or .Reverse()
Read more at MSDN
Edit: You can add this functionality to your class like so:
public class MyClass
{
public object this[Index indx]
{
get
{
// Do indexing here, this is just an example of the .IsFromEnd property
if (indx.IsFromEnd)
{
Console.WriteLine("Negative Index!")
}
else
{
Console.WriteLine("Positive Index!")
}
}
}
}
The Index.IsFromEnd
will tell you if someone is using the 'hat' (^) operator
I have seen many production problems caused by code not handling quotes ("), newline characters within quotes, and quotes within the quotes; e.g.: "he said ""this""" should be parsed into: he said "this"
Like it was mentioned earlier, many CSV parsing examples out there just read a line, and then break up the line by the separator character. This is rather incomplete and problematic.
For me and probably those who prefer build verses buy (or use somebody else's code and deal with their dependencies), I got down to classic text parsing programming and that worked for me:
/**
* Parse CSV data into an array of String arrays. It handles double quoted values.
* @param is input stream
* @param separator
* @param trimValues
* @param skipEmptyLines
* @return an array of String arrays
* @throws IOException
*/
public static String[][] parseCsvData(InputStream is, char separator, boolean trimValues, boolean skipEmptyLines)
throws IOException
{
ArrayList<String[]> data = new ArrayList<String[]>();
ArrayList<String> row = new ArrayList<String>();
StringBuffer value = new StringBuffer();
int ch = -1;
int prevCh = -1;
boolean inQuotedValue = false;
boolean quoteAtStart = false;
boolean rowIsEmpty = true;
boolean isEOF = false;
while (true)
{
prevCh = ch;
ch = (isEOF) ? -1 : is.read();
// Handle carriage return line feed
if (prevCh == '\r' && ch == '\n')
{
continue;
}
if (inQuotedValue)
{
if (ch == -1)
{
inQuotedValue = false;
isEOF = true;
}
else
{
value.append((char)ch);
if (ch == '"')
{
inQuotedValue = false;
}
}
}
else if (ch == separator || ch == '\r' || ch == '\n' || ch == -1)
{
// Add the value to the row
String s = value.toString();
if (quoteAtStart && s.endsWith("\""))
{
s = s.substring(1, s.length() - 1);
}
if (trimValues)
{
s = s.trim();
}
rowIsEmpty = (s.length() > 0) ? false : rowIsEmpty;
row.add(s);
value.setLength(0);
if (ch == '\r' || ch == '\n' || ch == -1)
{
// Add the row to the result
if (!skipEmptyLines || !rowIsEmpty)
{
data.add(row.toArray(new String[0]));
}
row.clear();
rowIsEmpty = true;
if (ch == -1)
{
break;
}
}
}
else if (prevCh == '"')
{
inQuotedValue = true;
}
else
{
if (ch == '"')
{
inQuotedValue = true;
quoteAtStart = (value.length() == 0) ? true : false;
}
value.append((char)ch);
}
}
return data.toArray(new String[0][]);
}
Unit Test:
String[][] data = parseCsvData(new ByteArrayInputStream("foo,\"\",,\"bar\",\"\"\"music\"\"\",\"carriage\r\nreturn\",\"new\nline\"\r\nnext,line".getBytes()), ',', true, true);
for (int rowIdx = 0; rowIdx < data.length; rowIdx++)
{
System.out.println(Arrays.asList(data[rowIdx]));
}
generates the output:
[foo, , , bar, "music", carriage
return, new
line]
[next, line]
vector<vector> matrix(row, vector(col, 0));
This will initialize a 2D vector of rows=row and columns = col with all initial values as 0. No need to initialize and use resize.
Since the vector is initialized with size, you can use "[]" operator as in array to modify the vector.
matrix[x][y] = 2;
static means it belongs to the class not an instance, this means that there is only one copy of that variable/method shared between all instances of a particular Class.
public class MyClass {
public static int myVariable = 0;
}
//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances
MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();
MyClass.myVariable = 5; //This change is reflected in both instances
final is entirely unrelated, it is a way of defining a once only initialization. You can either initialize when defining the variable or within the constructor, nowhere else.
note A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.
Extra Reading So on the topic of static, we were talking about the other uses it may have, it is sometimes used in static blocks. When using static variables it is sometimes necessary to set these variables up before using the class, but unfortunately you do not get a constructor. This is where the static keyword comes in.
public class MyClass {
public static List<String> cars = new ArrayList<String>();
static {
cars.add("Ferrari");
cars.add("Scoda");
}
}
public class TestClass {
public static void main(String args[]) {
System.out.println(MyClass.cars.get(0)); //This will print Ferrari
}
}
You must not get this confused with instance initializer blocks which are called before the constructor per instance.
Use conditional redirects with Options -FollowSymLinks
and AllowOverride -Options
disabled by the Hoster if a few local files should be served too:
Sample .htaccess
# Redirect everything except index.html to http://foo
<FilesMatch "(?<!index\.html)$">
Redirect 301 / http://foo/
</FilesMatch>
This example will serve local index.html and redirects all other staff to new domain.
Icarus answered a very similar question for me. Its not using "yum", but should still work for your purposes. Try,
wget http://mirror.olnevhost.net/pub/apache/maven/maven-3/3.0.5/binaries/apache-maven-3.0.5-bin.tar.gz
basically just go to the maven site. Find the version of maven you want. The file type and use the mirror for the wget statement above.
Afterwards the process is easy
run the following to extract the tar,
tar xvf apache-maven-3.0.5-bin.tar.gz
move maven to /usr/local/apache-maven
mv apache-maven-3.0.5 /usr/local/apache-maven
Next add the env variables to your ~/.bashrc file
export M2_HOME=/usr/local/apache-maven
export M2=$M2_HOME/bin
export PATH=$M2:$PATH
Execute these commands
source ~/.bashrc
6:. Verify everything is working with the following command
mvn -version
I think this might have something to do with caching (possibly in Windows Explorer). I was having the old PyInstaller icon show up in a few places too, but when I copied the exe somewhere else, all the old icons were gone.
You can do this by adding following script and style
function appHeight() {
const doc = document.documentElement
doc.style.setProperty('--vh', (window.innerHeight*.01) + 'px');
}
window.addEventListener('resize', appHeight);
appHeight();
Style
.module {
height: 100vh; /* Fallback for browsers that do not support Custom Properties */
height: calc(var(--vh, 1vh) * 100);
}
Sending an HTTP POST request using file_get_contents
is not that hard, actually : as you guessed, you have to use the $context
parameter.
There's an example given in the PHP manual, at this page : HTTP context options (quoting) :
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents
-- nothing more ;-)
As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="?"/>
You can get here more options.
System.Decimal
implements the IConvertable
interface, which has a ToInt32()
member.
Does calling System.Decimal.ToInt32()
work for you?
i have this problem , a few time problem is recycleView put in ScrollView object
After checking implementation, the reason appears to be the following. If RecyclerView gets put into a ScrollView, then during measure step its height is unspecified (because ScrollView allows any height) and, as a result, gets equal to minimum height (as per implementation) which is apparently zero.
You have couple of options for fixing this:
(Can be followed for android.support.v4.widget.NestedScrollView
as well)
You don't necessarily have to use the [string]:: prefix. This works in the same way:
if ($version)
{
$request += "/" + $version
}
A variable that is null or empty string evaluates to false.
Warning: Don't do this if you've already pushed
You want to do:
git reset HEAD~
If you don't want the changes and blow everything away:
git reset --hard HEAD~
In the css rule you have to add the extension of the file. This example with the deepest support possible:
@font-face {
font-family: 'MyWebFont';
src: url('webfont.eot'); /* IE9 Compat Modes */
src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
url('webfont.ttf') format('truetype'), /* Safari, Android, iOS */
url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}
EDIT:
"Failed to decode downloaded font" means the font is corrupt, or is incomplete (missing metrics, necessary tables, naming records, a million possible things).
Sometimes this problem is caused by the font itself. Google font provides the correct font you need but if font face is necessary i use Transfonter to generate all font format.
Sometimes is the FTP client that corrupt the file (not in this case because is on local pc). Be sure to transfer file in binary and not in ASCII.
Unfortunately the best way would be to check for that directory. I am not sure what you mean but "actually installed" as .NET 3.5 uses the same CLR as .NET 3.0 and .NET 2.0 so all new functionality is wrapped up in new assemblies that live in that directory. Basically, if the directory is there then 3.5 is installed.
Only thing I would add is to find the dir this way for maximum flexibility:
%windir%\Microsoft.NET\Framework\v3.5
I just stumbled upon a combination of Mixin and Extend:
.block1 { box-shadow: 0 5px 10px #000; }
.block2 { box-shadow: 5px 0 10px #000; }
.block3 { box-shadow: 0 0 1px #000; }
@mixin customExtend($class){ @extend .#{$class}; }
like: @include customExtend(block1);
h1 {color: fff; @include customExtend(block2);}
Sass will compile only the mixins content to the extended blocks, which makes it able to combine blocks without generating duplicate code. The Extend logic only puts the classname of the Mixin import location in the block1, ..., ... {box-shadow: 0 5px 10px #000;}
UnxUtils is the one I use, works perfectly for me...
Using Alt+ Insert for Windows or Command+ N for Mac in the editor, you may easily generate getter and setter methods for any fields of your class. This has the same effect as using the Menu Bar -> Code -> Generate...
and then using shift or control button, select all the variables you need to add getters and setters
A full version of the solution will be wrapping the method upvotes inside onClick, passing e and use native e.preventDefault();
upvotes = (e, arg1, arg2, arg3 ) => {
e.preventDefault();
//do something...
}
render(){
return (<a type="simpleQuery" onClick={ e => this.upvotes(e, arg1, arg2, arg3) }>
upvote
</a>);
{
I had the same issue, and it turned out to be that MariaDB was set to allow only root to log in locally via the unix_socket plug-in, so clearing that setting allowed successfully logging in with the user specified on the command line, provided a correct password is entered, of course. See this answer on Ask Ubuntu
The coalesce() is the best solution when there are multiple columns [and]/[or] values and you want the first one. However, looking at books on-line, the query optimize converts it to a case statement.
MSDN excerpt
The COALESCE expression is a syntactic shortcut for the CASE expression.
That is, the code COALESCE(expression1,...n) is rewritten by the query optimizer as the following CASE expression:
CASE
WHEN (expression1 IS NOT NULL) THEN expression1
WHEN (expression2 IS NOT NULL) THEN expression2
...
ELSE expressionN
END
With that said, why not a simple ISNULL()? Less code = better solution?
Here is a complete code snippet.
-- drop the test table
drop table #temp1
go
-- create test table
create table #temp1
(
issue varchar(100) NOT NULL,
total_amount int NULL
);
go
-- create test data
insert into #temp1 values
('No nulls here', 12),
('I am a null', NULL);
go
-- isnull works fine
select
isnull(total_amount, 0) as total_amount
from #temp1
Last but not least, how are you getting null values into a NOT NULL column?
I had to change the table definition so that I could setup the test case. When I try to alter the table to NOT NULL, it fails since it does a nullability check.
-- this alter fails
alter table #temp1 alter column total_amount int NOT NULL
Just use window.open()
function? The third parameter lets you specify window size.
var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
var URL = "https://www.linkedin.com/cws/share?mini=true&url=" + location.href;
var win = window.open(URL, "_blank", strWindowFeatures);
I remember I had the same problem a while back using WCF due the quantity of the data I was passing. I remember I changed timeouts everywhere but the problem persisted. What I finally did was open the connection as stream request, I needed to change the client and the server side, but it work that way. Since it was a stream connection, the server kept reading until the stream ended.
Please check this:
$servername='localhost';
$username='root';
$password='';
$databasename='MyDb';
$connection = mysqli_connect($servername,$username,$password);
if (!$connection) {
die("Connection failed: " . $conn->connect_error);
}
/*mysqli_query($connection, "DROP DATABASE if exists MyDb;");
if(!mysqli_query($connection, "CREATE DATABASE MyDb;")){
echo "Error creating database: " . $connection->error;
}
mysqli_query($connection, "use MyDb;");
mysqli_query($connection, "DROP TABLE if exists employee;");
$table="CREATE TABLE employee (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$value="INSERT INTO employee (firstname,lastname,email) VALUES ('john', 'steve', '[email protected]')";
if(!mysqli_query($connection, $table)){echo "Error creating table: " . $connection->error;}
if(!mysqli_query($connection, $value)){echo "Error inserting values: " . $connection->error;}*/
The new hooks way of doing this is to use useEffect instead of componentWillReceiveProps the old way:
componentWillReceiveProps(nextProps) {
// You don't have to do this check first, but it can help prevent an unneeded render
if (nextProps.startTime !== this.state.startTime) {
this.setState({ startTime: nextProps.startTime });
}
}
becomes the following in a functional hooks driven component:
// store the startTime prop in local state
const [startTime, setStartTime] = useState(props.startTime)
//
useEffect(() => {
if (props.startTime !== startTime) {
setStartTime(props.startTime);
}
}, [props.startTime]);
we set the state using setState, using useEffect we check for changes to the specified prop, and take the action to update the state on change of the prop.
You can try "request.get_full_path()"
45 characters.
You might expect an address to be
0000:0000:0000:0000:0000:0000:0000:0000
8 * 4 + 7 = 39
8 groups of 4 digits with 7 :
between them.
But if you have an IPv4-mapped IPv6 address, the last two groups can be written in base 10 separated by .
, eg. [::ffff:192.168.100.228]
. Written out fully:
0000:0000:0000:0000:0000:ffff:192.168.100.228
(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = 45
Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. [0000:0000:0000:0000:0000:ffff:c0a8:64e4]
for the address above.
In my case (i want to add 3 years to current date) the solution was:
$future_date = date('Y-m-d', strtotime("now + 3 years"));
To Gardenee, Treby and Daniel Lima: what will happen with 29th February? Sometimes February has only 28 days :)
the strncpy is a safer version of strcpy as a matter of fact you should never use strcpy because its potential buffer overflow vulnerability which makes you system vulnerable to all sort of attacks
Some libraries attempt to offer alternatives to the builtin java switch
statement. Vavr is one of them, they generalize it to pattern matching.
Here is an example from their documentation:
String s = Match(i).of(
Case($(1), "one"),
Case($(2), "two"),
Case($(), "?")
);
You can use any predicate, but they offer many of them out of the box, and $(null)
is perfectly legal. I find this a more elegant solution than the alternatives, but this requires java8 and a dependency on the vavr library...
this will work:
DECLARE @IndexInfo TABLE (index_name varchar(250)
,index_description varchar(250)
,index_keys varchar(250)
)
INSERT INTO @IndexInfo
exec sp_msforeachtable 'sp_helpindex ''?'''
select * from @IndexInfo
this does not reurn the table name and you will get warnings for all tables without an index, if that is a problem, you can create a loop over the tables that have indexes like this:
DECLARE @IndexInfoTemp TABLE (index_name varchar(250)
,index_description varchar(250)
,index_keys varchar(250)
)
DECLARE @IndexInfo TABLE (table_name sysname
,index_name varchar(250)
,index_description varchar(250)
,index_keys varchar(250)
)
DECLARE @Tables Table (RowID int not null identity(1,1)
,TableName sysname
)
DECLARE @MaxRow int
DECLARE @CurrentRow int
DECLARE @CurrentTable sysname
INSERT INTO @Tables
SELECT
DISTINCT t.name
FROM sys.indexes i
INNER JOIN sys.tables t ON i.object_id = t.object_id
WHERE i.Name IS NOT NULL
SELECT @MaxRow=@@ROWCOUNT,@CurrentRow=1
WHILE @CurrentRow<=@MaxRow
BEGIN
SELECT @CurrentTable=TableName FROM @Tables WHERE RowID=@CurrentRow
INSERT INTO @IndexInfoTemp
exec sp_helpindex @CurrentTable
INSERT INTO @IndexInfo
(table_name , index_name , index_description , index_keys)
SELECT
@CurrentTable , index_name , index_description , index_keys
FROM @IndexInfoTemp
DELETE FROM @IndexInfoTemp
SET @CurrentRow=@CurrentRow+1
END --WHILE
SELECT * from @IndexInfo
EDIT
if you want, you can filter the data, here are some examples (these work for either method):
SELECT * FROM @IndexInfo WHERE index_description NOT LIKE '%primary key%'
SELECT * FROM @IndexInfo WHERE index_description NOT LIKE '%nonclustered%' AND index_description LIKE '%clustered%'
SELECT * FROM @IndexInfo WHERE index_description LIKE '%unique%'
It is possible also that one may want to have personalized feature branches where code is just placed at the end of day. That permits to track development in finer detail.
I would not want to pollute master development with non-working code, thus doing --no-ff may just be what one is looking for.
As a side note, it may not be necessary to commit working code on a personalized branch, since history can be rewritten git rebase -i
and forced on the server as long as nobody else is working on that same branch.
The simplest answer to the meaning of deprecated
when used to describe software APIs is:
- Stop using APIs marked as deprecated!
- They will go away in a future release!!
- Start using the new versions ASAP!!!
In c++11, you can use some function like that:
int maxAt(std::vector<int>& vector_name) {
int max = INT_MIN;
for (auto val : vector_name) {
if (max < val) max = val;
}
return max;
}
simply say
git stash
It will remove all your local changes. You also can use later by saying
git stash apply
or git stash pop
There is no search and replace function or stream editing at the command line in XP or 2k3 (dont know about vista or beyond). So, you'll need to use a script like the one Ghostdog posted, or a search and replace capable tool like sed.
There is more than one way to do it, as this script shows:
@echo off
SETLOCAL=ENABLEDELAYEDEXPANSION
rename text.file text.tmp
for /f %%a in (text.tmp) do (
set foo=%%a
if !foo!==ex3 set foo=ex5
echo !foo! >> text.file)
del text.tmp
pprint.pprint()
is a good tool for this job:
>>> import pprint
>>> cars = {'A':{'speed':70,
... 'color':2},
... 'B':{'speed':60,
... 'color':3}}
>>> pprint.pprint(cars, width=1)
{'A': {'color': 2,
'speed': 70},
'B': {'color': 3,
'speed': 60}}
Do you want the files to save as UTF-8 because you are using special characters that would be lost in ASCII encoding? If that's the case, then there is a VS2008 global setting in Tools > Options > Environment > Documents
, named Save documents as Unicode when data cannot be saved in codepage
. When this is enabled, VS2008 will save as Unicode if certain characters cannot be represented in the otherwise-default codepage.
Also, which files are not being saved as UTF-8? All of my .cs, .csproj, .sln, .config, .as*x, etc, all save as UTF-8 (with signature, the byte order marks), by default.
I had a similar kind of issue, but with some differences...
In my case, my main form has a Control (vendor) which value I used to update a Query in my DB, using the following code:
Sub Set_Qry_PedidosRealizadosImportados_frm(Vd As Long)
Dim temp_qry As DAO.QueryDef
'Procedimento para ajustar o codigo do cliente na Qry_Pedidos realizados e importados
'Procedure to adjust the code of the client on Qry_Pedidos realizados e importados
Set temp_qry = CurrentDb.QueryDefs("Qry_Pedidos realizados e importados")
temp_qry.SQL = "SELECT DISTINCT " & _
"[Qry_Pedidos distintos].[Codigo], " & _
"[Qry_Pedidos distintos].[Razao social], " & _
"COUNT([Qry_Pedidos distintos].[Pedido Avante]) As [Pedidos realizados], " & _
"SUM(IIf(NZ([Qry_Pedidos distintos].[Pedido Flexx], 0) > 1, 1, 0)) As [Pedidos Importados] " & _
"FROM [Qry_Pedidos distintos] " & _
"WHERE [Qry_Pedidos distintos].Vd = " & Vd & _
" Group BY " & _
"[Qry_Pedidos distintos].[Razao social], " & _
"[Qry_Pedidos distintos].[Codigo];"
End Sub
Since the beginning my subform record source was the query named "Qry_Pedidos realizados e importados".
But the only way I could update the subform data inside the main form context was to refresh the data source of the subform to it self, like posted bellow:
Private Sub cmb_vendedor_v1_Exit(Cancel As Integer)
'Codigo para atualizar o comando SQL da query
'Code to update the SQL statement of the query
Call Set_Qry_Pedidosrealizadosimportados_frm(Me.cmb_vendedor_v1.Value)
'Codigo para forçar o Access a aceitar o novo comando SQL
'Code to force de Access to accept the new sql statement
Me!Frm_Pedidos_realizados_importados.Form.RecordSource = "Qry_Pedidos realizados e importados"
End Sub
No refresh, recalc, requery, etc, was necessary after all...
You don't need to use display:inline
to achieve this:
.inline {
border: 1px solid red;
margin:10px;
float:left;/*Add float left*/
margin :10px;
}
You can use float-left
.
Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.
This solution worked for MacOS Sierra, and running MySQL version 8.0.11. Please make sure driver you have added in your build path - "add external jar" should match up with SQL version.
String url = "jdbc:mysql://localhost:3306/syscharacterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
If you want to add a native library without interfering with java.library.path
at development time in Eclipse (to avoid including absolute paths and having to add parameters to your launch configuration), you can supply the path to the native libraries location for each Jar in the Java Build Path dialog under Native library location. Note that the native library file name has to correspond to the Jar file name. See also this detailed description.
With Swift 5, you may choose one of the three examples shown below in order to solve your problem.
String
's init(format:_:)
initializerFoundation
provides Swift String
a init(format:_:)
initializer. init(format:_:)
has the following declaration:
init(format: String, _ arguments: CVarArg...)
Returns a
String
object initialized by using a given format string as a template into which the remaining argument values are substituted.
The following Playground code shows how to create a String
formatted from Int
with at least two integer digits by using init(format:_:)
:
import Foundation
let string0 = String(format: "%02d", 0) // returns "00"
let string1 = String(format: "%02d", 1) // returns "01"
let string2 = String(format: "%02d", 10) // returns "10"
let string3 = String(format: "%02d", 100) // returns "100"
String
's init(format:arguments:)
initializerFoundation
provides Swift String
a init(format:arguments:)
initializer. init(format:arguments:)
has the following declaration:
init(format: String, arguments: [CVarArg])
Returns a
String
object initialized by using a given format string as a template into which the remaining argument values are substituted according to the user’s default locale.
The following Playground code shows how to create a String
formatted from Int
with at least two integer digits by using init(format:arguments:)
:
import Foundation
let string0 = String(format: "%02d", arguments: [0]) // returns "00"
let string1 = String(format: "%02d", arguments: [1]) // returns "01"
let string2 = String(format: "%02d", arguments: [10]) // returns "10"
let string3 = String(format: "%02d", arguments: [100]) // returns "100"
NumberFormatter
Foundation provides NumberFormatter
. Apple states about it:
Instances of
NSNumberFormatter
format the textual representation of cells that containNSNumber
objects and convert textual representations of numeric values intoNSNumber
objects. The representation encompasses integers, floats, and doubles; floats and doubles can be formatted to a specified decimal position.
The following Playground code shows how to create a NumberFormatter
that returns String?
from a Int
with at least two integer digits:
import Foundation
let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 2
let optionalString0 = formatter.string(from: 0) // returns Optional("00")
let optionalString1 = formatter.string(from: 1) // returns Optional("01")
let optionalString2 = formatter.string(from: 10) // returns Optional("10")
let optionalString3 = formatter.string(from: 100) // returns Optional("100")
Disabling the alert message is not a way to solve the problem. Despite the PHP core is continue to work it makes a dangerous assumptions and actions.
Never ignore the error where PHP should make an assumptions of something!!!!
If the class organized as a singleton you can always use function getInstance() and then use getData()
Likse:
$classObj = MyClass::getInstance();
$classObj->getData();
If the class is not a singleton, use
$classObj = new MyClass();
$classObj->getData();
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block
Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)
I just removed the head portion in index.html file and it worked fine.This is the head tag in html file
'use strict';
var express = require('express');
var fs = require('fs');
var compress = require('compression');
var bodyParser = require('body-parser');
var app = express();
app.set('port', 9999);
app.use(bodyParser.json({ limit: '1mb' }));
app.use(compress());
app.use(function (req, res, next) {
req.setTimeout(3600000)
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept,' + Object.keys(req.headers).join());
if (req.method === 'OPTIONS') {
res.write(':)');
res.end();
} else next();
});
function readApp(req,res) {
var file = req.originalUrl == "/read-android" ? "Android.apk" : "Ios.ipa",
filePath = "/home/sony/Documents/docs/";
fs.exists(filePath, function(exists){
if (exists) {
res.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Disposition" : "attachment; filename=" + file});
fs.createReadStream(filePath + file).pipe(res);
} else {
res.writeHead(400, {"Content-Type": "text/plain"});
res.end("ERROR File does NOT Exists.ipa");
}
});
}
app.get('/read-android', function(req, res) {
var u = {"originalUrl":req.originalUrl};
readApp(u,res)
});
app.get('/read-ios', function(req, res) {
var u = {"originalUrl":req.originalUrl};
readApp(u,res)
});
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
inplace=True
makes the function impure. It changes the original dataframe and returns None. In that case, You breaks the DSL chain.
Because most of dataframe functions return a new dataframe, you can use the DSL conveniently. Like
df.sort_values().rename().to_csv()
Function call with inplace=True
returns None and DSL chain is broken. For example
df.sort_values(inplace=True).rename().to_csv()
will throw NoneType object has no attribute 'rename'
Something similar with python’s build-in sort and sorted. lst.sort()
returns None
and sorted(lst)
returns a new list.
Generally, do not use inplace=True
unless you have specific reason of doing so. When you have to write reassignment code like df = df.sort_values()
, try attaching the function call in the DSL chain, e.g.
df = pd.read_csv().sort_values()...
This is works for me:
myEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(myEditText.isFocused()){
myEditText.requestFocus();
myEditText.clearFocus();
myEditText.setSelection(myEditText.getText().length(), 0);
}else{
myEditText.requestFocus();
myEditText.clearFocus();
}
}
});
They cause the compiler to emit the appropriate branch hints where the hardware supports them. This usually just means twiddling a few bits in the instruction opcode, so code size will not change. The CPU will start fetching instructions from the predicted location, and flush the pipeline and start over if that turns out to be wrong when the branch is reached; in the case where the hint is correct, this will make the branch much faster - precisely how much faster will depend on the hardware; and how much this affects the performance of the code will depend on what proportion of the time hint is correct.
For instance, on a PowerPC CPU an unhinted branch might take 16 cycles, a correctly hinted one 8 and an incorrectly hinted one 24. In innermost loops good hinting can make an enormous difference.
Portability isn't really an issue - presumably the definition is in a per-platform header; you can simply define "likely" and "unlikely" to nothing for platforms that do not support static branch hints.
REST is somewhat of a revival of old-school HTTP, where the actual HTTP verbs (commands) have semantic meaning. Til recently, apps that wanted to update stuff on the server would supply a form containing an 'action' variable and a bunch of data. The HTTP command would almost always be GET
or POST
, and would be almost irrelevant. (Though there's almost always been a proscription against using GET for operations that have side effects, in reality a lot of apps don't care about the command used.)
With REST, you might instead PUT /profiles/cHao
and send an XML or JSON representation of the profile info. (Or rather, I would -- you would have to update your own profile. :) That'd involve logging in, usually through HTTP's built-in authentication mechanisms.) In the latter case, what you want to do is specified by the URL, and the request body is just the guts of the resource involved.
http://en.wikipedia.org/wiki/Representational_State_Transfer has some details.
I wrote this simple helper:
Handlebars.registerHelper('conditions', function (options) {
var data = this;
data.__check_conditions = true;
return options.fn(this);
});
Handlebars.registerHelper('next', function(conditional, options) {
if(conditional && this.__check_conditions) {
this.__check_conditions = false;
return options.fn(this);
} else {
return options.inverse(this);
}
});
It's something like Chain Of Responsibility pattern in Handlebars
Example:
{{#conditions}}
{{#next condition1}}
Hello 1!!!
{{/next}}
{{#next condition2}}
Hello 2!!!
{{/next}}
{{#next condition3}}
Hello 3!!!
{{/next}}
{{#next condition4}}
Hello 4!!!
{{/next}}
{{/conditions}}
It's not a else if but in some cases it may help you)
select 'ALTER TABLE ' + OBJECT_NAME(o.object_id) +
' ALTER COLUMN ' + c.name + ' DATETIME2 ' +
CASE WHEN c.is_nullable = 0 THEN 'NOT NULL' ELSE 'NULL' END
from sys.objects o
inner join sys.columns c on o.object_id = c.object_id
inner join sys.types t on c.system_type_id = t.system_type_id
where o.type='U'
and c.name = 'Timestamp'
and t.name = 'datetime'
order by OBJECT_NAME(o.object_id)
courtesy of devio
If you're like me and you don't want to deal with merging, you can do the above steps, except use force instead of merge, because it will create a distracting log paper trail:
git checkout email
git reset --hard staging
git push origin email --force
Note: This is only if you REALLY never want to see the stuff in email again.
Looking through the answers, we have seen a lot of back and forth, whether or not list comprehension or filter may be faster or if it is even important or pythonic to care about such an issue. In the end, the answer is as most times: it depends.
I just stumbled across this question while optimizing code where this exact question (albeit combined with an in
expression, not ==
) is very relevant - the filter
+ lambda
expression is taking up a third of my computation time (of multiple minutes).
In my case, the list comprehension is much faster (twice the speed). But I suspect that this varies strongly based on the filter expression as well as the Python interpreter used.
Here is a simple code snippet that should be easy to adapt. If you profile it (most IDEs can do that easily), you will be able to easily decide for your specific case which is the better option:
whitelist = set(range(0, 100000000, 27))
input_list = list(range(0, 100000000))
proximal_list = list(filter(
lambda x: x in whitelist,
input_list
))
proximal_list2 = [x for x in input_list if x in whitelist]
print(len(proximal_list))
print(len(proximal_list2))
If you do not have an IDE that lets you profile easily, try this instead (extracted from my codebase, so a bit more complicated). This code snippet will create a profile for you that you can easily visualize using e.g. snakeviz:
import cProfile
from time import time
class BlockProfile:
def __init__(self, profile_path):
self.profile_path = profile_path
self.profiler = None
self.start_time = None
def __enter__(self):
self.profiler = cProfile.Profile()
self.start_time = time()
self.profiler.enable()
def __exit__(self, *args):
self.profiler.disable()
exec_time = int((time() - self.start_time) * 1000)
self.profiler.dump_stats(self.profile_path)
whitelist = set(range(0, 100000000, 27))
input_list = list(range(0, 100000000))
with BlockProfile("/path/to/create/profile/in/profile.pstat"):
proximal_list = list(filter(
lambda x: x in whitelist,
input_list
))
proximal_list2 = [x for x in input_list if x in whitelist]
print(len(proximal_list))
print(len(proximal_list2))
It all boils down to maintainability. The best way to put this is whenever you use the new
keyword to create an object, you're coupling the code that you're writing to an implementation.
The factory pattern lets you separate how you create an object from what you do with the object. When you create all of your objects using constructors, you are essentially hard-wiring the code that uses the object to that implementation. The code that uses your object is "dependent on" that object. This may not seem like a big deal on the surface, but when the object changes (think of changing the signature of the constructor, or subclassing the object) you have to go back and rewire things everywhere.
Today factories have largely been brushed aside in favor of using Dependency Injection because they require a lot of boiler-plate code that turns out to be a little hard to maintain itself. Dependency Injection is basically equivalent to factories but allows you to specify how your objects get wired together declaratively (through configuration or annotations).
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
Gson gson = new Gson();
JSONObject jsonObject = new JSONObject(s.toString());
String link = jsonObject.getString("Result");
This is one example where using prepared statements really saves you some trouble.
In MySQL, in order to insert a null value, you must specify it at INSERT
time or leave the field out which requires additional branching:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', NULL);
However, if you want to insert a value in that field, you must now branch your code to add the single quotes:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', 'String Value');
Prepared statements automatically do that for you. They know the difference between string(0) ""
and null
and write your query appropriately:
$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);
$field1 = "String Value";
$field2 = null;
$stmt->execute();
It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the mysql
extension. Use mysqli
and it's prepared statements instead. You'll save yourself a world of pain.
No, you can only get to the interior color of a cell by using a Macro. I am afraid. It's really easy to do (cell.interior.color) so unless you have a requirement that restricts you from using VBA, I say go for it.
In the webpack.config.js
:
module.exports = {
......
devServer: {
historyApiFallback: true,
port: 8081, // you can change the port there
noInfo: true,
overlay: true
},
......
}
You can change the port in the module.exports
-> devServer
-> port
.
Then you restrat the npm run dev
. You can get that.
You cannot test for string[]
in the general case but you can test for Array
quite easily the same as in JavaScript https://stackoverflow.com/a/767492/390330
If you specifically want for string
array you can do something like:
if (Array.isArray(value)) {
var somethingIsNotString = false;
value.forEach(function(item){
if(typeof item !== 'string'){
somethingIsNotString = true;
}
})
if(!somethingIsNotString && value.length > 0){
console.log('string[]!');
}
}
I recently fell in love with fuzzyfinder.vim ... :-)
:FuzzyFinderFile will let you open files by typing partial names or patterns.
So if your scenario is that you've committed to master
but meant to commit to another-branch
(which may or not may not already exist) but you haven't pushed yet, this is pretty easy to fix.
// if your branch doesn't exist, then add the -b argument
git checkout -b another-branch
git branch --force master origin/master
Now all your commits to master
will be on another-branch
.
Sourced with love from: http://haacked.com/archive/2015/06/29/git-migrate/
DBQuery.shellBatchSize = 300
will do.
MongoDB Docs - Configure the mongo Shell - Change the mongo Shell Batch Size
Thowable
catches really everything even ThreadDeath which gets thrown by default to stop a thread from the now deprecated Thread.stop()
method. So by catching Throwable
you can be sure that you'll never leave the try block without at least going through your catch block, but you should be prepared to also handle OutOfMemoryError
and InternalError
or StackOverflowError
.
Catching Throwable
is most useful for outer server loops that delegate all sorts of requests to outside code but may itself never terminate to keep the service alive.
Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)
Actually the error is being generated by the initMap in the Google's api script
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
so basically when the Google Map API is loaded then the initMap function is executed. If you don't have an initMap function, then the initMap is not a function error is generated.
So basically what you have to do is one of the following options:
&callback=angular.noop
if you just want an empty function() (only if you use angular)I tried the usual "gg=G" command, which is what I use to fix the indentation of code files. However, it didn't seem to work right on HTML files. It simply removed all the formatting.
If vim's autoformat/indent gg=G
seems to be "broken" (such as left indenting every line), most likely the indent plugin is not enabled/loaded. It should really give an error message instead of just doing bad indenting, otherwise users just think the autoformat/indenting feature is awful, when it actually is pretty good.
To check if the indent plugin is enabled/loaded, run :scriptnames
. See if .../indent/html.vim
is in the list. If not, then that means the plugin is not loaded. In that case, add this line to ~/.vimrc
:
filetype plugin indent on
Now if you open the file and run :scriptnames
, you should see .../indent/html.vim
. Then run gg=G
, which should do the correct autoformat/indent now. (Although it won't add newlines, so if all the html code is on a single line, it won't be indented).
Note: if you are running :filetype plugin indent on
on the vim command line instead of ~/.vimrc
, you must re-open the file :e
.
Also, you don't need to worry about autoindent
and smartindent
settings, they are not relevant for this.
If you don't mind the commas and the brackets you can simply use:
System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n"));
As @Hutch pointed out, one of the major limitations of sp_who2
is that it does not take any parameters so you cannot sort or filter it by default. You can save the results into a temp table, but then the you have to declare all the types ahead of time (and remember to DROP TABLE
).
Instead, you can just go directly to the source on master.dbo.sysprocesses
I've constructed this to output almost exactly the same thing that sp_who2
generates, except that you can easily add ORDER BY
and WHERE
clauses to get meaningful output.
SELECT spid,
sp.[status],
loginame [Login],
hostname,
blocked BlkBy,
sd.name DBName,
cmd Command,
cpu CPUTime,
physical_io DiskIO,
last_batch LastBatch,
[program_name] ProgramName
FROM master.dbo.sysprocesses sp
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
ORDER BY spid
It is because you are in a try
statement. Since there could be an error, sum might not get initialized, so put your return statement in the finally
block, that way it will for sure be returned.
Make sure that you initialize sum outside the try/catch/finally
so that it is in scope.
A call to vector<T>::size()
returns a value of type std::vector<T>::size_type
, not int, unsigned int or otherwise.
Also generally iteration over a container in C++ is done using iterators, like this.
std::vector<T>::iterator i = polygon.begin();
std::vector<T>::iterator end = polygon.end();
for(; i != end; i++){
sum += *i;
}
Where T is the type of data you store in the vector.
Or using the different iteration algorithms (std::transform
, std::copy
, std::fill
, std::for_each
et cetera).
In case you want to share on more forums, here is the solution.. https://github.com/bradvin/social-share-urls
For all databases query sys.sysprocesses
SELECT * FROM sys.sysprocesses WHERE open_tran = 1
For the current database use:
DBCC OPENTRAN
From the ReactDOM.render() documentation:
If the optional callback is provided, it will be executed after the component is rendered or updated.
The proper way is to look at the HTTP Accept-Language header sent to the server. This contains the ordered, weighted list of languages the user has configured their browser to prefer.
Unfortunately this header is not available for reading inside JavaScript; all you get is navigator.language
, which tells you what localised version of the web browser was installed. This is not necessarily the same thing as the user's preferred language(s). On IE you instead get systemLanguage
(OS installed language), browserLanguage
(same as language
) and userLanguage
(user configured OS region), which are all similarly unhelpful.
If I had to choose between those properties, I'd sniff for userLanguage
first, falling back to language
and only after that (if those didn't match any available language) looking at browserLanguage
and finally systemLanguage
.
If you can put a server-side script somewhere else on the net that simply reads the Accept-Language header and spits it back out as a JavaScript file with the header value in the string, eg.:
var acceptLanguage= 'en-gb,en;q=0.7,de;q=0.3';
then you could include a <script src> pointing at that external service in the HTML, and use JavaScript to parse the language header. I don't know of any existing library code to do this, though, since Accept-Language parsing is almost always done on the server side.
Whatever you end up doing, you certainly need a user override because it will always guess wrong for some people. Often it's easiest to put the language setting in the URL (eg. http?://www.example.com/en/site vs http?://www.example.com/de/site), and let the user click links between the two. Sometimes you do want a single URL for both language versions, in which case you have to store the setting in cookies, but this may confuse user agents with no support for cookies and search engines.
A random value?
If you want a random value, try
<?php
$value = mt_rand($min, $max);
mt_rand() will run a bit more random if you are using many random numbers in a row, or if you might ever execute the script more than once a second. In general, you should use mt_rand() over rand() if there is any doubt.
If you have the size of the image, why don't you set the frame.size
of the image view to be of this size?
EDIT----
Ok, so seeing your comment I propose this:
UIImageView *imageView;
//so let's say you're image view size is set to the maximum size you want
CGFloat maxWidth = imageView.frame.size.width;
CGFloat maxHeight = imageView.frame.size.height;
CGFloat viewRatio = maxWidth / maxHeight;
CGFloat imageRatio = image.size.height / image.size.width;
if (imageRatio > viewRatio) {
CGFloat imageViewHeight = round(maxWidth * imageRatio);
imageView.frame = CGRectMake(0, ceil((self.bounds.size.height - imageViewHeight) / 2.f), maxWidth, imageViewHeight);
}
else if (imageRatio < viewRatio) {
CGFloat imageViewWidth = roundf(maxHeight / imageRatio);
imageView.frame = CGRectMake(ceil((maxWidth - imageViewWidth) / 2.f), 0, imageViewWidth, maxHeight);
} else {
//your image view is already at the good size
}
This code will resize your image view to its image ratio, and also position the image view to the same centre as your "default" position.
PS: I hope you're setting imageView.layer.shouldRasterise = YES
and imageView.layer.rasterizationScale = [UIScreen mainScreen].scale;
if you're using CALayer shadow effect ;) It will greatly improve the performance of your UI.
Maybe this link will help you.
See: std::string documentation.
#include <string>
is the most widely accepted.
For the answer above, the default serial port is
serialParams.BaudRate = 9600;
serialParams.ByteSize = 8;
serialParams.StopBits = TWOSTOPBITS;
serialParams.Parity = NOPARITY;
Ouath just makes the Google instance null, hence it you out of Google. Now that's how the architecture is made. Logging out of Google, if you Logout of your app is a dirty work, but can't help if the requirement stipulates the same. Hence add the following to your signOut() function. My project was an Angular 6 app:
document.location.href = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://localhost:4200";
Here localhost:4200 is the URL of my app. If your login page is xyz.com then input that.
This is documented in section 3.9.3 of the Spring 3.0 manual:
For a fallback match, the bean name is considered a default qualifier value.
In other words, the default behaviour is as though you'd added @Qualifier("country")
to the setter method.
This Quick Reference looks pretty good if you're looking for a language reference. It's especially geared towards the user interface portion of the API.
For the complete API, however, I always use the Javadoc. I reference it constantly.
Got the "You have to install development tools first." error when trying to install the mysql2 gem after upgrading to Mac OS X Mountain Lion. Apparently doing this upgrade removes the command line compilers.
To fix:
You can use Random.Next(int maxValue)
:
Return: A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values ordinarily includes zero but not maxValue. However, if maxValue equals zero, maxValue is returned.
var r = new Random();
// print random integer >= 0 and < 100
Console.WriteLine(r.Next(100));
For this case however you could use Random.Next(int minValue, int maxValue)
, like this:
// print random integer >= 1 and < 101
Console.WriteLine(r.Next(1, 101);)
// or perhaps (if you have this specific case)
Console.WriteLine(r.Next(100) + 1);
It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.
4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.
If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.
I prefer following approach (code below). It solves the "namespace pollution" problem, but also it is much more typesafe (you can't assign and even compare two different enumerations, or your enumeration with any other built-in types etc).
struct Color
{
enum Type
{
Red, Green, Black
};
Type t_;
Color(Type t) : t_(t) {}
operator Type () const {return t_;}
private:
//prevent automatic conversion for any other built-in types such as bool, int, etc
template<typename T>
operator T () const;
};
Usage:
Color c = Color::Red;
switch(c)
{
case Color::Red:
//????????? ???
break;
}
Color2 c2 = Color2::Green;
c2 = c; //error
c2 = 3; //error
if (c2 == Color::Red ) {} //error
If (c2) {} error
I create macro to facilitate usage:
#define DEFINE_SIMPLE_ENUM(EnumName, seq) \
struct EnumName {\
enum type \
{ \
BOOST_PP_SEQ_FOR_EACH_I(DEFINE_SIMPLE_ENUM_VAL, EnumName, seq)\
}; \
type v; \
EnumName(type v) : v(v) {} \
operator type() const {return v;} \
private: \
template<typename T> \
operator T () const;};\
#define DEFINE_SIMPLE_ENUM_VAL(r, data, i, record) \
BOOST_PP_TUPLE_ELEM(2, 0, record) = BOOST_PP_TUPLE_ELEM(2, 1, record),
Usage:
DEFINE_SIMPLE_ENUM(Color,
((Red, 1))
((Green, 3))
)
Some references:
Here is an alternate way to make the installer and get rid of that error message. Also it seems that VS2015 express does not have the "Add Installer" menu item.
You simply need to create a class and add the below code and add the reference System.Configuration.Install.dll.
using System.Configuration.Install;
using System.ServiceProcess;
using System.ComponentModel;
namespace SAS
{
[RunInstaller(true)]
public class MyProjectInstaller : Installer
{
private ServiceInstaller serviceInstaller1;
private ServiceProcessInstaller processInstaller;
public MyProjectInstaller()
{
// Instantiate installer for process and service.
processInstaller = new ServiceProcessInstaller();
serviceInstaller1 = new ServiceInstaller();
// The service runs under the system account.
processInstaller.Account = ServiceAccount.LocalSystem;
// The service is started manually.
serviceInstaller1.StartType = ServiceStartMode.Manual;
// ServiceName must equal those on ServiceBase derived classes.
serviceInstaller1.ServiceName = "SAS Service";
// Add installer to collection. Order is not important if more than one service.
Installers.Add(serviceInstaller1);
Installers.Add(processInstaller);
}
}
}
I found the answer I was looking for from the one-liner posted earlier by pavek (thanks!) so I wanted to provide a complete answer in a single reply that works on Linux (GIT 1.7.1):
1--> mkdir myrepo
2--> cd myrepo
3--> git init
4--> git config core.sparseCheckout true
5--> echo 'path/to/subdir/' > .git/info/sparse-checkout
6--> git remote add -f origin ssh://...
7--> git pull origin master
I changed the order of the commands a bit but that does not seem to have any impact. The key is the presence of the trailing slash "/" at the end of the path in step 5.
Check if you are building for device instead of simulator. Go to Xcode menu 'Project' -> 'Set Active SDK' change from 'Device' to 'Simulator'
Under Xcode 4.1 Check your build settings for the project and your targets. For each check under 'Code Signing' check 'Code Signing Identity' and change over to 'Don't Code Sign'
Step the loop manually:
i=0 max=10 while [ $i -lt $max ] do echo "output: $i" true $(( i++ )) done
If you don’t have to be totally POSIX, you can use the arithmetic for loop:
max=10 for (( i=0; i < max; i++ )); do echo "output: $i"; done
Or use jot(1) on BSD systems:
for i in $( jot 0 10 ); do echo "output: $i"; done
It can be done by jquery and css. i did it in a way that can be used in dynamic situations , you just have to change background-image in jquery and it will do every thing , also you can change the time in css.
The fiddle : https://jsfiddle.net/Naderial/zohfvqz7/
Html:
<div class="test">
CSS :
.test {
/* as default, we set a background-image , but it is not nessesary */
background-image: url(http://lorempixel.com/400/200);
width: 200px;
height: 200px;
/* we set transition to 'all' properies - but you can use it just for background image either - by default the time is set to 1 second, you can change it yourself*/
transition: linear all 1s;
/* if you don't use delay , background will disapear and transition will start from a white background - you have to set the transition-delay the same as transition time OR more , so there won't be any problems */
-webkit-transition-delay: 1s;/* Safari */
transition-delay: 1s;
}
JS:
$('.test').click(function() {
//you can use all properties : background-color - background-image ...
$(this).css({
'background-image': 'url(http://lorempixel.com/400/200)'
});
});
Here's a simple pure JavaScript solution that works for a target Number (value for scrollTop
), target DOM element, or some special String cases:
/**
* target - target to scroll to (DOM element, scrollTop Number, 'top', or 'bottom'
* containerEl - DOM element for the container with scrollbars
*/
var scrollToTarget = function(target, containerEl) {
// Moved up here for readability:
var isElement = target && target.nodeType === 1,
isNumber = Object.prototype.toString.call(target) === '[object Number]';
if (isElement) {
containerEl.scrollTop = target.offsetTop;
} else if (isNumber) {
containerEl.scrollTop = target;
} else if (target === 'bottom') {
containerEl.scrollTop = containerEl.scrollHeight - containerEl.offsetHeight;
} else if (target === 'top') {
containerEl.scrollTop = 0;
}
};
And here are some examples of usage:
// Scroll to the top
var scrollableDiv = document.getElementById('scrollable_div');
scrollToTarget('top', scrollableDiv);
or
// Scroll to 200px from the top
var scrollableDiv = document.getElementById('scrollable_div');
scrollToTarget(200, scrollableDiv);
or
// Scroll to targetElement
var scrollableDiv = document.getElementById('scrollable_div');
var targetElement= document.getElementById('target_element');
scrollToTarget(targetElement, scrollableDiv);
You can use Numeric#step
.
0.step(30,5) do |num|
puts "number is #{num}"
end
# >> number is 0
# >> number is 5
# >> number is 10
# >> number is 15
# >> number is 20
# >> number is 25
# >> number is 30
I'd just like to add to the very helpful answer from Kurt Pfeifle - there is now a Python wrapper for Tabula, and this seems to work very well so far: https://github.com/chezou/tabula-py
This will convert your PDF table to a Pandas data frame. You can also set the area in x,y co-ordinates which is obviously very handy for irregular data.
Well, after reviewing all available solutions I wrote plugin which can freeze any row (not only th) at the top of page or container. It's very simple and very fast. Feel free to use it. http://maslianok.github.io/stickyRows/
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
also works. First create a JFrame called frame, then add this code underneath.
Use reindex
to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.
p = p.reindex(columns=['1Sun', '2Mon', '3Tue', '4Wed', '5Thu', '6Fri', '7Sat'])
So, your entire code example should look like this:
df = pd.read_csv(CsvFileName)
p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)
columns = ["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]
p = p.reindex(columns=columns)
p[columns] = p[columns].astype(int)
It's because you haven't declared outchar
before you use it. That means that the compiler will assume it's a function returning an int
and taking an undefined number of undefined arguments.
You need to add a prototype pf the function before you use it:
void outchar(char); /* Prototype (declaration) of a function to be called */ int main(void) { ... } void outchar(char ch) { ... }
Note the declaration of the main
function differs from your code as well. It's actually a part of the official C specification, it must return an int
and must take either a void
argument or an int
and a char**
argument.
Download MacPorts, and run the following command:
sudo port install boost
This is a common problem with people getting started. Whenever you update your UI elements from a thread other than the main thread, you need to use:
this.Dispatcher.Invoke(() =>
{
...// your code here.
});
You can also use control.Dispatcher.CheckAccess()
to check whether the current thread owns the control. If it does own it, your code looks as normal. Otherwise, use above pattern.
To set permission on the data
folder and all it's subfolders and files:
Open command prompt from the ADB folder:
>> adb shell
>> su
>> find /data -type d -exec chmod 777 {} \;
Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:
<div style="text-align:center;">
<div style="border:1px solid #000; display:inline-block;">Div 1</div>
<div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>
def list_mean(nums):
sumof = 0
num_of = len(nums)
mean = 0
for i in nums:
sumof += i
mean = sumof / num_of
return float(mean)
Some useful Excel automation in C# , u can find from the following link.
http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm
bolton.
I don’t know how helpful will that be but in my case I just created another circle with border only and placed it “inside” the other shape.
On Linux systems and OS X, the character to input to cause an EOF is Ctrl-D. For Windows, it's Ctrl-Z.
Depending on the operating system, this character will only work if it's the first character on a line, i.e. the first character after an Enter. Since console input is often line-oriented, the system may also not recognize the EOF character until after you've followed it up with an Enter.
And yes, if that character is recognized as an EOF, then your program will never see the actual character. Instead, a C program will get a -1
from getchar()
.
I suggest:
writeLines(c("Hello","World"), "output.txt")
It is shorter and more direct than the current accepted answer. It is not necessary to do:
fileConn<-file("output.txt")
# writeLines command using fileConn connection
close(fileConn)
Because the documentation for writeLines()
says:
If the
con
is a character string, the function callsfile
to obtain a file connection which is opened for the duration of the function call.
# default settings for writeLines(): sep = "\n", useBytes = FALSE
# so: sep = "" would join all together e.g.
Old Question, but still, if it might help someone, here is complete sample
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" /><br/>
<asp:Button ID="Button1" runat="server" Text="Upload File" OnClick="UploadFile" /><br/>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
In your Code-behind, C# code to grab file and save it in Directory
protected void UploadFile(object sender, EventArgs e)
{
//folder path to save uploaded file
string folderPath = Server.MapPath("~/Upload/");
//Check whether Directory (Folder) exists, although we have created, if it si not created this code will check
if (!Directory.Exists(folderPath))
{
//If folder does not exists. Create it.
Directory.CreateDirectory(folderPath);
}
//save file in the specified folder and path
FileUpload1.SaveAs(folderPath + Path.GetFileName(FileUpload1.FileName));
//once file is uploaded show message to user in label control
Label1.Text = Path.GetFileName(FileUpload1.FileName) + " has been uploaded.";
}
Source: File Upload in ASP.NET (Web-Forms Upload control example)
I've used HttpClient in .NET 4.0 applications on numerous occasions. If you are familiar with NuGet, you can do an Install-Package Microsoft.Net.Http to add it to your project. See the link below for further details.
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.
use the below commands to install oracle java8 through terminal
Step -1) Visit Oracle JDK download page, look for RPM version
Step -2) Download oracle java 8 using the below command wget --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u121-b13/e9e7ea248e2c4826b92b3f075a80e441/jdk-8u121-linux-x64.rpm
Step -3) Install the java8 using below command sudo yum localinstall jdk-8u121-linux-x64.rpm Now the JDK should be installed at /usr/java/jdk1.8.0_121 Step -4) Remove the downloaded .rpm file to utilize the space. rm jdk-8u121-linux-x64.rpm
Step -5) Verify the java by using command java -version
Step -6) If the CentOS has multiple JDK installed, you can use the alternatives command to set the default java sudo alternatives --config java
Step -7)Optional set JAVA_HOME Environment variables. copy the path of jdk install i.e /usr/java/jdk1.8.0_121 use below command to export java home export JAVA_HOME=/usr/java/jdk1.8.0_121 export PATH=$PATH:$JAVA_HOME
public class Class1
{
private void btn_click(object sender, EventArgs e)
{
ServerRequest sr = new ServerRequest();
sr.Callback += new ServerRequest.CallbackEventHandler(sr_Callback);
sr.DoRequest("myrequest");
}
void sr_Callback(string something)
{
}
}
public class ServerRequest
{
public delegate void CallbackEventHandler(string something);
public event CallbackEventHandler Callback;
public void DoRequest(string request)
{
// do stuff....
if (Callback != null)
Callback("bla");
}
}
This is the official documentation supporting the above answers.
Changing the icon font location Bootstrap assumes icon font files will be located in the ../fonts/ directory, relative to the compiled CSS files. Moving or renaming those font files means updating the CSS in one of three ways: Change the @icon-font-path and/or @icon-font-name variables in the source Less files. Utilize the relative URLs option provided by the Less compiler. Change the url() paths in the compiled CSS. Use whatever option best suits your specific development setup.
Other than this one mistake the new users would do is, after downloading the bootstrap zip from the official website. They would tend to skip the fonts folder for copying in their dev setup. So missing fonts folder can also lead to this problem
If you're using a NFS, "test" is a better solution, because you can add a timeout to it, in case your NFS is down:
time timeout 3 test -f
/nfs/my_nfs_is_currently_down
real 0m3.004s <<== timeout is taken into account
user 0m0.001s
sys 0m0.004s
echo $?
124 <= 124 means the timeout has been reached
A "[ -e my_file ]" construct will freeze until the NFS is functional again:
if [ -e /nfs/my_nfs_is_currently_down ]; then echo "ok" else echo "ko" ; fi
<no answer from the system, my session is "frozen">
Putting #pragma once
at the top of your header file will ensure that it is only included once. Note that #pragma once
is not standard C99, but supported by most modern compilers.
An alternative is to use include guards (e.g. #ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */
)
Basically you can isolate your root application context and web application context using ContextLoaderListner.
The config file mapped with context param will behave as root application context configuration. And config file mapped with dispatcher servlet will behave like web application context.
In any web application we may have multiple dispatcher servlets, so multiple web application contexts.
But in any web application we may have only one root application context that is shared with all web application contexts.
We should define our common services, entities, aspects etc in root application context. And controllers, interceptors etc are in relevant web application context.
A sample web.xml is
<!-- language: xml -->
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>example.config.AppConfig</param-value>
</context-param>
<servlet>
<servlet-name>restEntryPoint</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>example.config.RestConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>restEntryPoint</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>webEntryPoint</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>example.config.WebConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>webEntryPoint</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Here config class example.config.AppConfig can be used to configure services, entities, aspects etc in root application context that will be shared with all other web application contexts (for example here we have two web application context config classes RestConfig and WebConfig)
PS: Here ContextLoaderListener is completely optional. If we will not mention ContextLoaderListener in web.xml here, AppConfig will not work. In that case we need to configure all our services and entities in WebConfig and Rest Config.
stdClass is a another great PHP feature. You can create a anonymous PHP class. Lets check an example.
$page=new stdClass();
$page->name='Home';
$page->status=1;
now think you have a another class that will initialize with a page object and execute base on it.
<?php
class PageShow {
public $currentpage;
public function __construct($pageobj)
{
$this->currentpage = $pageobj;
}
public function show()
{
echo $this->currentpage->name;
$state = ($this->currentpage->status == 1) ? 'Active' : 'Inactive';
echo 'This is ' . $state . ' page';
}
}
Now you have to create a new PageShow object with a Page Object.
Here no need to write a new Class Template for this you can simply use stdClass to create a Class on the fly.
$pageview=new PageShow($page);
$pageview->show();
If you cannot see the "ng serve" command running, then you can do the following on Mac OSX (This should work on any Linux and Uni software as well).
ps -ef | grep "ng serve"
From this, find out the PID of the process and then kill it with the following command.
kill -9 <PID>
re.findall finds all the occurrence of the regex in a string and return in a list. Here, you are using a list of strings, you need this to use re.findall
Note - If the regex fails, an empty list is returned.
import re, sys
f = open('picklee', 'r')
lines = f.readlines()
regex = re.compile(r'[A-Z]+')
for line in lines:
print (re.findall(regex, line))
The then()
method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:
getFeed().then(function(data) { vm.feed = data;});
The then()
function returns the promise with a resolved value of the previous then()
callback, allowing you the pass the value to subsequent callbacks:
promiseB = promiseA.then(function(result) {
return result + 1;
});
// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1
Check out my answer : https://stackoverflow.com/a/40285262/5879376
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setComponent(new ComponentName("com.whatsapp","com.whatsapp.Conversation"));
sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators("YOUR_PHONE_NUMBER")+"@s.whatsapp.net");//phone number without "+" prefix
startActivity(sendIntent);
For the record, if the script is run with set -e
(or #!/bin/bash -e
) and you therefore cannot check $?
directly (since the script would terminate on any return code other than zero), but want to handle a specific code, @gboffis comment is great:
/some/command || error_code=$?
if [ "${error_code}" -eq 2 ]; then
...
try this~
data_format <- function(data,digit=2,type='%'){
if(type=='d') {
type = 'f';
digit = 0;
}
switch(type,
'%' = {format <- paste("%.", digit, "f%", type, sep='');num <- 100},
'f' = {format <- paste("%.", digit, type, sep='');num <- 1},
cat(type, "is not a recognized type\n")
)
sprintf(format, num * data)
}
Assume you want to install package MySQL-python
on Windows, maybe try pip install
command with --global-option
. See the example command below:
pip install MySQL-python ^
--force-reinstall --no-cache-dir ^
--global-option=build_ext ^
--global-option="-IC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\include" ^
--global-option="-LC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\lib\opt" ^
--verbose
For this example, I fully installed 64-bit version of MySQL Connector C
in customized location of C:\my\install\MySQL-x64\MySQL Connector C 6.0.2\
.
By the way, I noticed that pip install MySQL-python
by default always looks into directory C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include
, even if you're using 64-bit and/or have installed the driver at a different location. I tested on Python-2.7, and I guess this is a bug of either Python or MySQL-python.
Hope the above might be of some help.
Just wanted to mention death
package here: https://github.com/jprichardson/node-death
Example:
var ON_DEATH = require('death')({uncaughtException: true}); //this is intentionally ugly
ON_DEATH(function(signal, err) {
//clean up code here
})
Try using String.format()
:
ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(String.format("%s",x));
import java.util.Calendar;
import java.util.Date;
public class Main {
public static long calculateDays(String startDate, String endDate)
{
Date sDate = new Date(startDate);
Date eDate = new Date(endDate);
Calendar cal3 = Calendar.getInstance();
cal3.setTime(sDate);
Calendar cal4 = Calendar.getInstance();
cal4.setTime(eDate);
return daysBetween(cal3, cal4);
}
public static void main(String[] args) {
System.out.println(calculateDays("2012/03/31", "2012/06/17"));
}
/** Using Calendar - THE CORRECT WAY**/
public static long daysBetween(Calendar startDate, Calendar endDate) {
Calendar date = (Calendar) startDate.clone();
long daysBetween = 0;
while (date.before(endDate)) {
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
}
This method checks whether mobile is connected to internet and returns true if connected:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
in manifest,
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Edit: This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet).
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
//You can replace it with your name
return !ipAddr.equals("");
} catch (Exception e) {
return false;
}
}
This does not directly answer the question, but may help future visitors.
If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange
event to set that variable.
This can be done in the HTML:
<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>
or with JavaScript:
cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})
No, I think alt
is better because the purpose of that attribute is to provide "alternate" text in the event that the image cannot be view (whether it be that the image is missing or that the browser itself is incapable of displaying it).
The most important difference is time ! When you do not want to change the data inside the list better to use tuple ! Here is the example why use tuple !
import timeit
print(timeit.timeit(stmt='[1,2,3,4,5,6,7,8,9,10]', number=1000000)) #created list
print(timeit.timeit(stmt='(1,2,3,4,5,6,7,8,9,10)', number=1000000)) # created tuple
In this example we executed both statements 1 million times
Output :
0.136621
0.013722200000000018
Any one can clearly notice the time difference.
If you only need to show time value in a datagrid or label similar, best way is convert directly time in datetime datatype.
SELECT CONVERT(datetime,myTimeField) as myTimeField FROM Table1
Also try to update your browser because Angular need latest browser. check: https://angular.io/guide/browser-support
I fixed console.log issue after updating latest browser.
/data/data/"your app package name "
but you wont able to read that unless you have a rooted device
def trunc(f,n):
return ('%.16f' % f)[:(n-16)]
As far as you're concerned once you've "pulled out" the contents with something like .html() it's just a string. You can test that with
<html>
<head>
<title>runthis</title>
<script type="text/javascript" language="javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready( function() {
var x = $("#foo").html();
alert( typeof(x) );
});
</script>
</head>
<body>
<div id="foo"><table><tr><td>x</td></tr></table><span>xyz</span></div>
</body>
</html>
The alert text is string. As long as you don't pass it to a parser there's no magic about it, it's a string like any other string.
There's nothing that hinders you from using .post() to send this string back to the server.
edit: Don't pass a string as the parameter data to .post() but an object, like
var data = {
id: currid,
html: div_html
};
$.post("http://...", data, ...);
jquery will handle the encoding of the parameters.
If you (for whatever reason) want to keep your string you have to encode the values with something like escape().
var data = 'id='+ escape(currid) +'&html='+ escape(div_html);
Current answers are either incomplete or inefficient. Here is (perhaps) the shortest way to achieve the outcome (using theme_void()
:
data(diamonds) # Data example
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut)) +
theme_void() + theme(legend.position="none")
The outcome is:
If you are interested in just eliminating the labels, labs(x="", y="")
does the trick:
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut)) +
labs(x="", y="")
Personally I would use something like mplayer with the audio pass though option eg -oac copy
You're throwing away a result row when you do $sth->fetchColumn()
. That's not how you check if there's any results. you do
if ($sth->rowCount() > 0) {
... got results ...
} else {
echo 'nothing';
}
relevant docs here: http://php.net/manual/en/pdostatement.rowcount.php
A Python script like this:
import time
cur_time = int(time.time()*1000)
In C, the compiler can generally optimize them to be the same if the result is unused.
However, in C++ if using other types that provide their own ++ operators, the prefix version is likely to be faster than the postfix version. So, if you don't need the postfix semantics, it is better to use the prefix operator.
It's ugly, but I achieved a semblance of this like so:
Dockerfile:
FROM foo
COPY ./m2/ /root/.m2
RUN stuff
imageBuild.sh:
docker build . -t barImage
container="$(docker run -d barImage)"
rm -rf ./m2
docker cp "$container:/root/.m2" ./m2
docker rm -f "$container"
I have a java build that downloads the universe into /root/.m2, and did so every single time. imageBuild.sh
copies the contents of that folder onto the host after the build, and Dockerfile
copies them back into the image for the next build.
This is something like how a volume would work (i.e. it persists between builds).
You can make the import command from any SQL query browser using the following command:
source C:\path\to\file\dump.sql
Run the above code in the query window ... and wait a while :)
This is more or less equal to the previously stated command line version. The main difference is that it is executed from within MySQL instead. For those using non-standard encodings, this is also safer than using the command line version because of less risk of encoding failures.
The closest I can get to this is this example:
or
.container {
background: blue;
border: 10px solid blue;
max-height: 200px;
max-width: 200px;
overflow:hidden;
box-sizing:border-box;
}
img {
display: block;
max-height: 100%;
max-width: 100%;
}
The main problem is that the height takes the percentage of the containers height, so it is looking for an explicitly set height in the parent container, not it's max-height.
The only way round this to some extent I can see is the fiddle above where you can hide the overflow, but then the padding still acts as visible space for the image to flow into, and so replacing with a solid border works instead (and then adding border-box to make it 200px if that's the width you need)
Not sure if this would fit with what you need it for, but the best I can seem to get to.
Similar to unutbu above, you could also use applymap
as follows:
import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
df = df.applymap("${0:.2f}".format)
The tweak:
position:fixed;
works, but it breaks certain options....for example a scrollable menu that is tagged with a fixed position will not expand with the browser window anymore...wish there was another way to pin something on top/always visible
You need call in.close()
, in a finally
block to ensure it occurs.
From the Eclipse documentation, here is why it flags this particular problem (emphasis mine):
Classes implementing the interface java.io.Closeable (since JDK 1.5) and java.lang.AutoCloseable (since JDK 1.7) are considered to represent external resources, which should be closed using method close(), when they are no longer needed.
The Eclipse Java compiler is able to analyze whether code using such types adheres to this policy.
...
The compiler will flag [violations] with "Resource leak: 'stream' is never closed".
Full explanation here.
Perhaps a more pythonic way of doing so.
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, t, b, t, c)
plt.show()
Procedure to auto fix AUTO_INCREMENT value of table
DROP PROCEDURE IF EXISTS update_auto_increment;
DELIMITER //
CREATE PROCEDURE update_auto_increment (_table VARCHAR(64))
BEGIN
DECLARE _max_stmt VARCHAR(1024);
DECLARE _stmt VARCHAR(1024);
SET @inc := 0;
SET @MAX_SQL := CONCAT('SELECT IFNULL(MAX(`id`), 0) + 1 INTO @inc FROM ', _table);
PREPARE _max_stmt FROM @MAX_SQL;
EXECUTE _max_stmt;
DEALLOCATE PREPARE _max_stmt;
SET @SQL := CONCAT('ALTER TABLE ', _table, ' AUTO_INCREMENT = ', @inc);
PREPARE _stmt FROM @SQL;
EXECUTE _stmt;
DEALLOCATE PREPARE _stmt;
END//
DELIMITER ;
CALL update_auto_increment('your_table_name')
Let's see the code of how we can use this
import react from 'react'
function Header()
{
return <p><b><h1>This is the Heading section</h1></b></p>;
}
**export default Header;**
You can use the ternary operator notation:
<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">
This is what I use:
// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {
// truncate string
$stringCut = substr($string, 0, 500);
$endPoint = strrpos($stringCut, ' ');
//if the string doesn't contain any space then it will cut without word basis.
$string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
$string .= '... <a href="/this/story">Read More</a>';
}
echo $string;
You can tweak it further but it gets the job done in production.
I was getting this error even if I did all the solutions mentioned above.
by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfig ...
At some point when i look up the POM there was this dependency in it
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
And the Pojo class had the following imports
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
Which clearly shows the application was expecting a datasource.
What I did was I removed the JPA dependency from pom and replaced the imports for the pojo with the following once
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
Finally I got SUCCESSFUL build. Check it out you might have run into the same problem
Here is a short and simple line using InternetDomainName.topPrivateDomain()
in Guava: InternetDomainName.from(new URL(url).getHost()).topPrivateDomain().toString()
Given http://www.google.com/blah
, that will give you google.com
. Or, given http://www.google.co.mx
, it will give you google.co.mx
.
As Sa Qada commented in another answer on this post, this question has been asked earlier: Extract main domain name from a given url. The best answer to that question is from Satya, who suggests Guava's InternetDomainName.topPrivateDomain()
public boolean isTopPrivateDomain()
Indicates whether this domain name is composed of exactly one subdomain component followed by a public suffix. For example, returns true for google.com and foo.co.uk, but not for www.google.com or co.uk.
Warning: A true result from this method does not imply that the domain is at the highest level which is addressable as a host, as many public suffixes are also addressable hosts. For example, the domain bar.uk.com has a public suffix of uk.com, so it would return true from this method. But uk.com is itself an addressable host.
This method can be used to determine whether a domain is probably the highest level for which cookies may be set, though even that depends on individual browsers' implementations of cookie controls. See RFC 2109 for details.
Putting that together with URL.getHost()
, which the original post already contains, gives you:
import com.google.common.net.InternetDomainName;
import java.net.URL;
public class DomainNameMain {
public static void main(final String... args) throws Exception {
final String urlString = "http://www.google.com/blah";
final URL url = new URL(urlString);
final String host = url.getHost();
final InternetDomainName name = InternetDomainName.from(host).topPrivateDomain();
System.out.println(urlString);
System.out.println(host);
System.out.println(name);
}
}
I got a way which finally resolve this 1. check your calsspath in the top build.gradle,e.g mine is classpath 'com.android.tools.build:gradle:2.1.0-alpha3' then go to https://jcenter.bintray.com/com/android/tools/build/gradle/ find a release which is newer than yours,here I choose 2.1.0-beta3 change classpath to below, then launch the build. classpath 'com.android.tools.build:gradle:2.1.0-beta3'
It's a syntax for array references - you need to use (&array)
to clarify to the compiler that you want a reference to an array, rather than the (invalid) array of references int & array[100];
.
EDIT: Some clarification.
void foo(int * x);
void foo(int x[100]);
void foo(int x[]);
These three are different ways of declaring the same function. They're all treated as taking an int *
parameter, you can pass any size array to them.
void foo(int (&x)[100]);
This only accepts arrays of 100 integers. You can safely use sizeof
on x
void foo(int & x[100]); // error
This is parsed as an "array of references" - which isn't legal.
This works well for me. It uses an array so you aren't looping through each cell. Runs much faster over large worksheet sections.
Sub Trim_Cells_Array_Method()
Dim arrData() As Variant
Dim arrReturnData() As Variant
Dim rng As Excel.Range
Dim lRows As Long
Dim lCols As Long
Dim i As Long, j As Long
lRows = Selection.Rows.count
lCols = Selection.Columns.count
ReDim arrData(1 To lRows, 1 To lCols)
ReDim arrReturnData(1 To lRows, 1 To lCols)
Set rng = Selection
arrData = rng.value
For j = 1 To lCols
For i = 1 To lRows
arrReturnData(i, j) = Trim(arrData(i, j))
Next i
Next j
rng.value = arrReturnData
Set rng = Nothing
End Sub
The above didn't work for me in 3.3. Try this instead (YMMV, etc)
import urllib.request
url = "http://www.google.com/"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
print (response.read().decode('utf-8'))
a=int(input("Enter your number by seconds "))
d=a//(24*3600) #Days
h=a//(60*60)%24 #hours
m=a//60%60 #minutes
s=a%60 #seconds
print("Days ",d,"hours ",h,"minutes ",m,"seconds ",s)
System.out.println("Link : " + s3Object.getObjectContent().getHttpRequest().getURI());
with this you can retrieve the link of already uploaded file to S3 bucket.
I got it working by
Easily readable and customisable way to get a timestamp in your desired format, without use of any library:
function timestamp(){
function pad(n) {return n<10 ? "0"+n : n}
d=new Date()
dash="-"
colon=":"
return d.getFullYear()+dash+
pad(d.getMonth()+1)+dash+
pad(d.getDate())+" "+
pad(d.getHours())+colon+
pad(d.getMinutes())+colon+
pad(d.getSeconds())
}
(If you require time in UTC format, then just change the function calls. For example "getMonth" becomes "getUTCMonth")
I was getting the error "The module may compatible with this version of windows" for both version of RegSvr32 (32 bit and 64 bit). I was trying to register a DLL that was built for XP (32 bit) in Server 2008 R2 (x64) and none of the Regsr32 resolutions worked for me. However, registering the assembly in the appropriate .Net worked perfect for me. C:\Windows\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe
My pages also kept 404'ing. Contacted support, and they pointed out that the url is case sensitive; solved my issue.
Yes, when you import classes with the same simple names, you must refer to them by their fully qualified class names. I would leave the import statements in, as it gives other developers a sense of what is in the file when they are working with it.
java.util.Data date1 = new java.util.Date();
my.own.Date date2 = new my.own.Date();
By convention, the directory src/main/resources
contains the resources that will be used by the application. So Maven will include them in the final JAR
.
Thus in your application, you will access them using the getResourceAsStream()
method, as the resources are loaded in the classpath.
If you need to have them outside your application, do not store them in src/main/resources
as they will be bundled by Maven. Of course, you can exclude them (using the link given by chkal) but it is better to create another directory (for example src/main/external-resources
) in order to keep the conventions regarding the src/main/resources
directory.
In the latter case, you will have to deliver the resources independently as your JAR file (this can be achieved by using the Assembly plugin). If you need to access them in your Eclipse environment, go to the Properties
of your project, then in Java Build Path
in Sources
tab, add the folder (for example src/main/external-resources
). Eclipse will then add this directory in the classpath.
Your code using createWriteStream creates a file descriptor for every write. log.end is better because it asks node to close immediately after the write.
var fs = require('fs');
var logStream = fs.createWriteStream('log.txt', {flags: 'a'});
// use {flags: 'a'} to append and {flags: 'w'} to erase and write a new file
logStream.write('Initial line...');
logStream.end('this is the end line');
origin
is the default alias to the URL of your remote repository.
This will happen when you doubleclick a JAR file in Windows explorer, but the JAR is by itself actually not an executable JAR. A real executable JAR should have at least a class with a main()
method and have it referenced in MANIFEST.MF
.
In Eclispe, you need to export the project as Runnable JAR file instead of as JAR file to get a real executable JAR.
Or, if your JAR is solely a container of a bunch of closely related classes (a library), then you shouldn't doubleclick it, but open it using some ZIP tool. Windows explorer namely by default associates JAR files with java.exe
, which won't work for those kind of libary JARs.
These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit
for Chrome, Safari; -moz
for Firefox, -o
for Opera, -ms
for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.
This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.
To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:
.elementClass {
-moz-border-radius: 2em;
-ms-border-radius: 2em;
-o-border-radius: 2em;
-webkit-border-radius: 2em;
border-radius: 2em;
}
Specifically, to address the CSS in your question, the lines you quote:
-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;
Specify the column-count
, column-gap
and column-fill
properties for Webkit browsers and Firefox.
References:
Note, you can do:
$results = Project::select('name')->orderBy('name')->get();
This generate a query like:
"SELECT name FROM proyect ORDER BY 'name' ASC"
In some apps when the DB is not optimized and the query is more complex, and you need prevent generate a ORDER BY in the finish SQL, you can do:
$result = Project::select('name')->get();
$result = $result->sortBy('name');
$result = $result->values()->all();
Now is php who order the result.
Found it in the manual
The mode parameter is used to specify the handling of untracked files. It is optional: it defaults to all, and if specified, it must be stuck to the option (e.g. -uno, but not -u no).
git status -uno
One possible solution is to add a class to every option
<select name="export_type" id="export_type">
<option class="export_option" value="pdf">PDF</option>
<option class="export_option" value="xlsx">Excel</option>
<option class="export_option" value="docx">DocX</option>
</select>
and then use the click handler for this class
$(document).ready(function () {
$(".export_option").click(function (e) {
//alert('click');
});
});
UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome. Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.
If you want to uninstall when connected to single device/emulator then use below command
adb uninstall <package name>
else with multiple devices then use below command
adb -s <device ID> uninstall <package name>
I think it is more pythonic:
aList.remove(123)
aList.insert(0, 2014)
more useful:
def shuffle(list, to_delete, to_shuffle, index):
list.remove(to_delete)
list.insert(index, to_shuffle)
return
list = ['a', 'b']
shuffle(list, 'a', 'c', 0)
print list
>> ['c', 'b']
Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.
In vim type
:help vimrc
and check your path to the _vimrc/.vimrc file with
:echo $HOME
:echo $VIM
Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.
:help source
The two operands (1 and 3) are integers, therefore integer arithmetic (division here) is used. Declaring the result variable as double just causes an implicit conversion to occur after division.
Integer division of course returns the true result of division rounded towards zero. The result of 0.333...
is thus rounded down to 0 here. (Note that the processor doesn't actually do any rounding, but you can think of it that way still.)
Also, note that if both operands (numbers) are given as floats; 3.0 and 1.0, or even just the first, then floating-point arithmetic is used, giving you 0.333...
.