Use OleDB, you can create, read, and edit excel files pretty easily. Read the MSDN docs for more info:
http://msdn.microsoft.com/en-us/library/aa288452(VS.71).aspx
I've used OleDB to read from excel files and I know you can create them, but I haven't done it firsthand.
There is an amazing library called SwipeCellKit
, it should gain more acknowledgement. In my opinion it is cooler than MGSwipeTableCell
. The latter doesn't completely replicate the behavior of the Mail app's cells whereas SwipeCellKit
does. Have a look
In my humble opinion, idempotence means:
I send a compete resource definition, so - the resulting resource state is exactly as defined by PUT params. Each and every time I update the resource with the same PUT params - the resulting state is exactly the same.
I sent only part of the resource definition, so it might happen other users are updating this resource's OTHER parameters in a meantime. Consequently - consecutive patches with the same parameters and their values might result with different resource state. For instance:
Presume an object defined as follows:
CAR: - color: black, - type: sedan, - seats: 5
I patch it with:
{color: 'red'}
The resulting object is:
CAR: - color: red, - type: sedan, - seats: 5
Then, some other users patches this car with:
{type: 'hatchback'}
so, the resulting object is:
CAR: - color: red, - type: hatchback, - seats: 5
Now, if I patch this object again with:
{color: 'red'}
the resulting object is:
CAR: - color: red, - type: hatchback, - seats: 5
What is DIFFERENT to what I've got previously!
This is why PATCH is not idempotent while PUT is idempotent.
There is a nice Dzone article from July 2017 which details various ways of summarising NaN values. Check it out here.
The article I have cited provides additional value by: (1) Showing a way to count and display NaN counts for every column so that one can easily decide whether or not to discard those columns and (2) Demonstrating a way to select those rows in specific which have NaNs so that they may be selectively discarded or imputed.
Here's a quick example to demonstrate the utility of the approach - with only a few columns perhaps its usefulness is not obvious but I found it to be of help for larger data-frames.
import pandas as pd
import numpy as np
# example DataFrame
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
# Check whether there are null values in columns
null_columns = df.columns[df.isnull().any()]
print(df[null_columns].isnull().sum())
# One can follow along further per the cited article
Because of the GDPR it makes no sense to use the iframe, you should rather use the object tag with the embed tag and also use the embed link.
<object width="100%" height="333">
<param name="movie" value="https://www.youtube-nocookie.com/embed/Sdg0ef2PpBw">
<embed src="https://www.youtube-nocookie.com/embed/Sdg0ef2PpBw" width="100%" height="333">
</object>
_x000D_
You should also activate the extended data protection mode function to receive the no cookie url.
type="application/x-shockwave-flash"
flash does not have to be used
Nocookie, however, means that data is still being transmitted, namely the thumbnail that is loaded from YouTube. But at least data is no longer passed on to advertising networks (as example DoubleClick). And no user data is stored on your website by youtube.
The dash type of a linestyle
is given by the linetype
, which does also select the line color unless you explicitely set an other one with linecolor
.
However, the support for dashed lines depends on the selected terminal:
png
(uses libgd
)pngcairo
, support dashed lines, but it is disables by default. To enable it, use set termoption dashed
, or set terminal pngcairo dashed ...
.linetype
, use the test
command:Running
set terminal pngcairo dashed
set output 'test.png'
test
set output
gives:
whereas, the postscript
terminal shows different dash patterns:
set terminal postscript eps color colortext
set output 'test.eps'
test
set output
Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:
A new dashtype
parameter was introduced:
To get the predefined dash patterns, use e.g.
plot x dashtype 2
You can also specify custom dash patterns like
plot x dashtype (3,5,10,5),\
2*x dashtype '.-_'
The terminal options dashed
and solid
are ignored. By default all lines are solid. To change them to dashed, use e.g.
set for [i=1:8] linetype i dashtype i
The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic
:
In case anyone wants the answer of Dirk Vollmar in a C# switch statement:
case "doc": return "application/msword";
case "dot": return "application/msword";
case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "dotx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
case "docm": return "application/vnd.ms-word.document.macroEnabled.12";
case "dotm": return "application/vnd.ms-word.template.macroEnabled.12";
case "xls": return "application/vnd.ms-excel";
case "xlt": return "application/vnd.ms-excel";
case "xla": return "application/vnd.ms-excel";
case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
case "xltx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
case "xlsm": return "application/vnd.ms-excel.sheet.macroEnabled.12";
case "xltm": return "application/vnd.ms-excel.template.macroEnabled.12";
case "xlam": return "application/vnd.ms-excel.addin.macroEnabled.12";
case "xlsb": return "application/vnd.ms-excel.sheet.binary.macroEnabled.12";
case "ppt": return "application/vnd.ms-powerpoint";
case "pot": return "application/vnd.ms-powerpoint";
case "pps": return "application/vnd.ms-powerpoint";
case "ppa": return "application/vnd.ms-powerpoint";
case "pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
case "potx": return "application/vnd.openxmlformats-officedocument.presentationml.template";
case "ppsx": return "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
case "ppam": return "application/vnd.ms-powerpoint.addin.macroEnabled.12";
case "pptm": return "application/vnd.ms-powerpoint.presentation.macroEnabled.12";
case "potm": return "application/vnd.ms-powerpoint.template.macroEnabled.12";
case "ppsm": return "application/vnd.ms-powerpoint.slideshow.macroEnabled.12";
case "mdb": return "application/vnd.ms-access";
Neither code is always better. They do different things, so they are good at different things.
InvariantCultureIgnoreCase
uses comparison rules based on english, but without any regional variations. This is good for a neutral comparison that still takes into account some linguistic aspects.
OrdinalIgnoreCase
compares the character codes without cultural aspects. This is good for exact comparisons, like login names, but not for sorting strings with unusual characters like é
or ö
. This is also faster because there are no extra rules to apply before comparing.
This would be a cleaner implementation:
function size2Byte($size) {
$units = array('KB', 'MB', 'GB', 'TB');
$currUnit = '';
while (count($units) > 0 && $size > 1024) {
$currUnit = array_shift($units);
$size /= 1024;
}
return ($size | 0) . $currUnit;
}
I'd rather use the expression "serialization" than "casting into bytes". Serializing an object means converting it into a byte array (or XML, or something else) that can be used on the remote box to re-construct the object. In .NET, the Serializable
attribute marks types whose objects can be serialized.
The presence of this data-attribute tells Bootstrap to switch between visual or a logical states of another element on user interaction.
It is used to show modals, tab content, tooltips and popover menus as well as setting a pressed-state for a toggle-button. It is used in multiple ways without a clear documentation.
The following worked for me to vertically align content (multi-line) in a list-table
.. list-table::
:class: longtable
:header-rows: 1
:stub-columns: 1
:align: left
:widths: 20, 20, 20, 20, 20
* - Classification
- Restricted
- Company |br| Confidential
- Internal Use Only
- Public
* - Row1 col1
- Row1 col2
- Row1 col3
- Row1 col4
- Row1 col5
Using theme overrides .css option I defined:
.stub {
text-align: left;
vertical-align: top;
}
In the theme that I use 'python-docs-theme', the cell entry is defined as 'stub' class. Use your browser development menu to inspect what your theme class is for cell content and update that accordingly.
The pattern \d
might not be supported by your sed
. Try [0-9]
or [[:digit:]]
instead.
To only print the actual match (not the entire matching line), use a substitution.
sed -n 's/.*\([0-9][0-9]*G[0-9][0-9]*\).*/\1/p'
You can use:
jQuery('[name="' + nameAttributeValue + '"]');
this will be an inefficient way to select elements though, so it would be best to also use the tag name or restrict the search to a specific element:
jQuery('div[name="' + nameAttributeValue + '"]'); // with tag name
jQuery('div[name="' + nameAttributeValue + '"]',
document.getElementById('searcharea')); // with a search base
import nltk
is Python syntax, and as such won't work in a shell script.
To test the version of nltk
and scikit_learn
, you can write a Python script and run it. Such a script may look like
import nltk
import sklearn
print('The nltk version is {}.'.format(nltk.__version__))
print('The scikit-learn version is {}.'.format(sklearn.__version__))
# The nltk version is 3.0.0.
# The scikit-learn version is 0.15.2.
Note that not all Python packages are guaranteed to have a __version__
attribute, so for some others it may fail, but for nltk and scikit-learn at least it will work.
Filter the version number.
java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}'
You cannot store arrays in a vector
or any other container. The type of the elements to be stored in a container (called the container's value type) must be both copy constructible and assignable. Arrays are neither.
You can, however, use an array
class template, like the one provided by Boost, TR1, and C++0x:
std::vector<std::array<double, 4> >
(You'll want to replace std::array
with std::tr1::array
to use the template included in C++ TR1, or boost::array
to use the template from the Boost libraries. Alternatively, you can write your own; it's quite straightforward.)
SELECT * from `user` ORDER BY `user_id`;
SET @count = 0;
UPDATE `user` SET `user_id` = @count:= @count + 1;
ALTER TABLE `user_id` AUTO_INCREMENT = 1;
if you want to order by
What I have done in the past is declare my inner class collections using IList<Class>
, ICollection<Class>
or IEnumerable<Class>
(if static list) depending on whether or not I will have to do any number of the following in a method in my repository: enumerate, sort/order or modify. When I just need to enumerate (and maybe sort) over objects then I create a temp List<Class>
to work with the collection within an IEnumerable method. I think this practice would only be effective if the collection is relatively small, but it may be good practice in general, idk. Please correct me if there is evidence as to why this would not good practice.
When I had this problem, I installed 'Remote Tools for Visual Studio 2015' from MSDN. I attached my local VS to the server to debug.
I appreciate that some folks may not have the ability to either install on or access other servers, but I thought I'd throw it out there as an option.
Integer Types:
short -> signed short
signed short
unsigned short
int -> signed int
signed int
unsigned int
signed -> signed int
unsigned -> unsigned int
long -> signed long
signed long
unsigned long
Be careful of char:
char (is signed or unsigned depending on the implmentation)
signed char
unsigned char
To add to Skelly's Bootstrap 3 no-gutter answer above (https://stackoverflow.com/a/21282059/662883)
Add the following to prevent gutters on a row containing only one column (useful when using column-wrapping: http://getbootstrap.com/css/#grid-example-wrapping):
.row.no-gutter [class*='col-']:only-child,
.row.no-gutter [class*='col-']:only-child
{
padding-right: 0;
padding-left: 0;
}
From the python command prompt:
import scipy
print scipy.__version__
In python 3 you'll need to change it to:
print (scipy.__version__)
Windows: I prefer Alt+F3 to search a string and change all instances of search string at once.
Note: In Kotlin the syntax for declaring the arrays in annotations uses arrayOf(...)
instead of {...}
@Entity
@Table(uniqueConstraints=arrayOf(UniqueConstraint(columnNames=arrayOf("book", "chapter_number"))))
class Chapter(@ManyToOne var book:Book,
@Column var chapterNumber:Int)
Note: As of Kotlin 1.2 its is possible to use the [...]
syntax so the code become much simpler
@Entity
@Table(uniqueConstraints=[UniqueConstraint(columnNames=["book", "chapter_number"])])
class Chapter(@ManyToOne var book:Book,
@Column var chapterNumber:Int)
From jquery prospective - it's just adding load
/onload
event to window and document.
Check this out:
In my app, I had similar problem: 2 line of string and, eventually, add "..." if the string was too long. I used this code in xml file into textview tag:
android:maxLines="2"
android:ellipsize="end"
android:singleLine="false"
It will take some work, but is certainly not impossible.
What I have done is:
Microsoft.CSharp.CSharpCodeProvider
(CompileAssemblyFromSource)Activator.CreateInstance
)This way you can deal with the C# code you already know, instead of having to emit MSIL.
But this works best if your class implements some interface (or is derived from some baseclass), else how is the calling code (read: compiler) to know about that class that will be generated at runtime?
Here is a STL-like class
File "csvfile.h"
#pragma once
#include <iostream>
#include <fstream>
class csvfile;
inline static csvfile& endrow(csvfile& file);
inline static csvfile& flush(csvfile& file);
class csvfile
{
std::ofstream fs_;
const std::string separator_;
public:
csvfile(const std::string filename, const std::string separator = ";")
: fs_()
, separator_(separator)
{
fs_.exceptions(std::ios::failbit | std::ios::badbit);
fs_.open(filename);
}
~csvfile()
{
flush();
fs_.close();
}
void flush()
{
fs_.flush();
}
void endrow()
{
fs_ << std::endl;
}
csvfile& operator << ( csvfile& (* val)(csvfile&))
{
return val(*this);
}
csvfile& operator << (const char * val)
{
fs_ << '"' << val << '"' << separator_;
return *this;
}
csvfile& operator << (const std::string & val)
{
fs_ << '"' << val << '"' << separator_;
return *this;
}
template<typename T>
csvfile& operator << (const T& val)
{
fs_ << val << separator_;
return *this;
}
};
inline static csvfile& endrow(csvfile& file)
{
file.endrow();
return file;
}
inline static csvfile& flush(csvfile& file)
{
file.flush();
return file;
}
File "main.cpp"
#include "csvfile.h"
int main()
{
try
{
csvfile csv("MyTable.csv"); // throws exceptions!
// Header
csv << "X" << "VALUE" << endrow;
// Data
csv << 1 << "String value" << endrow;
csv << 2 << 123 << endrow;
csv << 3 << 1.f << endrow;
csv << 4 << 1.2 << endrow;
}
catch (const std::exception& ex)
{
std::cout << "Exception was thrown: " << e.what() << std::endl;
}
return 0;
}
Latest version here
Comparable
is for providing a default ordering on data objects, for example if the data objects have a natural order.
A Comparator
represents the ordering itself for a specific use.
I hope this clarifies those two:
x | 2
0001 //x
0010 //2
0011 //result = 3
x & 1
0001 //x
0001 //1
0001 //result = 1
exactly I used this
private void updateSetTopState(int index) {
View v = listview.getChildAt(index -
listview.getFirstVisiblePosition()+listview.getHeaderViewsCount());
if(v == null)
return;
TextView aa = (TextView) v.findViewById(R.id.aa);
aa.setVisibility(View.VISIBLE);
}
Another question asked specifically how to perform multiple left joins using dplyr in R . The question was marked as a duplicate of this one so I answer here, using the 3 sample data frames below:
x <- data.frame(i = c("a","b","c"), j = 1:3, stringsAsFactors=FALSE)
y <- data.frame(i = c("b","c","d"), k = 4:6, stringsAsFactors=FALSE)
z <- data.frame(i = c("c","d","a"), l = 7:9, stringsAsFactors=FALSE)
Update June 2018: I divided the answer in three sections representing three different ways to perform the merge. You probably want to use the purrr
way if you are already using the tidyverse packages. For comparison purposes below, you'll find a base R version using the same sample dataset.
1) Join them with reduce
from the purrr
package:
The purrr
package provides a reduce
function which has a concise syntax:
library(tidyverse)
list(x, y, z) %>% reduce(left_join, by = "i")
# A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
You can also perform other joins, such as a full_join
or inner_join
:
list(x, y, z) %>% reduce(full_join, by = "i")
# A tibble: 4 x 4
# i j k l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
# 4 d NA 6 8
list(x, y, z) %>% reduce(inner_join, by = "i")
# A tibble: 1 x 4
# i j k l
# <chr> <int> <int> <int>
# 1 c 3 5 7
2) dplyr::left_join()
with base R Reduce()
:
list(x,y,z) %>%
Reduce(function(dtf1,dtf2) left_join(dtf1,dtf2,by="i"), .)
# i j k l
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
3) Base R merge()
with base R Reduce()
:
And for comparison purposes, here is a base R version of the left join based on Charles's answer.
Reduce(function(dtf1, dtf2) merge(dtf1, dtf2, by = "i", all.x = TRUE),
list(x,y,z))
# i j k l
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
Another possibility is using tidyr::expand
:
library(dplyr)
library(tidyr)
df %>% group_by_at(vars(-freq)) %>% expand(temp = 1:freq) %>% select(-temp)
#> # A tibble: 6 x 2
#> # Groups: var1, var2 [3]
#> var1 var2
#> <fct> <fct>
#> 1 a d
#> 2 b e
#> 3 b e
#> 4 c f
#> 5 c f
#> 6 c f
One-liner version of vonjd's answer:
library(data.table)
setDT(df)[ ,list(freq=rep(1,freq)),by=c("var1","var2")][ ,freq := NULL][]
#> var1 var2
#> 1: a d
#> 2: b e
#> 3: b e
#> 4: c f
#> 5: c f
#> 6: c f
Created on 2019-05-21 by the reprex package (v0.2.1)
Follow the steps:
More details for each step Click Here
There is no way in PostgreSQL to deconstruct a scalar JSON object. Thus, as you point out,
select length(to_json('Some "text"'::TEXT) ::TEXT);
is 15,
The trick is to convert the JSON into an array of one JSON element, then extract that element using ->>
.
select length( array_to_json(array[to_json('Some "text"'::TEXT)])->>0 );
will return 11.
As a shorthand you can run:
docker tag d58 myname/server:latest
Where d58
represents the first 3 characters of the IMAGE ID,in this case, that's all you need.
Finally, you can remove the old image as follows:
docker rmi server
The pop-up window does not have any close event that you can listen to.
On the other hand, there is a closed property that is set to true when the window gets closed.
You can set a timer to check that closed property and do it like this:
var win = window.open('foo.html', 'windowName',"width=200,height=200,scrollbars=no");
var timer = setInterval(function() {
if(win.closed) {
clearInterval(timer);
alert('closed');
}
}, 1000);
See this working Fiddle example!
We can use frequency method of Collections class for this. Split the string into string array. Use HashSet to remove duplicates and check frequency of each object in HashSet using frequency method of Collections
void usingCollections(){
String input = "cuttack";
String [] stringArray = input.split("");
Set<String> s = new HashSet(Arrays.asList(stringArray));
for(String abc : s){
System.out.println (abc + ":"+Collections.frequency(Arrays.asList(stringArray),abc));
}
}
If your merge was not too complicated another option would be to:
After that you are left with only the changes from the stash you dropped too early.
It's only supposed to send the information to the server. The reason that it must preceed the file field is that it has to come before the file payload in the request for the server to be able to use it to check the size of the upload.
How the value is used on the server depends on what you use to take care of the upload. The code is supposedly intended for a specific upload component that specifically looks for that value.
It seems that the built in upload support in PHP is one to use this field value.
in your code, at line
map.setCenter(new GLatLng(lat, lon), 5);
the setCenter method takes just one parameter, for the lat:long location. Why are you passing two parameters there ?
I suggest you should change it to,
map.setCenter(new GLatLng(lat, lon));
var fs = require("fs");
function readFileLineByLine(filename, processline) {
var stream = fs.createReadStream(filename);
var s = "";
stream.on("data", function(data) {
s += data.toString('utf8');
var lines = s.split("\n");
for (var i = 0; i < lines.length - 1; i++)
processline(lines[i]);
s = lines[lines.length - 1];
});
stream.on("end",function() {
var lines = s.split("\n");
for (var i = 0; i < lines.length; i++)
processline(lines[i]);
});
}
var linenumber = 0;
readFileLineByLine(filename, function(line) {
console.log(++linenumber + " -- " + line);
});
In general,
variable=$(command)
or
variable=`command`
The latter one is the old syntax, prefer $(command)
.
Note: variable = ....
means execute the command variable
with the first argument =
, the second ....
_.map using lodash like loop to achieve this
var result={};
_.map({one: 1, two: 2, three: 3}, function(num, key){ result[key]=num * 3; });
console.log(result)
//output
{one: 1, two: 2, three: 3}
Reduce is clever looks like above answare
_.reduce({one: 1, two: 2, three: 3}, function(result, num, key) {
result[key]=num * 3
return result;
}, {});
//output
{one: 1, two: 2, three: 3}
Try a slight different approach:
//set string and append it as object
var myHtmlString = '<iframe id="myFrame" width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>';
$('body').append(myHtmlString);
//as you noticed you can't just get it back
var myHtmlStringBack = $('#myFrame').html();
alert(myHtmlStringBack); // will be empty (a bug in jquery?) but...
//since an id was added to your iframe so you can retrieve its attributes back...
var width = $('#myFrame').attr('width');
var height = $('#myFrame').attr('height');
var src = $('#myFrame').attr('src');
var myReconstructedString = '<iframe id="myFrame" width="'+ width +'" height="'+ height +'" src="'+ src+'" frameborder="0" allowfullscreen></iframe>';
alert(myReconstructedString);
Here is a short example, the C++ way using rdbuf
. I got this from the web. I can't find my original source on this:
#include <fstream>
#include <iostream>
int main ()
{
std::ifstream f1 ("C:\\me.txt",std::fstream::binary);
std::ofstream f2 ("C:\\me2.doc",std::fstream::trunc|std::fstream::binary);
f2<<f1.rdbuf();
return 0;
}
iframe have "sandbox" attribute that may block pop up etc
To terminate a process you know the name of, try:
taskkill /IM notepad.exe
This will ask it to close, but it may refuse, offer to "save changes", etc. If you want to forcibly kill it, try:
taskkill /F /IM notepad.exe
Deleting nodes from XML
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
for (int i = nodes.Count - 1; i >= 0; i--)
{
nodes[i].ParentNode.RemoveChild(nodes[i]);
}
doc.Save(path);
Adding attribute to Nodes in XML
XmlDocument originalXml = new XmlDocument();
originalXml.Load(path);
XmlNode menu = originalXml.SelectSingleNode("//Settings");
XmlNode newSub = originalXml.CreateNode(XmlNodeType.Element, "Setting", null);
XmlAttribute xa = originalXml.CreateAttribute("name");
xa.Value = "qwerty";
XmlAttribute xb = originalXml.CreateAttribute("value");
xb.Value = "555";
newSub.Attributes.Append(xa);
newSub.Attributes.Append(xb);
menu.AppendChild(newSub);
originalXml.Save(path);
Make sure you specify pass header=None
and add usecols=[3,6]
for the 4th and 7th columns.
All other answers on this question didn't hit upon the key point.
Assume we have a table:
CREATE TABLE `table` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`value` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `value` (`value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
And have 10 rows with both id and value from 1 to 10:
INSERT INTO `table`(`id`, `value`) VALUES (1, 1),(2, 2),(3, 3),(4, 4),(5, 5),(6, 6),(7, 7),(8, 8),(9, 9),(10, 10);
Try the following 2 queries:
SELECT `value` v FROM `table` WHERE `value`>5; -- Get 5 rows
SELECT `value` v FROM `table` HAVING `value`>5; -- Get 5 rows
You will get exactly the same results, you can see the HAVING clause can work without GROUP BY clause.
Here's the difference:
SELECT `value` v FROM `table` WHERE `v`>5;
Error #1054 - Unknown column 'v' in 'where clause'
SELECT `value` v FROM `table` HAVING `v`>5; -- Get 5 rows
WHERE clause allows a condition to use any table column, but it cannot use aliases or aggregate functions. HAVING clause allows a condition to use a selected (!) column, alias or an aggregate function.
This is because WHERE clause filters data before select, but HAVING clause filters resulting data after select.
So put the conditions in WHERE clause will be more efficient if you have many many rows in a table.
Try EXPLAIN to see the key difference:
EXPLAIN SELECT `value` v FROM `table` WHERE `value`>5;
+----+-------------+-------+-------+---------------+-------+---------+------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+-------+---------+------+------+--------------------------+
| 1 | SIMPLE | table | range | value | value | 4 | NULL | 5 | Using where; Using index |
+----+-------------+-------+-------+---------------+-------+---------+------+------+--------------------------+
EXPLAIN SELECT `value` v FROM `table` having `value`>5;
+----+-------------+-------+-------+---------------+-------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+-------+---------+------+------+-------------+
| 1 | SIMPLE | table | index | NULL | value | 4 | NULL | 10 | Using index |
+----+-------------+-------+-------+---------------+-------+---------+------+------+-------------+
You can see either WHERE or HAVING uses index, but the rows are different.
Set Current State first ...this.state
Its because when you are going to assign a new state it may be undefined. so it will be fixed by setting state extracting current state also
this.setState({...this.state, field})
If there is an object in your state, you should set state as follows, suppose you have to set username inside the user object.
this.setState({user:{...this.state.user, ['username']: username}})
If you don't need the DATETIME value in the rest of your code, it'd be more efficient, simple and secure to use an UPDATE query with a sub-select, something like
UPDATE products SET t=(SELECT f FROM products WHERE id=17) WHERE id=42;
or in case it's in the same row in a single table, just
UPDATE products SET t=f WHERE id=42;
Just a note of a peculiarity I faced:
Consider:
db server: 192.168.0.101
web server: 192.168.0.102
If you have a user defined in mysql.user as 'user'@'192.168.0.102'
with password1 and another 'user'@'192.168.0.%'
with password2,
then,
if you try to connect to the db server from the web server as 'user' with password2,
it will result in an 'Access denied' error because the single IP 'user'@'192.168.0.102'
authentication is used over the wildcard 'user'@'192.168.0.%'
authentication.
Copy to Config File: /etc/mysql/my.cnf OR /bin/mysql/my.ini
[mysqld]
port = 3306
sql-mode=""
MySQL
restart.
Or you can also do
[mysqld]
port = 3306
SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
MySQL
restart.
import swineflu
x = swineflu.fibo() # create an object `x` of class `fibo`, an instance of the class
x.f() # call the method `f()`, bound to `x`.
Here is a good tutorial to get started with classes in Python.
since iOS7:
first: the content size width must be equal to the width of your scrollview
second: in your initWithNibName:
self.automaticallyAdjustsScrollViewInsets = NO;
That´s it.
Note: Most modern browsers will now allow you to navigate objects in the developer console. This answer is antiquated.
This method will walk through object properties and write them to the console with increasing indent:
function enumerate(o,s){
//if s isn't defined, set it to an empty string
s = typeof s !== 'undefined' ? s : "";
//if o is null, we need to output and bail
if(typeof o == "object" && o === null){
console.log(s+k+": null");
} else {
//iterate across o, passing keys as k and values as v
$.each(o, function(k,v){
//if v has nested depth
if(typeof v == "object" && v !== null){
//write the key to the console
console.log(s+k+": ");
//recursively call enumerate on the nested properties
enumerate(v,s+" ");
} else {
//log the key & value
console.log(s+k+": "+String(v));
}
});
}
}
Just pass it the object you want to iterate through:
var response = $.ajax({
url: myurl,
dataType: "json"
})
.done(function(a){
console.log("Returned values:");
enumerate(a);
})
.fail(function(){ console.log("request failed");});
This helped me out after reading @Mr-Faizan's and other answers.
Untick the 'Enable foreign key checks'
in phpMyAdmin and hit the query. I don't know about WorkBench but the other answers might help you out.
The KILL SESSION
command doesn't actually kill the session. It merely asks the session to kill itself. In some situations, like waiting for a reply from a remote database or rolling back transactions, the session will not kill itself immediately and will wait for the current operation to complete. In these cases the session will have a status of "marked for kill". It will then be killed as soon as possible.
Check the status to confirm:
SELECT sid, serial#, status, username FROM v$session;
You could also use IMMEDIATE clause:
ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;
The IMMEDIATE
clause does not affect the work performed by the command, but it returns control back to the current session immediately, rather than waiting for confirmation of the kill. Have a look at Killing Oracle Sessions.
Update If you want to kill all the sessions, you could just prepare a small script.
SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' FROM v$session;
Spool the above to a .sql
file and execute it, or, copy paste the output and run it.
Try this:
Update TableB Set
Code = Coalesce(
(Select Max(Value)
From TableA
Where Id = b.Id), 123)
From TableB b
Wherever you want to apply a break, either a table
or tr
, you needs to give a class for ex. page-break
with CSS as mentioned below:
/* class works for table row */
table tr.page-break{
page-break-after:always
}
<tr class="page-break">
/* class works for table */
table.page-break{
page-break-after:always
}
<table class="page-break">
and it will work as you required
Alternatively, you can also have div
structure for same:
CSS:
@media all {
.page-break { display: none; }
}
@media print {
.page-break { display: block; page-break-before: always; }
}
Div:
<div class="page-break"></div>
The most compact version:
<input type="submit" onclick="return confirm('Are you sure?')" />
The key thing to note is the return
-
Because there are many ways to skin a cat, here is another alternate method:
HTML:
<input type="submit" onclick="clicked(event)" />
Javascript:
<script>
function clicked(e)
{
if(!confirm('Are you sure?')) {
e.preventDefault();
}
}
</script>
1 to 10:
[0-9]{1,10}
In .NET (and not only, see the comment below) also valid (with a stipulation) this:
\d{1,10}
C#:
var regex = new Regex("^[0-9]{1,10}$", RegexOptions.Compiled);
regex.IsMatch("1"); // true
regex.IsMatch("12"); // true
..
regex.IsMatch("1234567890"); // true
regex.IsMatch(""); // false
regex.IsMatch(" "); // true
regex.IsMatch("a"); // false
P.S. Here's a very useful sandbox.
Instead of this:
String char = name.substring(0,1); //char="a"
You should use the charAt()
method.
char c = name.charAt(0); // c='a'
int ascii = (int)c;
Generally, I'd prefer not using GoTo for bad readability. To me, it's a bad excuse for programming simple iterative functions instead of having to program recursive functions, or even better (if things like a Stack Overflow is feared), their true iterative alternatives (which may sometimes be complex).
Something like this would do:
while(true) {
alert("RINSE");
alert("LATHER");
}
That right there is an infinite loop. The expression ("true") inside the parantheses of the while clause is what the Javascript engine will check for - and if the expression is true, it'll keep the loop running. Writing "true" here always evaluates to true, hence an infinite loop.
On my Ubuntu machine, I can see the output at /var/log/syslog
.
On a RHEL/CentOS machine, the output is found in /var/log/messages
.
This is controlled by the rsyslog
service, so if this is disabled for some reason you may need to start it with systemctl start rsyslog
.
As noted by others, your syslog()
output would be logged by the /var/log/syslog
file.
You can see system, user, and other logs at /var/log
.
For more details: here's an interesting link.
When we use crontab
or the deprecated /etc/rc.local
file, we need a delay (e.g. sleep 10
, depending on the machine) to make sure that system services are available. Usually, systemd
(or upstart
) is used to manage which services start when the system boots. You can try use the similar configuration for this:
# /etc/systemd/system/docker-compose-app.service
[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service
[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up -d
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0
[Install]
WantedBy=multi-user.target
Or, if you want run without the -d
flag:
# /etc/systemd/system/docker-compose-app.service
[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service
[Service]
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0
Restart=on-failure
StartLimitIntervalSec=60
StartLimitBurst=3
[Install]
WantedBy=multi-user.target
Change the WorkingDirectory
parameter with your dockerized project path. And enable the service to start automatically:
systemctl enable docker-compose-app
PriceList[0]
is a float. PriceList[0][1]
is trying to access the first element of a float. Instead, do
PriceList[0] = PriceList[1] = ...code omitted... = PriceList[6] = PizzaChange
or
PriceList[0:7] = [PizzaChange]*7
The problem is that your anonymous object property data-icon
has an invalid name. C# properties cannot have dashes in their names. There are two ways you can get around that:
Use an underscore instead of dash (MVC will automatically replace the underscore with a dash in the emitted HTML):
@Html.ActionLink("Edit", "edit", "markets",
new { id = 1 },
new {@class="ui-btn-right", data_icon="gear"})
Use the overload that takes in a dictionary:
@Html.ActionLink("Edit", "edit", "markets",
new { id = 1 },
new Dictionary<string, object> { { "class", "ui-btn-right" }, { "data-icon", "gear" } });
The only problem with JSON in Java is that if your XML has a single child, but is an array, it will convert it to an object instead of an array. This can cause problems if you dynamically always convert from XML to JSON, where if your example XML has only one element, you return an object, but if it has 2+, you return an array, which can cause parsing issues for people using the JSON.
Infoscoop's XML2JSON class has a way of tagging elements that are arrays before doing the conversion, so that arrays can be properly mapped, even if there is only one child in the XML.
Here is an example of using it (in a slightly different language, but you can also see how arrays is used from the nodelist2json() method of the XML2JSON link).
You should use "Microsoft OLE DB Provider for ODBC Drivers" to get to access to Microsoft Access. Here is the sample tutorial on using it
http://msdn.microsoft.com/en-us/library/aa288452(v=vs.71).aspx
As of Alpha 6 you can create the following sass file:
@each $breakpoint in map-keys($grid-breakpoints) {
$infix: breakpoint-infix($breakpoint, $grid-breakpoints);
col, td, th {
@for $i from 1 through $grid-columns {
&.col#{$infix}-#{$i} {
flex: none;
position: initial;
}
}
@include media-breakpoint-up($breakpoint, $grid-breakpoints) {
@for $i from 1 through $grid-columns {
&.col#{$infix}-#{$i} {
width: 100% / $grid-columns * $i;
}
}
}
}
}
From here: http://docs.oracle.com/javase/tutorial/information/glossary.html
field
property
attribute
variable
You need to use the Disposable Pattern like this:
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Dispose any managed objects
// ...
}
// Now disposed of any unmanaged objects
// ...
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Destructor
~YourClassName()
{
Dispose(false);
}
You can find out the option for changing browser in Window menu
.
See image at below.
This image can be easy to understand.
To check if a string does not contain any whitespaces, you can use
string.matches("^\\S*$")
Example:
"name" -> true
" " -> false
"name xxname" -> false
From Android R, this method always returns false. Google says that this is done "to protect goat privacy":
/**
* Used to determine whether the user making this call is subject to
* teleportations.
*
* <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
* now automatically identify goats using advanced goat recognition technology.</p>
*
* <p>As of {@link android.os.Build.VERSION_CODES#R}, this method always returns
* {@code false} in order to protect goat privacy.</p>
*
* @return Returns whether the user making this call is a goat.
*/
public boolean isUserAGoat() {
if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.R) {
return false;
}
return mContext.getPackageManager()
.isPackageAvailable("com.coffeestainstudios.goatsimulator");
}
From their source, the method used to return false
until it was changed in API 21.
/**
* Used to determine whether the user making this call is subject to
* teleportations.
* @return whether the user making this call is a goat
*/
public boolean isUserAGoat() {
return false;
}
It looks like the method has no real use for us as developers. Someone has previously stated that it might be an Easter egg.
In API 21 the implementation was changed to check if there is an installed app with the package com.coffeestainstudios.goatsimulator
/**
* Used to determine whether the user making this call is subject to
* teleportations.
*
* <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
* now automatically identify goats using advanced goat recognition technology.</p>
*
* @return Returns true if the user making this call is a goat.
*/
public boolean isUserAGoat() {
return mContext.getPackageManager()
.isPackageAvailable("com.coffeestainstudios.goatsimulator");
}
Mysql has this handy UPDATE INTO command ;)
edit Looks like they renamed it to REPLACE
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted
So I liked @Ask Clarke answer with little improvement by adding try catch block for dates which cannot go through var d = new Date(d) -
function checkIfDateNotValid(d) {
try{
var d = new Date(d);
return !(d.getTime() === d.getTime()); //NAN is the only type which is not equal to itself.
}catch (e){
return true;
}
}
this is very easy way to do this without any Library: if the OS version is not supported - under kitkat - so nothing happend. i do this steps:
<View android:id="@+id/statusBarBackground" android:layout_width="match_parent" android:layout_height="wrap_content" />
then i made this method:
public void setStatusBarColor(View statusBar,int color){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//status bar height
int actionBarHeight = getActionBarHeight();
int statusBarHeight = getStatusBarHeight();
//action bar height
statusBar.getLayoutParams().height = actionBarHeight + statusBarHeight;
statusBar.setBackgroundColor(color);
}
}
also you need those both methods to get action Bar & status bar height:
public int getActionBarHeight() {
int actionBarHeight = 0;
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
return actionBarHeight;
}
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
then the only thing you need is this line to set status bar color:
setStatusBarColor(findViewById(R.id.statusBarBackground),getResources().getColor(android.R.color.white));
Like this:
string str= test[0]+test[1];
You can also use a loop:
for(int i=0; i<2; i++)
str += test[i];
When just a single result is needed, then no loop should be used. Just fetch the row right away.
In case you need to fetch the entire row into associative array:
$row = $result->fetch_assoc();
in case you need just a single value
$row = $result->fetch_row();
$value = $row[0] ?? false;
The last example will return the first column from the first returned row, or false
if no row was returned. It can be also shortened to a single line,
$value = $result->fetch_row()[0] ?? false;
Below are complete examples for different use cases
When variables are to be used in the query, then a prepared statement must be used. For example, given we have a variable $id
:
$query = "SELECT ssfullname, ssemail FROM userss WHERE ud=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute()
$result = $stmt->get_result();
$row = $result->fetch_assoc();
// in case you need just a single value
$query = "SELECT count(*) FROM userss WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute()
$result = $stmt->get_result();
$value = $result->fetch_row()[0] ?? false;
The detailed explanation of the above process can be found in my article. As to why you must follow it is explained in this famous question
In your case, where no variables to be used in the query, you can use the query()
method:
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = $conn->query($query);
// in case you need an array
$row = $result->fetch_assoc();
// OR in case you need just a single value
$value = $result->fetch_row()[0] ?? false;
By the way, although using raw API while learning is okay, consider using some database abstraction library or at least a helper function in the future:
// using a helper function
$sql = "SELECT email FROM users WHERE id=?";
$value = prepared_select($conn, $sql, [$id])->fetch_row[0] ?? false;
// using a database helper class
$email = $db->getCol("SELECT email FROM users WHERE id=?", [$id]);
As you can see, although a helper function can reduce the amount of code, a class' method could encapsulate all the repetitive code inside, making you to write only meaningful parts - the query, the input parameters and the desired result format (in the form of the method's name).
You have to print it:
In [22]: "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
Out[22]: 'I\nwould\nexpect\nmultiple\nlines'
In [23]: print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines
@Injectable({
providedIn: 'root'
})
constructor(public comp2 : component2) { }
method1()
{
this.comp2.method2();
}
component 1 and component 2 code below.
import {Component2} from './Component2';
@Component({
selector: 'sel-comp1',
templateUrl: './comp1.html',
styleUrls: ['./comp1.scss']
})
export class Component1 implements OnInit {
show = false;
constructor(public comp2: Component2) { }
method1()
{
this.comp2.method2();
}
}
@Component({
selector: 'sel-comp2',
templateUrl: './comp2.html',
styleUrls: ['./comp2.scss']
})
export class Component2 implements OnInit {
method2()
{
alert('called comp2 method from comp1');
}
You can use like this:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public EventMessage<ModificaOperativitaRapporto> activate(EventMessage<ModificaOperativitaRapporto> eventMessage) {
//here some transaction related code
}
You can use this thing also:
public interface TransactionStatus extends SavepointManager {
boolean isNewTransaction();
boolean hasSavepoint();
void setRollbackOnly();
boolean isRollbackOnly();
void flush();
boolean isCompleted();
}
Following is the method I found:
1) Make a list of files with relative paths in a file (say FilesList.txt) as follows (either space separated or line separated):
foo/AccessTestInterface.java
foo/goo/AccessTestInterfaceImpl.java
2) Use the command:
javac @FilesList.txt -d classes
This will compile all the files and put the class files inside classes directory.
Now easy way to create FilesList.txt is this: Go to your source root directory.
dir *.java /s /b > FilesList.txt
But, this will populate absolute path. Using a text editor "Replace All" the path up to source directory (include \ in the end) with "" (i.e. empty string) and Save.
Here you go, Python documentation on old string formatting. tutorial -> 7.1.1. Old String Formatting -> "More information can be found in the [link] section".
Note that you should start using the new string formatting when possible.
Single line command ,this worked for me
explorer .\
In the older versions it would default to the console subsystem even if you selected "empty project", but not in 2010, so you have to set it manually. To do this select the project in the solution explorer on the right or left (probably is already selected so you don't have to worry about this). Then select "project" from the menu bar drop down menus, then select "project_name properties" > "configuration properties" > "linker" > "system" and set the first property, the drop down "subsystem" property to "console (/SUBSYSTEM:CONSOLE)". The console window should now stay open after execution as usual.
I only see one color being specified (albeit you specify it in two different places.) Either you've omitted some of your style rules, or you simply didn't specify another color.
whatever you all do, the best way is to take the short_name for the specified language, i.e.: fr, en, nl, de, it, etc... and assign the same to a global value.
make a picker view to pop up like a drop down menu (combination of a button on click of which a picker view appears from below with a list of languages) and select the language you desire. let the short name be stored internally. make a .h + .m file named LocalisedString.
Set the global value of short_name to be equal to the obtained value in LocalisedString.m When the required language is selected assign the NSBundlePath to create project sub-directories for the needed language. for eg, nl.proj, en.proj.
When the particular proj folder is selected call the localised string for the respective language and change the language dynamically.
no rules broken.
For Oracle, John's solution using instr() function works. Here's slightly different solution that worked -
SELECT id
FROM table1
WHERE id IN (1, 20, 45, 60)
ORDER BY instr('1, 20, 45, 60', id)
apt-get install python2.7
will work on debian-like linuxes. The python website describes a whole bunch of other ways to get Python.
Very Commonly Used top 3 ones are
1. window.location.hostname
2. window.location.href
3. window.location.pathname
You want to use pack
and base_convert
.
// Convert a string into binary
// Should output: 0101001101110100011000010110001101101011
$value = unpack('H*', "Stack");
echo base_convert($value[1], 16, 2);
// Convert binary into a string
// Should output: Stack
echo pack('H*', base_convert('0101001101110100011000010110001101101011', 2, 16));
{{p.User['first_name'] or 'My default string'}}
Another alternative is to express the comment as a variable expansion that always expands to nothing.
Variable names cannot contain =
, except for undocumented dynamic variables like
%=ExitCode%
and %=C:%
. No variable name can ever contain an =
after the 1st position. So I sometimes use the following to include comments within a parenthesized block:
::This comment hack is not always safe within parentheses.
(
%= This comment hack is always safe, even within parentheses =%
)
It is also a good method for incorporating in-line comments
dir junk >nul 2>&1 && %= If found =% echo found || %= else =% echo not found
The leading =
is not necessary, but I like if for the symmetry.
There are two restrictions:
1) the comment cannot contain %
2) the comment cannot contain :
Spring MVC
is a sub-project of the Spring Framework, targeting design and development of applications that use the MVC (Model-View-Controller) pattern. Spring MVC is designed to integrate fully and completely with the Spring Framework and transitively, most other sub-projects.
Spring Boot
can be understood quite well from this article by the Spring Engineering team. It is supposedly opinionated, i.e. it heavily advocates a certain style of rapid development, but it is designed well enough to accommodate exceptions to the rule, if you will. In short, it is a convention over configuration methodology that is willing to understand your need to break convention when warranted.
Change /img/stuvi-logo.png
to img/stuvi-logo.png
{{ HTML::image('img/stuvi-logo.png', 'alt text', array('class' => 'css-class')) }}
Which produces the following HTML.
<img src="http://your.url/img/stuvi-logo.png" class="css-class" alt="alt text">
I would avoid inline javascript altogether, and as I mentioned in my comment, I'd also probably use <input type="button" />
for this. That being said...
<a href="http://stackoverflow.com/questions/16337937/how-to-call-javascript-from-a-href" id="mylink">Link.</a>
var clickHandler = function() {
alert('Stuff happens now.');
}
if (document.addEventListener) {
document.getElementById('mylink').addEventListener('click', clickHandler, false);
} else {
document.getElementById('mylink').attachEvent('click', clickHandler);
}
Null is ALWAYS an unknown object that exists in memory, whereas undefined is not.
Having had a similar problem with data from 1800 to now, this worked for me:
data2$date=as.character(data2$date)
lct <- Sys.getlocale("LC_TIME");
Sys.setlocale("LC_TIME","C")
data2$date<- as.Date(data2$date, format = "%Y %m %d") # and it works
If your application is already using Apache Commons lib, you can slightly modify the accepted answer to not create a new empty array each time:
List<String> list = ..;
String[] array = list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
// or if using static import
String[] array = list.toArray(EMPTY_STRING_ARRAY);
There are a few more preallocated empty arrays of different types in ArrayUtils
.
Also we can trick JVM to create en empty array for us this way:
String[] array = list.toArray(ArrayUtils.toArray());
// or if using static import
String[] array = list.toArray(toArray());
But there's really no advantage this way, just a matter of taste, IMO.
Set your css in the table cell to
white-space:pre-wrap;
document.body.innerHTML = 'First line\nSecond line\nThird line';
_x000D_
body{ white-space:pre-wrap; }
_x000D_
I believe the sprintf is the right function for you. I's in the standard library, like printf. Follow the link below for more information:
You can perform bulk insert using mongoose, as the highest score answer. But the example cannot work, it should be:
/* a humongous amount of potatos */
var potatoBag = [{name:'potato1'}, {name:'potato2'}];
var Potato = mongoose.model('Potato', PotatoSchema);
Potato.collection.insert(potatoBag, onInsert);
function onInsert(err, docs) {
if (err) {
// TODO: handle error
} else {
console.info('%d potatoes were successfully stored.', docs.length);
}
}
Don't use a schema instance for the bulk insert, you should use a plain map object.
Since your JPA repository name is UserBoardRepository, your custom Interface name should be UserBoardRepositoryCustom (it should end with 'Custom') and your implementation class name should be UserBoardRepositoryImpl (should end with Impl; you can set it with a different postfix using the repository-impl-postfix property)
The find library is designed for this task specifically: https://ruby-doc.org/stdlib-2.5.1/libdoc/find/rdoc/Find.html
require 'find'
Find.find(path) do |file|
# process
end
This is a standard ruby library, so it should be available
To fix your issue, i have made few changes in bla.js and it is working,
var foo= function (req, res, next) {
console.log('inside foo');
return ("foo");
}
var bar= function(req, res, next) {
this.foo();
}
module.exports = {bar,foo};
and no modification in app.js
var bla = require('./bla.js');
console.log(bla.bar());
<?php
if (isset($_POST['add'])) {
$nama = $_POST['name'];
$subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";
echo "Name: {$nama} <br />";
echo "Subscribe: {$subscribe}";
echo "<hr />";
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >
<input type="text" name="name" /> <br />
<input type="checkbox" name="subscribe" value="news" /> News <br />
<input type="submit" name="add" value="Save" />
</form>
First create a new directory:
!mkdir file_destination
Now, it's the time to inflate the directory with the unzipped files with this:
!unzip file_location -d file_destination
If you are using the background image for the rounded corners then I would rather increase the padding style of the main div to give enough room for the rounded corners of the background image to be visible.
Try increasing the padding of the main div style:
#mainWrapperDivWithBGImage
{
background: url("myImageWithRoundedCorners.jpg") no-repeat scroll 0 0 transparent;
height: 248px;
margin: 0;
overflow: hidden;
padding: 10px 10px;
width: 996px;
}
P.S: I assume the rounded corners have a radius of 10px.
Late to the game but here a handy little category I use that accounts for decimal places and the local symbol used for it. link to its gist here
@interface NSString (Extension)
- (BOOL) isAnEmail;
- (BOOL) isNumeric;
@end
@implementation NSString (Extension)
/**
* Determines if the current string is a valid email address.
*
* @return BOOL - True if the string is a valid email address.
*/
- (BOOL) isAnEmail
{
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:self];
}
/**
* Determines if the current NSString is numeric or not. It also accounts for the localised (Germany for example use "," instead of ".") decimal point and includes these as a valid number.
*
* @return BOOL - True if the string is numeric.
*/
- (BOOL) isNumeric
{
NSString *localDecimalSymbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
NSMutableCharacterSet *decimalCharacterSet = [NSMutableCharacterSet characterSetWithCharactersInString:localDecimalSymbol];
[decimalCharacterSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
NSCharacterSet* nonNumbers = [decimalCharacterSet invertedSet];
NSRange r = [self rangeOfCharacterFromSet: nonNumbers];
if (r.location == NSNotFound)
{
// check to see how many times the decimal symbol appears in the string. It should only appear once for the number to be numeric.
int numberOfOccurances = [[self componentsSeparatedByString:localDecimalSymbol] count]-1;
return (numberOfOccurances > 1) ? NO : YES;
}
else return NO;
}
@end
Your user.jsp:
<form:form action="profile/proffesional" modelAttribute="PROFESSIONAL">
---
---
</form:form>
In your controller class:
(make it as a meaning full method name..Hear i think you are insert record in DB.)
@RequestMapping(value = "proffessional", method = RequestMethod.POST)
public @ResponseBody
String proffessionalDetails(
@ModelAttribute UserProfessionalForm professionalForm,
BindingResult result, Model model) {
UserProfileVO userProfileVO = new UserProfileVO();
userProfileVO.setUser(sessionData.getUser());
userService.saveUserProfile(userProfileVO);
model.addAttribute("PROFESSIONAL", professionalForm);
return "Your Professional Details Updated";
}
I had a problem because my canvas was inside of a container without ID so I used this jquery code below
$('.cropArea canvas').width()
You've probably tried this, but are your specifications such that you can do this?
DECLARE @city varchar(75)
DECLARE @count INT
SET @city = 'London'
SELECT @count = COUNT(*) FROM customers WHERE City = @city
You can create an interface
, pass it to AsyncTask
(in constructor), and then call method in onPostExecute()
For example:
Your interface:
public interface OnTaskCompleted{
void onTaskCompleted();
}
Your Activity:
public class YourActivity implements OnTaskCompleted{
// your Activity
}
And your AsyncTask:
public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
private OnTaskCompleted listener;
public YourTask(OnTaskCompleted listener){
this.listener=listener;
}
// required methods
protected void onPostExecute(Object o){
// your stuff
listener.onTaskCompleted();
}
}
EDIT
Since this answer got quite popular, I want to add some things.
If you're a new to Android development, AsyncTask
is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:
Activity
, it will stay in memory even after user left the screen (or rotated the device).AsyncTask
is not delivering result to Activity
if Activity
was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.Activity
When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.
This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.
This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.
public class HexColor
{
public static void main (String[] args)
{
JSlider sRed = new JSlider(0,255,1);
JSlider sGreen = new JSlider(0,255,1);
JSlider sBlue = new JSlider(0,255,1);
JLabel hexCode = new JLabel();
JPanel myPanel = new JPanel();
GridBagLayout layout = new GridBagLayout();
JFrame frame = new JFrame();
//set frame to organize components using GridBagLayout
frame.setLayout(layout);
//create gray filled rectangle
myPanel.paintComponent();
myPanel.setBackground(Color.GRAY);
//In practice this code is replicated and applied to sGreen and sBlue.
//For the sake of brevity I only show sRed in this post.
sRed.addChangeListener(
new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e){
myPanel.setBackground(changeColor());
myPanel.repaint();
hexCode.setText(toHex());
}
}
);
//add each component to JFrame
frame.add(myPanel);
frame.add(sRed);
frame.add(sGreen);
frame.add(sBlue);
frame.add(hexCode);
} //end of main
//creates JPanel filled rectangle
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawRect(360, 300, 10, 10);
g.fillRect(360, 300, 10, 10);
}
//changes the display color in JPanel
private Color changeColor()
{
int r = sRed.getValue();
int b = sBlue.getValue();
int g = sGreen.getValue();
Color c;
return c = new Color(r,g,b);
}
//Displays hex representation of displayed color
private String toHex()
{
Integer r = sRed.getValue();
Integer g = sGreen.getValue();
Integer b = sBlue.getValue();
Color hC;
hC = new Color(r,g,b);
String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
while(hex.length() < 6){
hex = "0" + hex;
}
hex = "Hex Code: #" + hex;
return hex;
}
}
A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.
Looks like the approach in @gaborous's answer is deprecated.
The new approach seems to be:
from IPython.core import debugger
debug = debugger.Pdb().set_trace
def buggy_method():
debug()
I had the same problem but mine worked fine. Turn off your firewall, antivirus. Make sure your port 80 is enabled and both pcs are set to be remotely accessed. In each pc under users, add new user using the host ip address of the other pc. Restart all services. Put your wampserver online. It should connect
Just another answer, although it's similar to Supr's one - just a different color space.
The thing is: Humans perceive the difference in color not uniformly and the RGB color space is ignoring this. As a result if you use the RGB color space and just compute the euclidean distance between 2 colors you may get a difference which is mathematically absolutely correct, but wouldn't coincide with what humans would tell you.
This may not be a problem - the difference is not that large I think, but if you want to solve this "better" you should convert your RGB colors into a color space that was specifically designed to avoid the above problem. There are several ones, improvements from earlier models (since this is based on human perception we need to measure the "correct" values based on experimental data). There's the Lab colorspace which I think would be the best although a bit complicated to convert it to. Simpler would be the CIE XYZ one.
Here's a site that lists the formula's to convert between different color spaces so you can experiment a bit.
If you want to return a char*
from a function, make sure you malloc()
it. Stack initialized character arrays make no sense in returning, as accessing them after returning from that function is undefined behavior.
change it to
char* createStr() {
char char1= 'm';
char char2= 'y';
char *str = malloc(3 * sizeof(char));
if(str == NULL) return NULL;
str[0] = char1;
str[1] = char2;
str[2] = '\0';
return str;
}
I was getting the same error of fsocket() and I just updated my hosts files
hope it will solve your problem
for any further query please ping me at http://kingologic.com
You need to use the TO_DATE
function.
SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;
{
test_str1 = ""
test_str2 = " "
# checking if string is empty
print ("The zero length string without spaces is empty ? : ", end = "")
if(len(test_str1) == 0):
print ("Yes")
else :
print ("No")
# prints No
print ("The zero length string with just spaces is empty ? : ", end = "")
if(len(test_str2) == 0):
print ("Yes")
else :
print ("No")
}
You can use \= in an substitution string and is something I do every so often.
If you have what's essentially an unordered list in vim, say using # as a marker, you can convert it over to an ordered list.
# CSSLINT
# PHPCS
# Charlie
# Delta
If it starts on line one, you can do
:1,6s/#/\=line(".")/g
To convert it over to
1 CSSLINT
2 PHPCS
3 Charlie
4 Delta
If it doesn't start on line one, just do the maths:
:16,20s/#/\=line(".") - 15/g
More info at :help sub-replace-expression
If you are using reflection, you can get the Method object and then:
method.getDeclaringClass().getName()
To get the Method itself, you can probably use:
Class<?> c = Class.forName("class name");
Method method = c.getDeclaredMethod ("method name", parameterTypes)
I know this is old, but I ran into the same issue. I'm on a Mac/Ubuntu and switch back and forth. What I have found is that just sending a simple interrupt signal to the main R process does exactly what you're looking for. I've ran scripts that went on for as long as 24 hours and the signal interrupt works very well. You should be able to run kill in terminal:
$ kill -2 pid
You can find the pid by running
$ps aux | grep exec/R
Not sure about Windows since I'm not ever on there, but I can't imagine there's not an option to do this as well in Command Prompt/Task Manager
Hope this helps!
Hope this coding will helps you :)
plot(x,y,xaxt = 'n')
axis(side=1,at=c(1,20,30,50),labels=c("1975","1980","1985","1990"))
Your 100% means 100% of the viewport, you can fix that using the vw unit besides the % unit at the width. The problem is that 100vw is related to the viewport, besides % is related to parent tag. Do like that:
.table-cell-wrapper {
width: 100vw;
height: 100%;
display: table-cell;
vertical-align: middle;
text-align: center;
}
This is my summary of the above and works perfectly for me. Thanks for the info!
<script language='javascript' type='text/javascript'>
$(document).ready(function () {
var firstInput = $('form').find('input[type=text],input[type=password],input[type=radio],input[type=checkbox],textarea,select').filter(':visible:first');
if (firstInput != null) {
firstInput.focus();
}
});
</script>
As documented in ?legend
you do this like so:
plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)
Line breaks are achieved with the new line character \n
. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.
Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).
If you want draw and not freeze your thread as more point are drawn you should use plt.pause() not time.sleep()
im using the following code to plot a series of xy coordinates.
import matplotlib.pyplot as plt
import math
pi = 3.14159
fig, ax = plt.subplots()
x = []
y = []
def PointsInCircum(r,n=20):
circle = [(math.cos(2*pi/n*x)*r,math.sin(2*pi/n*x)*r) for x in xrange(0,n+1)]
return circle
circle_list = PointsInCircum(3, 50)
for t in range(len(circle_list)):
if t == 0:
points, = ax.plot(x, y, marker='o', linestyle='--')
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
else:
x_coord, y_coord = circle_list.pop()
x.append(x_coord)
y.append(y_coord)
points.set_data(x, y)
plt.pause(0.01)
This is using dataframes from the pandas
package. The "index" part can be either a single index, a list of indices, or a list of booleans. This can be read about in the documentation: https://pandas.pydata.org/pandas-docs/stable/indexing.html
So the index
part specifies a subset of the rows to pull out, and the (optional) column_name
specifies the column you want to work with from that subset of the dataframe. So if you want to update the 'class' column but only in rows where the class is currently set as 'versicolor', you might do something like what you list in the question:
iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
To match anything other than letter or number you could try this:
[^a-zA-Z0-9]
And to replace:
var str = 'dfj,dsf7lfsd .sdklfj';
str = str.replace(/[^A-Za-z0-9]/g, ' ');
Worth noting that the code you see is sent to the database as is, the queries are sent separately to prevent SQL injection. AFAIK The ? marks are placeholders that are replaced by the number params by the database, not by hibernate.
Also, note that there shouldn't be any space after =
:
set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_27
Change your selector to
val = j$("#select_2 option:selected").text();
You're selecting the <select>
instead of the <option>
The Material icons use the Material icon font, and the font needs to be included with the page.
Here's the CDN from Google Web Fonts:
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
str could be a number or a string.
formatting("hi",3);
function formatting(str,len)
{
return ("000000"+str).slice(-len);
}
Add more zeros if needs large digits
If your Pycharm 2016.1.4v and higher you should use
"default path" /K "<path-to-your-activate.bat>"
don't forget quotes
I arrived at this peculiar, hard-to-debug error through a different route. My trouble ended up being that I was using a pattern rule in a build step when the target and the dependency were located in distinct directories. Something like this:
foo/apple.o: bar/apple.c $(FOODEPS)
%.o: %.c
$(CC) $< -o $@
I had several dependencies set up this way, and was trying to use one pattern recipe for them all. Clearly, a single substitution for "%" isn't going to work here. I made explicit rules for each dependency, and I found myself back among the puppies and unicorns!
foo/apple.o: bar/apple.c $(FOODEPS)
$(CC) $< -o $@
Hope this helps someone!
From the Android Developers page,
onPause():
Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.
onStop():
Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed. Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.
Now suppose there are three Activities and you go from A to B, then onPause of A will be called now from B to C, then onPause of B and onStop of A will be called.
The paused Activity gets a Resume and Stopped gets Restarted.
When you call this.finish()
, onPause-onStop-onDestroy will be called. The main thing to remember is: paused Activities get Stopped and a Stopped activity gets Destroyed whenever Android requires memory for other operations.
I hope it's clear enough.
If you are using getActivity() then you have to make sure that the calling activity is added already. If activity has not been added in such case so you may get null when you call getActivity()
in such cases getContext() is safe
then the code for starting the activity will be slightly changed like,
Intent intent = new Intent(getContext(), mFragmentFavorite.class);
startActivity(intent);
Activity, Service and Application extends ContextWrapper class so you can use this or getContext() or getApplicationContext() in the place of first argument.
Structs are the actual value - they can be empty but never null
This is true, however also note that as of .NET 2 structs support a Nullable version and C# supplies some syntactic sugar to make it easier to use.
int? value = null;
value = 1;
Follow this https://developers.google.com/youtube/player_parameters for more info about video controls like:
<iframe id="video_iframe" width="660" height="415" src="http://www.youtube.com/v/{{course_url}}?start=7&autoplay=0&showinfo=0&iv_load_policy=3&rel=0"
frameborder="0"
allowfullscreen></iframe>
start=7&autoplay=0&showinfo=0&iv_load_policy=3&rel=0"
frameborder="0"
all controls are described in there
You want to convert it to an object first and then access normally making sure to cast it.
JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];
It looks like your string is encoded to utf-8
, so what exactly is the problem? Or what are you trying to do here..?
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
(?????)?
>>> s2 = u'(?????)?'
>>> s2 == s1
True
>>> s2
u'(\uff61\uff65\u03c9\uff65\uff61)\uff89'
I am just going to repeat it, because it is quite important:
Always validate on the server
and add JavaScript for user-responsiveness.
Not 100% sure what you mean:
Trusted_Connection=True;
IS using Windows credentials and is 100% equivalent to:
Integrated Security=SSPI;
or
Integrated Security=true;
If you don't want to use integrated security / trusted connection, you need to specify user id and password explicitly in the connection string (and leave out any reference to Trusted_Connection
or Integrated Security
)
server=yourservername;database=yourdatabase;user id=YourUser;pwd=TopSecret
Only in this case, the SQL Server authentication mode is used.
If any of these two settings is present (Trusted_Connection=true
or Integrated Security=true/SSPI
), then the Windows credentials of the current user are used to authenticate against SQL Server and any user iD=
setting will be ignored and not used.
For reference, see the Connection Strings site for SQL Server 2005 with lots of samples and explanations.
Using Windows Authentication is the preferred and recommended way of doing things, but it might incur a slight delay since SQL Server would have to authenticate your credentials against Active Directory (typically). I have no idea how much that slight delay might be, and I haven't found any references for that.
Summing up:
If you specify either Trusted_Connection=True;
or Integrated Security=SSPI;
or Integrated Security=true;
in your connection string
==> THEN (and only then) you have Windows Authentication happening. Any user id=
setting in the connection string will be ignored.
If you DO NOT specify either of those settings,
==> then you DO NOT have Windows Authentication happening (SQL Authentication mode will be used)
For what is worth:
the closest integer to any given input as shown in the following table can be calculated using Math.ceil or Math.floor depending of the distance between the input and the next integer
+-------+--------+
| input | output |
+-------+--------+
| 1 | 0 |
| 2 | 0 |
| 3 | 5 |
| 4 | 5 |
| 5 | 5 |
| 6 | 5 |
| 7 | 5 |
| 8 | 10 |
| 9 | 10 |
+-------+--------+
private int roundClosest(final int i, final int k) {
int deic = (i % k);
if (deic <= (k / 2.0)) {
return (int) (Math.floor(i / (double) k) * k);
} else {
return (int) (Math.ceil(i / (double) k) * k);
}
}
You can always do
('0' + deg).slice(-2)
If you use it very often, you may extend the object Number
Number.prototype.pad = function(n) {
if (n==undefined)
n = 2;
return (new Array(n).join('0') + this).slice(-n);
}
deg.pad(4) // "0045"
where you can set any pad size or leave the default 2.
To build on the previous answer if you add -f
you can tail the logs.
kubectl logs -f deployment/app
Don't use jquery...use plain javascript
var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var b = a.splice(0,10);
//a is now [11,12,13,14,15];
//b is now [1,2,3,4,5,6,7,8,9,10];
You could loop this to get the behavior you want.
var a = YOUR_ARRAY;
while(a.length) {
console.log(a.splice(0,10));
}
This would give you 10 elements at a time...if you have say 15 elements, you would get 1-10, the 11-15 as you wanted.
Use below command to change computer hostname remotely , Require system reboot after change..
psexec.exe -h -e \\\IPADDRESS -u USERNAME -p PASSWORD netdom renamecomputer CurrentComputerName /newname:NewComputerName /force
The css clear: left
in your adm class should stop the div floating with the elements above it.
My guess is that you simply need to URL-encode your Base64 string when you include it in the querystring.
Base64 encoding uses some characters which must be encoded if they're part of a querystring (namely +
and /
, and maybe =
too). If the string isn't correctly encoded then you won't be able to decode it successfully at the other end, hence the errors.
You can use the HttpUtility.UrlEncode
method to encode your Base64 string:
string msg = "Please click on the link below or paste it into a browser "
+ "to verify your email account.<br /><br /><a href=\""
+ _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
+ HttpUtility.UrlEncode(userName.Encrypt("verify")) + "\">"
+ _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
+ HttpUtility.UrlEncode(userName.Encrypt("verify")) + "</a>";
The bandwidth of a link is the theoretical maximum amount of data that could be sent over that channel without regard to practical considerations. For example, you could pump 10^9 bits per second down a Gigabit Ethernet link over a Cat-6e or fiber optic cable. Unfortunately this would be a completely unformatted stream of bits.
To make it actually useful there's a start of frame sequence which precedes any actual data bits, a frame check sequence at the end for error detection and an idle period between transmitted frames. All of those occupy what is referred to as "bit times" meaning the amount of time it takes to transmit one bit over the line. This is all necessary overhead, but is subtracted from the total bandwidth of the link.
And this is only for the lowest level protocol which is stuffing raw data out onto the wire. Once you start adding in the MAC addresses, an IP header and a TCP or UDP header, then you've added even more overhead.
Check out http://en.wikipedia.org/wiki/Ethernet_frame. Similar problems exist for other transmission media.
Following @Francisco Goldenstein answer, I wrote an extension method
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Mediatel.Framework
{
public static class XDocumentHelper
{
public static IEnumerable<XElement> DescendantElements(this XDocument xDocument, string nodeName)
{
return xDocument.Descendants().Where(p => p.Name.LocalName == nodeName);
}
}
}
Cool @derek-kromm, Your answer is accepted and correct, But I am wondering if we need to alter
more than the column. Here is how we can do.
ALTER TABLE tbl_name
ALTER COLUMN col_name TYPE varchar (11),
ALTER COLUMN col_name2 TYPE varchar (11),
ALTER COLUMN col_name3 TYPE varchar (11);
Cheers!! Read Simple Write Simple
function FastScrollUp()
{
window.scroll(0,0)
};
function FastScrollDown()
{
$i = document.documentElement.scrollHeight ;
window.scroll(0,$i)
};
var step = 20;
var h,t;
var y = 0;
function SmoothScrollUp()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, -step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollUp()},20);
};
function SmoothScrollDown()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollDown()},20);
}
I think this is the shortest regular expression that does it:
/\B(?=(\d{3})+\b)/g
"123456".replace(/\B(?=(\d{3})+\b)/g, ",")
I checked it on a few numbers and it worked.
In the DRF version 3.6.3 this worked for me
class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.CharField(source='category.name')
class Meta:
model = Item
fields = ('id', 'name', 'category_name')
More info can be found here: Serializer Fields core arguments
I spent many hours spent tearing out my hair over this. The build output wasn't consistent; different projects would be "not up to date" for different reasons from one build to the next consecutive build. I eventually found that the culprit was DropBox (3.0.4). I junction my source folder from ...\DropBox into my projects folder (not sure if this is the reason), but DropBox somehow "touches" files during a build. Paused syncing and everything is consistently up-to-date.
$myTimezone = date_default_timezone_get();
date_default_timezone_set($userTimezone);
$userDay = date('l', $userTimestamp);
date_default_timezone_set($myTimezone);
This should work (didn't test it, so YMMV). It works by storing the script's current timezone, changing it to the one specified by the user, getting the day of the week from the date()
function at the specified timestamp, and then setting the script's timezone back to what it was to begin with.
You might have some adventures with timezone identifiers, though.
EDIT these lines in host file and it should work.
Host file usually located in C:\Windows\System32\drivers\etc\hosts
::1 localhost.localdomain localhost
127.0.0.1 localhost
USE style="max-width:90%;"
<select name=countries style="max-width:90%;">
<option value=af>Afghanistan</option>
<option value=ax>Åland Islands</option>
...
<option value=gs>South Georgia and the South Sandwich Islands</option>
...
</select>
For me, restarting Docker Desktop did not help. Shutting down Win10 and start it again, it did help.
let concurrentQueue = dispatch_queue_create("com.swift3.imageQueue", DISPATCH_QUEUE_CONCURRENT) //Swift 2 version
let concurrentQueue = DispatchQueue(label:"com.swift3.imageQueue", attributes: .concurrent) //Swift 3 version
I re-worked your code in Xcode 8, Swift 3 and the changes are marked in contrast to your Swift 2 version.
I tried the answer of @mobistry:
canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
But it doesn't worked for me.
The solution, for me, was:
canvas.drawColor(Color.TRANSPARENT, Mode.MULTIPLY);
Maybe some one has the same problem.
I strongly favour minimal file headers, by which I mean just:
#!
line) if this is an executable script import os # standard library
import sys
import requests # 3rd party packages
from mypackage import ( # local source
mymodule,
myothermodule,
)
ie. three groups of imports, with a single blank line between them. Within each group, imports are sorted. The final group, imports from local source, can either be absolute imports as shown, or explicit relative imports.
Everything else is a waste of time, visual space, and is actively misleading.
If you have legal disclaimers or licencing info, it goes into a separate file. It does not need to infect every source code file. Your copyright should be part of this. People should be able to find it in your LICENSE
file, not random source code.
Metadata such as authorship and dates is already maintained by your source control. There is no need to add a less-detailed, erroneous, and out-of-date version of the same info in the file itself.
I don't believe there is any other data that everyone needs to put into all their source files. You may have some particular requirement to do so, but such things apply, by definition, only to you. They have no place in “general headers recommended for everyone”.
You can send some flag to stop while loop in server
for example
import socket
s = socket.socket()
s.bind(("localhost", 5000))
s.listen(1)
c,a = s.accept()
filetodown = open("img.png", "wb")
while True:
print("Receiving....")
data = c.recv(1024)
if data == b"DONE":
print("Done Receiving.")
break
filetodown.write(data)
filetodown.close()
c.send("Thank you for connecting.")
c.shutdown(2)
c.close()
s.close()
#Done :)
import socket
s = socket.socket()
s.connect(("localhost", 5000))
filetosend = open("img.png", "rb")
data = filetosend.read(1024)
while data:
print("Sending...")
s.send(data)
data = filetosend.read(1024)
filetosend.close()
s.send(b"DONE")
print("Done Sending.")
print(s.recv(1024))
s.shutdown(2)
s.close()
#Done :)
Solved it in my case with this code using help of this post:
Bitmap myBitmap = getBitmap(imgFile.getAbsolutePath());
try {
ExifInterface exif = new ExifInterface(imgFile.getAbsolutePath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.d("EXIF", "Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
}
else if (orientation == 3) {
matrix.postRotate(180);
}
else if (orientation == 8) {
matrix.postRotate(270);
}
myBitmap = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight(), matrix, true); // rotating bitmap
}
catch (Exception e) {
}
ImageView img = (ImageView) findViewById(R.id.imgTakingPic);
img.setImageBitmap(myBitmap);
Hope it saves someone's time!
You could do the following:
DELETE * FROM table WHERE NOT(id = 2);
It's quite unclear how you are computing the size ("the size in debug mode"?").
Use printf()
:
printf("the size of c is %u\n", (unsigned int) sizeof c);
Normally you'd print a size_t
value (which is the type sizeof
returns) with %zu
, but if you're using a pre-C99 compiler like Visual Studio that won't work.
You need to find the typedef
statements in your code that define the custom names like uint8
and so on; those are not standard so nobody here can know how they're defined in your code.
New C code should use <stdint.h>
which gives you uint8_t
and so on.
Personal understanding, in TensorFlow domain, logits are the values to be used as input to softmax. I came to this understanding based on this tensorflow tutorial.
https://www.tensorflow.org/tutorials/layers
Although it is true that logit is a function in maths(especially in statistics), I don't think that's the same 'logit' you are looking at. In the book Deep Learning by Ian Goodfellow, he mentioned,
The function s-1(x) is called the logit in statistics, but this term is more rarely used in machine learning. s-1(x) stands for the inverse function of logistic sigmoid function.
In TensorFlow, it is frequently seen as the name of last layer. In Chapter 10 of the book Hands-on Machine Learning with Scikit-learn and TensorFLow by Aurélien Géron, I came across this paragraph, which stated logits
layer clearly.
note that
logits
is the output of the neural network before going through the softmax activation function: for optimization reasons, we will handle the softmax computation later.
That is to say, although we use softmax as the activation function in the last layer in our design, for ease of computation, we take out logits
separately. This is because it is more efficient to calculate softmax
and cross-entropy
loss together. Remember that cross-entropy
is a cost function, not used in forward propagation.
Yes, you can always use null
instead of an object. Just be careful because some methods might throw error.
It would be 1.
also null
s would be factored in in the for loop, but you could use
for(Item i : itemList) {
if (i!= null) {
//code here
}
}
No it won't, Java will short-circuit and stop evaluating once it knows the result.
For me, this is the best way.
var arrayOfNums = [1,4,5,68,9,10]
for i in 0..<arrayOfNums.count {
print(arrayOfNums[arrayOfNums.count - i - 1])
}
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
Export should be specific about which version of GCC/G++ to use, because if user had multiple compiler version, it would not compile successfully.
export CC=path_of_gcc/gcc-version
export CXX=path_of_g++/g++-version
cmake path_of_project_contain_CMakeList.txt
make
In case project use C++11 this can be handled by using -std=C++-11
flag in CMakeList.txt
You can find the codes in the DB2 Information Center. Here's a definition of the -302
from the z/OS Information Center:
THE VALUE OF INPUT VARIABLE OR PARAMETER NUMBER position-number IS INVALID OR TOO LARGE FOR THE TARGET COLUMN OR THE TARGET VALUE
On Linux/Unix/Windows DB2, you'll look under SQL Messages to find your error message. If the code is positive, you'll look for SQLxxxxW
, if it's negative, you'll look for SQLxxxxN
, where xxxx is the code you're looking up.
Install git and tortoise git for windows and make sure it is on your path, (the installer for Tortoise Git includes options for the command line tools and ensuring that it is on the path - select them).
You will need to close and re-open any existing command line sessions for the changes to take effect.
Then you should be able to run npm install
successfully or move on to the next problem!
You can create a PrintStream wrapping around your OutputStream and then just call it's print(String):
final OutputStream os = new FileOutputStream("/tmp/out");
final PrintStream printStream = new PrintStream(os);
printStream.print("String");
printStream.close();
I like Tri Q's answer, but those value converters are a pain to use. PaulB did it with an event handler, but that's also unnecessary. Here's a pure XAML solution:
<ContentControl Content="{Binding YourChoices}">
<ContentControl.ContentTemplate>
<DataTemplate>
<Grid>
<ComboBox x:Name="cb" ItemsSource="{Binding}"/>
<TextBlock x:Name="tb" Text="Select Something" IsHitTestVisible="False" Visibility="Hidden"/>
</Grid>
<DataTemplate.Triggers>
<Trigger SourceName="cb" Property="SelectedItem" Value="{x:Null}">
<Setter TargetName="tb" Property="Visibility" Value="Visible"/>
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>
You're adding the event handler to the <select>
element.
Therefore, $(this)
will be the dropdown itself, not the selected <option>
.
You need to find the selected <option>
, like this:
var option = $('option:selected', this).attr('mytag');
I would solve this like that. First, I'd create an instance of your given datetime object. Then, I'd create another datetime object which is 7 days later than the initial one. And finally, I'd format it the way you like.
With meringue library, this is quite intuitive and elegant. Here's the code:
(new Future(
new FromCustomFormat('F j, Y', 'March 3, 2011'),
new NDays(7)
))
->value();
The result is a string in ISO8601 format. If you like, you can format it anyway you like using the same ISO8601 syntax:
(new ISO8601Formatted(
new Future(
new FromCustomFormat('F j, Y', 'March 3, 2011'),
new NDays(7)
),
'F j, Y'
))
->value();
The code above uses meringue library. Here's a quick start, you can take a look if you want.
I had the same problem after a MacOS system upgrade. Solved it by upgrading the postgres with brew. Details: it looks like the system was trying to access Postgres 11 using older Postgres 10 settings. I'm sure it was my mistake somewhere in the past, but luckily it all got sorted out with the upgrade above.
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
I love this answer. However, since next()
raise a StopIteration
exception when there are no items,
i would use the following snippet to avoid an exception:
a = []
item = next((x for x in a), None)
For example,
a = []
item = next(x for x in a)
Will raise a StopIteration
exception;
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
For future seekers who might have dropped simple details like me, in my case I just have forgotten to call my action function with parentheses.
actions.js:
export function addNewComponent() {
return {
type: ADD_NEW_COMPONENT,
};
}
myComponent.js:
import React, { useEffect } from 'react';
import { addNewComponent } from '../../redux/actions';
useEffect(() => {
dispatch(refreshAllComponents); // <= Here was what I've missed.
}, []);
I've forgotten to dispatch the action function with ()
. So doing this solved my issue.
useEffect(() => {
dispatch(refreshAllComponents());
}, []);
Again this might have nothing to do with OP's problem, but I hope I helps people with the same problem as mine.
If you are using windows system:
please check the file
C:\Windows\System32\drivers\etc\hosts
and add line such as:
127.0.0.1 localhost
I would suggest using list.clear() rather than allocating a new object. When you call the "new" keyword, you are creating more space in memory. In reality, it doesn't matter much. I suppose that if you know how large the list will be, it might be a good idea to create a new space but then specify how large the array will be.
The truth is, it's not going to matter unless you're doing scientific programming. In that case, you need to go learn C++.
If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.
Starting with your example array:
import numpy as np
x = np.array([[1000, 10, 0.5],
[ 765, 5, 0.35],
[ 800, 7, 0.09]])
x_normed = x / x.max(axis=0)
print(x_normed)
# [[ 1. 1. 1. ]
# [ 0.765 0.5 0.7 ]
# [ 0.8 0.7 0.18 ]]
x.max(0)
takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,)
containing the maximum value in each column. You can then divide x
by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.
If x
contains negative values you would need to subtract the minimum first:
x_normed = (x - x.min(0)) / x.ptp(0)
Here, x.ptp(0)
returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.
That clearly depends on the particular implementation of the interpreter/compiler of the specific language.
That said, theoretically, any sane implementation is likely to be able to implement one in terms of the other if it was faster so the difference should be negligible at most.
Of course, I assumed while
and for
behave as they do in C and similar languages. You could create a language with completely different semantics for while
and for