When a module is loaded from a file in Python, __file__
is set to its path. You can then use that with other functions to find the directory that the file is located in.
Taking your examples one at a time:
A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.
B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.
C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.
You can see the various values returned from these here:
import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))
and make sure you run it from different locations (such as ./text.py
, ~/python/text.py
and so forth) to see what difference that makes.
I just want to address some confusion first. __file__
is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.
http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.
In this case __file__
is an attribute of a module (a module object). In Python a .py
file is a module. So import amodule
will have an attribute of __file__
which means different things under difference circumstances.
Taken from the docs:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
In your case the module is accessing it's own __file__
attribute in the global namespace.
To see this in action try:
# file: test.py
print globals()
print __file__
And run:
python test.py
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py
you didn't give a value for id. Try this :
INSERT INTO role (id, name, created) VALUES ('example1','Content Coordinator', GETDATE()), ('example2', 'Content Viewer', GETDATE())
Or you can set the auto increment on id field, if you need the id value added automatically.
This is likely to be attacked via SQL injection by the way. It'd be worth while reading up on that and adjusting your queries accordingly.
Maybe look at even creating a stored proc for this and using something like sp_executesql which can provide some protection against this when dynamic sql is a requirement (ie. unknown table names etc). For more info, check out this link.
Use match
to return your desired vector, then cbind
it to your matrix
cbind(t, z[, "symbol"][match(rownames(t), rownames(z))])
[,1] [,2] [,3] [,4]
GO.ID "GO:0002009" "GO:0030334" "GO:0015674" NA
LEVEL "8" "6" "7" NA
Annotated "342" "343" "350" NA
Significant "1" "1" "1" NA
Expected "0.07" "0.07" "0.07" NA
resultFisher "0.679" "0.065" "0.065" NA
ILMN_1652464 "0" "0" "1" "PLAC8"
ILMN_1651838 "0" "0" "0" "RND1"
ILMN_1711311 "1" "1" "0" NA
ILMN_1653026 "0" "0" "0" "GRA"
PS. Be warned that t
is base R function that is used to transpose matrices. By creating a variable called t, it can lead to confusion in your downstream code.
I had this problem! I tried: git fetch + git merge, but dont resolved! I tried: git pull, and also dont resolved
Then I tried this and resolved my problem (is similar of answer of Engineer):
git fetch origin master:tmp
git rebase tmp
git push origin HEAD:master
git branch -D tmp
SRCS=$(wildcard *.c)
OBJS=$(SRCS:.c=.o)
all: $(OBJS)
Use subquery
SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]
Like the previous replies, I'm also suggesting xcopy
. However, I would like to add to Hallgeir Engen's answer with the /exclude
parameter. There seems to be a bug with the parameter preventing it from working with path names that are long or that contain spaces, as quotes will not work. The path names need to be in the "DOS"-format with "Documents" translating to "DOCUME~1" (according to this source).
So, if you want to use the \exclude parameter, there is a workaround here:
cd $(SolutionDir)
xcopy "source-relative-to-path-above" "destination-relative-to-path-above
/exclude:exclude-file-relative-path
Note that the source and destination paths can (and should, if they contain spaces) be within quotes, but not the path to the exclude file.
Assuming you have two programs that process the two files, process_in.exe and process_out.exe:
for %%f in (*.in) do (
echo %%~nf
process_in "%%~nf.in"
process_out "%%~nf.out"
)
%%~nf is a substitution modifier, that expands %f to a file name only. See other modifiers in https://technet.microsoft.com/en-us/library/bb490909.aspx (midway down the page) or just in the next answer.
Add onclick="window.location = this.href"
to your <a>
element. After this modification it could be .click()
ed with expected behaviour. To do so with every link on your page, you can add this:
<script type="text/javascript">
$(function () {
$("a").attr("onclick", "window.location = this.href");
});
</script>
Good answers above explaining the actual question from the OP.
If anyone needs to pass around a number that needs to be globally updated, use the AtomicInteger(
) instead of creating the various wrapper classes suggested or relying on 3rd party libs.
The AtomicInteger(
) is of course mostly used for thread safe access but if the performance hit is no issue, why not use this built-in class. The added bonus is of course the obvious thread safety.
import java.util.concurrent.atomic.AtomicInteger
SQL> select * from stud;
STUDENTID NAME DETAILS
---------- ------------------------------ ------------------------------
1 Alfred AA
2 Betty BB
3 Chris CC
SQL> select * from subject;
SUBJECTID NAME
---------- ------------------------------
1 Maths
2 Science
3 English
SQL> select * from marks;
STUDENTID SUBJECTID MARK
---------- ---------- ----------
1 1 61
1 2 75
1 3 87
2 1 82
2 2 64
2 3 77
3 1 82
3 2 83
3 3 67
9 rows selected.
SQL> select name, subjectid, mark
2 from (select name, subjectid, mark, dense_rank() over(partition by subjectid order by mark desc) rank
3 from stud st, marks mk
4 where st.studentid=mk.studentid)
5 where rank=1;
NAME SUBJECTID MARK
------------------------------ ---------- ----------
Betty 1 82
Chris 1 82
Chris 2 83
Alfred 3 87
SQL>
There is also an alternative way to use MarkupExtension
in order to use Binding
for a ConverterParameter
. With this solution you can still use the default IValueConverter
instead of the IMultiValueConverter
because the ConverterParameter
is passed into the IValueConverter
just like you expected in your first sample.
Here is my reusable MarkupExtension
:
/// <summary>
/// <example>
/// <TextBox>
/// <TextBox.Text>
/// <wpfAdditions:ConverterBindableParameter Binding="{Binding FirstName}"
/// Converter="{StaticResource TestValueConverter}"
/// ConverterParameterBinding="{Binding ConcatSign}" />
/// </TextBox.Text>
/// </TextBox>
/// </example>
/// </summary>
[ContentProperty(nameof(Binding))]
public class ConverterBindableParameter : MarkupExtension
{
#region Public Properties
public Binding Binding { get; set; }
public BindingMode Mode { get; set; }
public IValueConverter Converter { get; set; }
public Binding ConverterParameter { get; set; }
#endregion
public ConverterBindableParameter()
{ }
public ConverterBindableParameter(string path)
{
Binding = new Binding(path);
}
public ConverterBindableParameter(Binding binding)
{
Binding = binding;
}
#region Overridden Methods
public override object ProvideValue(IServiceProvider serviceProvider)
{
var multiBinding = new MultiBinding();
Binding.Mode = Mode;
multiBinding.Bindings.Add(Binding);
if (ConverterParameter != null)
{
ConverterParameter.Mode = BindingMode.OneWay;
multiBinding.Bindings.Add(ConverterParameter);
}
var adapter = new MultiValueConverterAdapter
{
Converter = Converter
};
multiBinding.Converter = adapter;
return multiBinding.ProvideValue(serviceProvider);
}
#endregion
[ContentProperty(nameof(Converter))]
private class MultiValueConverterAdapter : IMultiValueConverter
{
public IValueConverter Converter { get; set; }
private object lastParameter;
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (Converter == null) return values[0]; // Required for VS design-time
if (values.Length > 1) lastParameter = values[1];
return Converter.Convert(values[0], targetType, lastParameter, culture);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
if (Converter == null) return new object[] { value }; // Required for VS design-time
return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };
}
}
}
With this MarkupExtension
in your code base you can simply bind the ConverterParameter
the following way:
<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
<Setter.Value>
<wpfAdditions:ConverterBindableParameter Binding="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}"
Converter="{StaticResource AccessLevelToVisibilityConverter}"
ConverterParameterBinding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" />
</Setter.Value>
</Setter>
Which looks almost like your initial proposal.
Some handy quick functions (if you're not using Boost):
template<typename T>
std::string ToString(const T& v)
{
std::ostringstream ss;
ss << v;
return ss.str();
}
template<typename T>
T FromString(const std::string& str)
{
std::istringstream ss(str);
T ret;
ss >> ret;
return ret;
}
Example:
int i = FromString<int>(s);
std::string str = ToString(i);
Works for any streamable types (floats etc). You'll need to #include <sstream>
and possibly also #include <string>
.
Currently, your enum
is nested inside of your Card
class. All you have to do is move the definition of the enum
out of the class:
// A better name which follows conventions instead of card_suits is
public enum CardSuit
{
Clubs,
Hearts,
Spades,
Diamonds
}
public class Card
{
}
To Specify:
The name change from card_suits
to CardSuit
was suggested because Microsoft guidelines suggest Pascal Case for Enumerations and the singular form is more descriptive in this case (as a plural would suggest that you're storing multiple enumeration values by ORing them together).
You can have only one default export which you declare like:
export default App;
or
export default class App extends React.Component {...
and later do import App from './App'
If you want to export something more you can use named exports which you declare without default
keyword like:
export {
About,
Contact,
}
or:
export About;
export Contact;
or:
export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);
and later you import them like:
import App, { About, Contact } from './App';
EDIT:
There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js
file. Other than that why export anything if it is no used outside the file?. Correct main.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'
class App extends React.Component {
...
}
class Home extends React.Component {
...
}
class About extends React.Component {
...
}
class Contact extends React.Component {
...
}
ReactDOM.render((
<Router history = {browserHistory}>
<Route path = "/" component = {App}>
<IndexRoute component = {Home} />
<Route path = "home" component = {Home} />
<Route path = "about" component = {About} />
<Route path = "contact" component = {Contact} />
</Route>
</Router>
), document.getElementById('app'))
EDIT2:
another thing is that this tutorial is based on react-router-V3 which has different api than v4.
For t2/m3/c3/c4/r3/i2/d2 instances:
m1 small, medium, and large instances tend to perform higher than expected. c1.medium is another freak, at 800 MBit/s.
I gathered this by combing dozens of sources doing benchmarks (primarily using iPerf & TCP connections). Credit to CloudHarmony & flux7 in particular for many of the benchmarks (note that those two links go to google searches showing the numerous individual benchmarks).
The large instance size has the most variation reported:
Burstable (T2) instances appear to exhibit burstable networking performance too:
The CloudHarmony iperf benchmarks show initial transfers start at 1 GBit/s and then gradually drop to the sustained levels above after a few minutes. PDF links to reports below:
t2.small (PDF)
Note that these are within the same region - if you're transferring across regions, real performance may be much slower. Even for the larger instances, I'm seeing numbers of a few hundred MBit/s.
Depending on what you want the file to contain:
touch /path/to/file
for an empty filesomecommand > /path/to/file
for a file containing the output of some command.
eg: grep --help > randomtext.txt
echo "This is some text" > randomtext.txt
nano /path/to/file
or vi /path/to/file
(or any other editor emacs,gedit etc
)
It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist
Create the file using cat
$ cat > myfile.txt
Now, just type whatever you want in the file:
Hello World!
CTRL-D to save and exit
There are several possible solutions:
touch file
>file
echo -n > file
printf '' > file
The echo
version will work only if your version of echo
supports the -n
switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.
echo '' > file
printf '\n' > file
This is a valid "text file" because it ends in a newline.
"$EDITOR" file
echo 'text' > file
cat > file <<END \
text
END
printf 'text\n' > file
These are equivalent. The $EDITOR
command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat
version presumes a literal newline after the \
and after each other line. Other than that these will all work in a POSIX shell.
Of course there are many other methods of writing and creating files, too.
If you are using CodeIgniter you can solve this by adding the following code to your Controller before loading any Views (assuming you have charset
properly set on your config. If not, just put charset=whateveryouwant
.
$this->output->set_header('Content-type: text/html; charset='.$this->config->item('charset'));
The way I did it was to add that line to the constructor of MY_Controller, my superclass for all Controllers, this way I make sure I will have no encoding problems anywhere.
By the way, this doesn't affect JSON returns (which are encoded in UTF-8).
Object[] obj = {"hi","there"};
Object[] obj2 ={"im","fine","what abt u"};
Object[] obj3 = new Object[obj.length+obj2.length];
for(int i =0;i<obj3.length;i++)
obj3[i] = (i<obj.length)?obj[i]:obj2[i-obj.length];
An alternative to javax.comm
is the rxtx
library which supports more platforms than javax.comm
.
If you're using the DateTime module, you can call the epoch() method on a DateTime object, since that's what you think of as unix time.
Using DateTimes allows you to convert fairly easily from epoch, to date objects.
Alternativly, localtime and gmtime will convert an epoch into an array containing day month and year, and timelocal and timegm from the Time::Local module will do the opposite, converting an array of time elements (seconds, minutes, ..., days, months etc.) into an epoch.
If you say window.location.reload(true)
the browser will skip the cache and reload the page from the server. window.location.reload(false)
will do the opposite.
Note: default
value for window.location.reload()
is false
As per the MDN Specifications, X-Frame-Options: ALLOW-FROM
is not supported in Chrome and support is unknown in Edge and Opera.
Content-Security-Policy: frame-ancestors
overrides X-Frame-Options
(as per this W3 spec), but frame-ancestors
has limited compatibility. As per these MDN Specs, it's not supported in IE or Edge.
You have some variables that are different types in Java language like that:
message of type string
timestamp of type time
count of type integer
version of type integer
If you use a HashMap like:
HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put("message","message");
yourHash.put("timestamp",timestamp);
yourHash.put("count ",count);
yourHash.put("version ",version);
If you want to use the yourHash:
for(String key : yourHash.keySet()){
String message = (String) yourHash.get(key);
Datetime timestamp= (Datetime) yourHash.get(key);
int timestamp= (int) yourHash.get(key);
}
@available(iOS 11.0, *)
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let editAction = UIContextualAction.init(style: UIContextualAction.Style.normal, title: "Edit", handler: { (action, view, completion) in
//TODO: Edit
completion(true)
self.popUpViewPresent(index:indexPath.row)
})
let deleteAction = UIContextualAction.init(style: UIContextualAction.Style.destructive, title: "Delete", handler: { (action, view, completion) in
//TODO: Delete
completion(true)
self.deleteTagAction(senderTag:indexPath.row)
})
editAction.image = UIImage(named: "Edit-white")
deleteAction.image = UIImage(named: "Delete-white")
editAction.backgroundColor = UIColor.gray
deleteAction.backgroundColor = UIColor.red
let config = UISwipeActionsConfiguration(actions: [deleteAction, editAction])
config.performsFirstActionWithFullSwipe = false
return config
}
milliseconds = 12884983 // or x milliseconds
hr = 0
min = 0
sec = 0
day = 0
while (milliseconds >= 1000) {
milliseconds = (milliseconds - 1000)
sec = sec + 1
if (sec >= 60) min = min + 1
if (sec == 60) sec = 0
if (min >= 60) hr = hr + 1
if (min == 60) min = 0
if (hr >= 24) {
hr = (hr - 24)
day = day + 1
}
}
I hope that my shorter method will help you
Not sure why nobody posted an actual SVG answer. Here is an SVG rectangle with rounded corners (radius 3) on the top:
<svg:path d="M0,0 L0,27 A3,3 0 0,0 3,30 L7,30 A3,3 0 0,0 10,27 L10,0 Z" />
This is a Move To (M), Line To (L), Arc To (A), Line To (L), Arc To (A), Line To (L), Close Path (Z).
The comma-delimited numbers are absolute coordinates. The arcs are defined with additional parameters specifying the radius and type of arc. This could also be accomplished with relative coordinates (use lower-case letters for L and A).
The complete reference for those commands is on the W3C SVG Paths page, and additional reference material on SVG paths can be found in this article.
You can use from bellow code for date and time :
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println("Current Date Time : " + dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, 1);
System.out.println("Add one day to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
System.out.println("Add one month to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.YEAR, 1);
System.out.println("Add one year to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.HOUR, 1);
System.out.println("Add one hour to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 1);
System.out.println("Add one minute to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 1);
System.out.println("Add one second to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println("Subtract one day from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println("Subtract one month from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
System.out.println("Subtract one year from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -1);
System.out.println("Subtract one hour from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, -1);
System.out.println("Subtract one minute from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.SECOND, -1);
System.out.println("Subtract one second from current date : " + dateFormat.format(cal.getTime()));
Output :
Current Date Time : 2008/12/28 10:24:53
Add one day to current date : 2008/12/29 10:24:53
Add one month to current date : 2009/01/28 10:24:53
Add one year to current date : 2009/12/28 10:24:53
Add one hour to current date : 2008/12/28 11:24:53
Add one minute to current date : 2008/12/28 10:25:53
Add one second to current date : 2008/12/28 10:24:54
Subtract one day from current date : 2008/12/27 10:24:53
Subtract one month from current date : 2008/11/28 10:24:53
Subtract one year from current date : 2007/12/28 10:24:53
Subtract one hour from current date : 2008/12/28 09:24:53
Subtract one minute from current date : 2008/12/28 10:23:53
Subtract one second from current date : 2008/12/28 10:24:52
This link is good : See here
And see : See too
And : Here
And : Here
And : Here
If you need just time :
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
This will give you some control over the clicking, and looks tidy
<script>
var timeOut = 0;
function onClick(but)
{
//code
clearTimeout(timeOut);
timeOut = setTimeout(function (){onClick(but)},1000);
}
</script>
<button onclick="onClick(this)">Start clicking</button>
XCODE 10.1
1. Goto Xcode -> Preferences (Shortcut CMD,)
2. Select Components
3. Download Simulator version
4. XCode -> Open Developer Tool -> Simulator This will launch Simulator as stand alone application
5 Hardware -> Device -> Manage Devices...
6. Click on + iCon to create new simulator version.
7. Specify Simulator Name, Device Type and Choose OS version from drop down.
8. Click Create.
9. Hardware -> Device -> iOS 11.0 -> iPhone 6
Thats it run enjoy coding!
Found all the windows binaries here :
https://github.com/ojdkbuild/ojdkbuild
These Windows binaries are built to keep them as close as possible in behaviour to java-x-openjdk CentOS packages.
If I understand you, perhaps you don't need an array of zeroes; rather, you need a hash. The hash keys will be the values in the other array and the hash values will be the number of times the value exists in the other array:
use strict;
use warnings;
my @other_array = (0,0,0,1,2,2,3,3,3,4);
my %tallies;
$tallies{$_} ++ for @other_array;
print "$_ => $tallies{$_}\n" for sort {$a <=> $b} keys %tallies;
Output:
0 => 3
1 => 1
2 => 2
3 => 3
4 => 1
To answer your specific question more directly, to create an array populated with a bunch of zeroes, you can use the technique in these two examples:
my @zeroes = (0) x 5; # (0,0,0,0,0)
my @zeroes = (0) x @other_array; # A zero for each item in @other_array.
# This works because in scalar context
# an array evaluates to its size.
This will work regardless of what column inside your one code line for cell thats located in row X, in column Y:
Mid(Cells(X,Y).Address, 2, instr(2,Cells(X,Y).Address,"$")-2)
If you have a cell with unique defined name "Cellname":
Mid(Cells(1,val(range("Cellname").Column)).Address, 2, instr(2,Cells(1,val(range("Cellname").Column)).Address,"$")-2)
put below tag in web.config file in configuration node
<connectionStrings>
<add name="NameOFConnectionString" connectionString="Data Source=Server;Initial Catalog=DatabaseName;User ID=User;Password=Pwd"
providerName="System.Data.SqlClient" />
then you can use above connectionstring, e.g.
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["NameOFConnectionString"].ToString();
First of all don't make the mock static. Make it a private field. Just put your setUp class in the @Before
not @BeforeClass
. It might be run a bunch, but it's cheap.
Secondly, the way you have it right now is the correct way to get a mock to return something different depending on the test.
JS provides the tools to do this the right way. Try the demo snippet.
var doc = document;_x000D_
var buttons = doc.getElementsByTagName('button');_x000D_
var button = buttons[0];_x000D_
_x000D_
button.addEventListener("mouseover", function(){_x000D_
this.classList.add('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseout", function(){_x000D_
this.classList.remove('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mousedown", function(){_x000D_
this.classList.add('mouse-down');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseup", function(){_x000D_
this.classList.remove('mouse-down');_x000D_
alert('Button Clicked!');_x000D_
});_x000D_
_x000D_
//this is unrelated to button styling. It centers the button._x000D_
var box = doc.getElementById('box');_x000D_
var boxHeight = window.innerHeight;_x000D_
box.style.height = boxHeight + 'px';
_x000D_
button{_x000D_
text-transform: uppercase;_x000D_
background-color:rgba(66, 66, 66,0.3);_x000D_
border:none;_x000D_
font-size:4em;_x000D_
color:white;_x000D_
-webkit-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
-moz-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
}_x000D_
button:focus {_x000D_
outline:0;_x000D_
}_x000D_
.mouse-over{_x000D_
background-color:rgba(66, 66, 66,0.34);_x000D_
}_x000D_
.mouse-down{_x000D_
-webkit-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
-moz-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52); _x000D_
}_x000D_
_x000D_
/* unrelated to button styling */_x000D_
#box {_x000D_
display: flex;_x000D_
flex-flow: row nowrap ;_x000D_
justify-content: center;_x000D_
align-content: center;_x000D_
align-items: center;_x000D_
width:100%;_x000D_
}_x000D_
_x000D_
button {_x000D_
order:1;_x000D_
flex: 0 1 auto;_x000D_
align-self: auto;_x000D_
min-width: 0;_x000D_
min-height: auto;_x000D_
} _x000D_
_x000D_
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset=utf-8 />_x000D_
<meta name="description" content="3d Button Configuration" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<section id="box">_x000D_
<button>_x000D_
Submit_x000D_
</button>_x000D_
</section>_x000D_
</body>_x000D_
</html>
_x000D_
If you don't want the image to affect the layout at all (and float on top of other content) you can apply the following CSS to the image:
position:absolute;
right:0;
top:0;
If you want it to float at the right of a particular parent section, you can add position: relative
to that section.
@Asahi pretty much hit the nail on the head, but I just wanted to add a bit of XML for anyone maybe floating in here later via google:
<ListView android:id="@+id/MyListView"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:divider="@android:color/transparent"
android:dividerHeight="10.0sp"/>
For some reason, values such as "10", "10.0", and "10sp" all are rejected by Android for the dividerHeight
value. It wants a floating point number and a unit, such as "10.0sp". As @Goofyahead notes, you can also use display-independent pixels for this value (ie, "10dp").
The full modern solution to your problem is purely CSS-based, but note that older browsers won't support it, in which cases you'd need to fallback to solutions such as the others have provided.
So in pure CSS:
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
However the mouse cursor will still change to a caret when over the element's text, so you add to that:
cursor: default;
Modern CSS is pretty elegant.
we can try this to get current script name without extension.
import os
script_name = os.path.splitext(os.path.basename(__file__))[0]
You can check out my add on for firefox. It allows to cross domain in the lastest firefox version: https://addons.mozilla.org/en-US/firefox/addon/cross-domain-cors/
add JAVA_HOME to the file:
/etc/environment
for it to be available to the entire system (you would need to restart Ubuntu though)
int index = std::distance(std::begin(myArray), std::find(begin(myArray), end(std::myArray), VALUE));
Returns an invalid index (length of the array) if not found.
From here:
// Add jQuery
var GM_JQ = document.createElement('script');
GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
GM_JQ.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(GM_JQ);
// Check if jQuery's loaded
function GM_wait()
{
if(typeof unsafeWindow.jQuery == 'undefined')
{
window.setTimeout(GM_wait,100);
}
else
{
$ = unsafeWindow.jQuery;
letsJQuery();
}
}
GM_wait();
// All your GM code must be inside this function
function letsJQuery()
{
// Do your jQuery stuff in here
}
This will wait until jQuery is loaded to use it, but you can use the same concept, setting variables in your other scripts (or checking them if they're not your script) to wait until they're loaded to use them.
For example, on my site, I use this for asynchronous JS loading and waiting until they're finished before doing anything with them using jQuery:
<script type="text/javascript" language="JavaScript">
function js(url){
s = document.createElement("script");
s.type = "text/javascript";
s.src = url;
document.getElementsByTagName("head")[0].appendChild(s);
}
js("/js/jquery-ui.js");
js("/js/jrails.js");
js("/js/jquery.jgrowl-min.js");
js("/js/jquery.scrollTo-min.js");
js("/js/jquery.corner-min.js");
js("/js/jquery.cookie-min.js");
js("/js/application-min.js");
function JS_wait() {
if (typeof $.cookie == 'undefined' || // set in jquery.cookie-min.js
typeof getLastViewedAnchor == 'undefined' || // set in application-min.js
typeof getLastViewedArchive == 'undefined' || // set in application-min.js
typeof getAntiSpamValue == 'undefined') // set in application-min.js
{
window.setTimeout(JS_wait, 100);
}
else
{
JS_ready();
}
}
function JS_ready() {
// snipped
};
$(document).ready(JS_wait);
</script>
In a google script project you can create html files (example: index.html) or gs files (example:code.gs). The .gs files are executed on the server and you can use Logger.log as @Peter Herrman describes. However if the function is created in a .html file it is being executed on the user's browser and you can use console.log. The Chrome browser console can be viewed by Ctrl Shift J on Windows/Linux or Cmd Opt J on Mac
If you want to use Logger.log on an html file you can use a scriptlet to call the Logger.log function from the html file. To do so you would insert <? Logger.log(something) ?> replacing something with whatever you want to log. Standard scriptlets, which use the syntax <? ... ?>, execute code without explicitly outputting content to the page.
try this:
SELECT
t.*
FROM TestData t
INNER JOIN (SELECT
MIN(ID) as MinID
FROM TestData
WHERE SKU LIKE 'FOO-%'
) dt ON t.ID=dt.MinID
EDIT
once the OP corrected his samle output (previously had only ONE result row, now has all shown), this is the correct query:
declare @TestData table (ID int, sku char(6), product varchar(15))
insert into @TestData values (1 , 'FOO-23' ,'Orange')
insert into @TestData values (2 , 'BAR-23' ,'Orange')
insert into @TestData values (3 , 'FOO-24' ,'Apple')
insert into @TestData values (4 , 'FOO-25' ,'Orange')
--basically the same as @Aaron Alton's answer:
SELECT
dt.ID, dt.SKU, dt.Product
FROM (SELECT
ID, SKU, Product, ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowID
FROM @TestData
WHERE SKU LIKE 'FOO-%'
) AS dt
WHERE dt.RowID=1
ORDER BY dt.ID
SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;
(the documentation for this is here: http://dev.mysql.com/doc/refman/5.0/en/select.html)
or:
$select = "SELECT * FROM table_name";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
I was facing the same issue as below.
npm ERR! errno -4058 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory, open 'D:\SVenu\FullStackDevelopment\Angular\Angular2_Splitter_CodeSkeleton\CodeSke leton\run\package.json' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent
The problem I made was, I was running the command npm build run
instead of running npm run build
.
Just sharing to help someone who does small mistakes like me.
This is a good way to do it:
<?php
if (!(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' ||
$_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>
In order to change the label size you can select an appropriate size policy for the label like expanding or minimum expanding.
You can scale the pixmap by keeping its aspect ratio every time it changes:
QPixmap p; // load pixmap
// get label dimensions
int w = label->width();
int h = label->height();
// set a scaled pixmap to a w x h window keeping its aspect ratio
label->setPixmap(p.scaled(w,h,Qt::KeepAspectRatio));
There are two places where you should add this code:
resizeEvent
of the widget that contains the labelBelow code avoids creating infinite loop. Assume XYZ is the string which we are looking for in the workbook.
Private Sub CommandButton1_Click()
Dim Sh As Worksheet, myCounter
Dim Loc As Range
For Each Sh In ThisWorkbook.Worksheets
With Sh.UsedRange
Set Loc = .Cells.Find(What:="XYZ")
If Not Loc Is Nothing Then
MsgBox ("Value is found in " & Sh.Name)
myCounter = 1
Set Loc = .FindNext(Loc)
End If
End With
Next
If myCounter = 0 Then
MsgBox ("Value not present in this worrkbook")
End If
End Sub
You could try:
$(this).closest(".column").prev().find(".inputQty").val();
Ok i was previously not aware that AngularJS
usually refers to Angular
v1 version and only Angular to Angular v2+
This answer only applies for Angular
Leaving this here for future reference..
Not sure how it works for you guys but on Angular 9 i have to wrap ngStyle in brackets like this:
[ng-style]="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"
Otherwise it doesn't work
Some reference for you http://dev.mysql.com/doc/refman/5.0/en/update.html
UPDATE user_account student
INNER JOIN user_account teacher ON
teacher.user_account_id = student.teacher_id
AND teacher.user_type = 'ROLE_TEACHER'
SET student.student_education_facility_id = teacher.education_facility_id
Here is a plugin for you: (Fiddle: http://jsfiddle.net/maniator/CjrJ7/)
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
//use it:
$('textarea').pressEnter(function(){alert('here')})
Here's my imperative version of mkdirp
for nodejs.
function mkdirSyncP(location) {
let normalizedPath = path.normalize(location);
let parsedPathObj = path.parse(normalizedPath);
let curDir = parsedPathObj.root;
let folders = parsedPathObj.dir.split(path.sep);
folders.push(parsedPathObj.base);
for(let part of folders) {
curDir = path.join(curDir, part);
if (!fs.existsSync(curDir)) {
fs.mkdirSync(curDir);
}
}
}
<p><strong>This is in bold.</strong> This is not.</p>
You might find Mozilla Developer Network to be a very handy and reliable reference.
You can use Simple JSON for PHP. It sends the headers help you to forge the JSON.
It looks like :
<?php
// Include the json class
include('includes/json.php');
// Then create the PHP-Json Object to suits your needs
// Set a variable ; var name = {}
$Json = new json('var', 'name');
// Fire a callback ; callback({});
$Json = new json('callback', 'name');
// Just send a raw JSON ; {}
$Json = new json();
// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';
// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);
// Finally, send the JSON.
$Json->send();
?>
Enter the first in the series and select that cell, then series fill (HOME > Editing - Fill, Series..., Columns):
It is very fast and the results are values not formulae.
a very common try_files line which can be applied on your condition is
location / {
try_files $uri $uri/ /test/index.html;
}
you probably understand the first part, location /
matches all locations, unless it's matched by a more specific location, like location /test
for example
The second part ( the try_files
) means when you receive a URI that's matched by this block try $uri
first, for example http://example.com/images/image.jpg
nginx will try to check if there's a file inside /images
called image.jpg
if found it will serve it first.
Second condition is $uri/
which means if you didn't find the first condition $uri
try the URI as a directory, for example http://example.com/images/
, ngixn will first check if a file called images
exists then it wont find it, then goes to second check $uri/
and see if there's a directory called images
exists then it will try serving it.
Side note: if you don't have autoindex on
you'll probably get a 403 forbidden error, because directory listing is forbidden by default.
EDIT: I forgot to mention that if you have
index
defined, nginx will try to check if the index exists inside this folder before trying directory listing.
Third condition /test/index.html
is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html
inside the folder test
and serve it if it exists.
If the third condition fails too, then nginx will serve the 404 error page.
Also there's something called named locations, like this
location @error {
}
You can call it with try_files
like this
try_files $uri $uri/ @error;
TIP: If you only have 1 condition you want to serve, like for example inside folder images
you only want to either serve the image or go to 404 error, you can write a line like this
location /images {
try_files $uri =404;
}
which means either serve the file or serve a 404 error, you can't use only $uri
by it self without =404
because you need to have a fallback option.
You can also choose which ever error code you want, like for example:
location /images {
try_files $uri =403;
}
This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..
The Android NDK is a toolset that lets you implement parts of your app in native code, using languages such as C and C++. For certain types of apps, this can help you reuse code libraries written in those languages.
For more info on how to get started with native development, follow this link.
Sample applications can be found here.
The following code is cross-browser compliant. It works in IE7, IE8, Fx 3, Safari, and Chrome, so no need to handle cross-browser issues. Did not test in IE6.
<iframe id="iframeId" name="iframeId">...</iframe>
<script type="text/javascript">
var iframeDoc;
if (window.frames && window.frames.iframeId &&
(iframeDoc = window.frames.iframeId.document)) {
var iframeBody = iframeDoc.body;
var ifromContent = iframeBody.innerHTML;
}
</script>
It is just letting you know that the object you are printing is not a string, rather a byte object as a byte literal. People explain this in incomplete ways, so here is my take.
Consider creating a byte object by typing a byte literal (literally defining a byte object without actually using a byte object e.g. by typing b'') and converting it into a string object encoded in utf-8. (Note that converting here means decoding)
byte_object= b"test" # byte object by literally typing characters
print(byte_object) # Prints b'test'
print(byte_object.decode('utf8')) # Prints "test" without quotations
You see that we simply apply the .decode(utf8)
function.
https://docs.python.org/3.3/library/stdtypes.html#bytes
https://docs.python.org/3.3/reference/lexical_analysis.html#string-and-bytes-literals
stringliteral ::= [stringprefix](shortstring | longstring)
stringprefix ::= "r" | "u" | "R" | "U"
shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::= shortstringchar | stringescapeseq
longstringitem ::= longstringchar | stringescapeseq
shortstringchar ::= <any source character except "\" or newline or the quote>
longstringchar ::= <any source character except "\">
stringescapeseq ::= "\" <any source character>
bytesliteral ::= bytesprefix(shortbytes | longbytes)
bytesprefix ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
shortbytes ::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
longbytes ::= "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
shortbytesitem ::= shortbyteschar | bytesescapeseq
longbytesitem ::= longbyteschar | bytesescapeseq
shortbyteschar ::= <any ASCII character except "\" or newline or the quote>
longbyteschar ::= <any ASCII character except "\">
bytesescapeseq ::= "\" <any ASCII character>
How about below:
FileReader fileReader = new FileReader(new File("test.txt"));
BufferedReader br = new BufferedReader(fileReader);
String line = null;
// if no more lines the readLine() returns null
while ((line = br.readLine()) != null) {
// reading lines until the end of the file
}
Source: http://devmain.blogspot.co.uk/2013/10/java-quick-way-to-read-or-write-to-file.html
I have used this before and I think in order to make sure credential persist and in a best secure way is
ConfigurationManager
classSecureString
classCryptography
namespace.This link will be of great help I hope : Click here
SELECT Id 'PatientId',
ISNULL(CONVERT(varchar(50),ParentId),'') 'ParentId'
FROM Patients
ISNULL
always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar
), you'd best make sure that's the type of the first argument.
COALESCE
is usually a better function to use than ISNULL
, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier
has higher precedence than varchar
, so that doesn't help.
(It's also generally preferred because it extends to more than two arguments)
Probably somewhere you have DBconnection->close();
and then some queries try to execute .
Hint: It's sometimes mistake to insert ...->close();
in __destruct()
(because __destruct
is event, after which there will be a need for execution of queries)
You can reset settings for eclipse by deleting .metadata folder from your current workspace.
This will however remove all projects from your project explorer NOT workspace. So dont worry your projects have not gone anywhere.
You can import projects from your workspace like this : just make sure that you uncheck "Copy project into workspace".
Full version:
<? echo date('F Y'); ?>
Short version:
<? echo date('M Y'); ?>
Here is a good reference for the different date options.
update
To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp
parameter for the date() function. Like this:
echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));
This will also work (it's typically used to get the last day of the previous month):
echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));
Hope that helps.
i believe that DI is a way of configurings or instantianting a bean. The DI can be done in many ways like constructor, setter-getter etc.
Factory pattern is just another way of instantiating beans. this pattern will be used mainly when you have to create objects using factory design pattern,because while using this pattern you dont configure the properties of a bean, only instantiate the object.
Check this link :Dependency Injection
import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))
Note that expanduser
is necessary (on Unix) in case the given expression for the file (or directory) name and location may contain a leading ~/
(the tilde refers to the user's home directory), and expandvars
takes care of any other environment variables (like $HOME
).
The formal difference -
The difference in usage:
object
. You can use it with or without related class. In 1st case it's called a companion object. You have to:
To create a program you should use main method in object
, not in class
.
object Hello {
def main(args: Array[String]) {
println("Hello, World!")
}
}
You also may use it as you use singleton object in java.
There are 4 dimensions of the tensor you want to convert.
[:, ::-1, :, :]
:
means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.
::-1
means that for the second axes it reverses the the axes
This might be because of the transitive dependencies.
Try to add/ remove the scope from the JSTL library.
This worked for me!
Building on the previous answers, please note an important point, you also need to manipulate your table column to ensure it does not contain the time fragment of the datetime datatype.
Below is a small sample script demonstrating the above:
select getdate()
--2012-05-01 12:06:51.413
select cast(getdate() as date)
--2012-05-01
--we're using sysobjects for the example
create table test (id int)
select * from sysobjects where cast(crdate as date) = cast(getdate() as date)
--resultset contains only objects created today
drop table test
I hope this helps.
EDIT:
Following @dwurf comment (thanks) about the effect the above example may have on performance, I would like to suggest the following instead.
We create a date range between today at midnight (start of day) and the last millisecond of the day (SQL server count up to .997, that's why I'm reducing 3 milliseconds). In this manner we avoid manipulating the left side and avoid the performance impact.
select getdate()
--2012-05-01 12:06:51.413
select dateadd(millisecond, -3, cast(cast(getdate()+1 as date) as datetime))
--2012-05-01 23:59:59.997
select cast(getdate() as date)
--2012-05-01
create table test (id int)
select * from sysobjects where crdate between cast(getdate() as date) and dateadd(millisecond, -3, cast(cast(getdate()+1 as date) as datetime))
--resultset contains only objects created today
drop table test
A space is encoded to %20
in URLs, and to +
in forms submitted data (content type application/x-www-form-urlencoded). You need the former.
Using Guava:
dependencies {
compile 'com.google.guava:guava:23.0'
// or, for Android:
compile 'com.google.guava:guava:23.0-android'
}
You can use UrlEscapers:
String encodedString = UrlEscapers.urlFragmentEscaper().escape(inputString);
Don't use String.replace, this would only encode the space. Use a library instead.
Thanks all for your help! Finally I used JQuery/AJAX as you suggested, passing the parameter using model.
So, in JS:
$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction);
var points= $('#newpoints').val();
$element.find('PointsDiv').html("You have" + points+ " points");
In Controller:
var model = _newPoints;
return PartialView(model);
In View
<div id="divPoints"></div>
@Html.Hidden("newpoints", Model)
As others have pointed out, you can combine find
and basename
, but by default the basename
program will only operate on one path at a time, so the executable will have to be launched once for each path (using either find ... -exec
or find ... | xargs -n 1
), which may potentially be slow.
If you use the -a
option on basename
, then it can accept multiple filenames in a single invocation, which means that you can then use xargs
without the -n 1
, to group the paths together into a far smaller number of invocations of basename
, which should be more efficient.
Example:
find /dir1 -type f -print0 | xargs -0 basename -a
Here I've included the -print0
and -0
(which should be used together), in order to cope with any whitespace inside the names of files and directories.
Here is a timing comparison, between the xargs basename -a
and xargs -n1 basename
versions. (For sake of a like-with-like comparison, the timings reported here are after an initial dummy run, so that they are both done after the file metadata has already been copied to I/O cache.) I have piped the output to cksum
in both cases, just to demonstrate that the output is independent of the method used.
$ time sh -c 'find /usr/lib -type f -print0 | xargs -0 basename -a | cksum'
2532163462 546663
real 0m0.063s
user 0m0.058s
sys 0m0.040s
$ time sh -c 'find /usr/lib -type f -print0 | xargs -0 -n 1 basename | cksum'
2532163462 546663
real 0m14.504s
user 0m12.474s
sys 0m3.109s
As you can see, it really is substantially faster to avoid launching basename
every time.
You should be able to use the "client.ResponseHeaders[..]" call, see this link for examples of getting stuff back from the response
You can use parents() to get all parents with the given selector.
Description: Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
But parent() will get just the first parent of the element.
Description: Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
And there is .parentsUntil() which I think will be the best.
Description: Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector.
It's possible to do this without using extra JS code using the data-collapse and data-target attributes on the a link.
e.g.
<a class="btn" data-toggle="collapse" data-target="#viewdetails">View details »</a>
Cookies are not for authentication. Why reinvent a wheel? HTTP has well-designed authentication mechanisms. If we use cookies, we fall into using HTTP as a transport protocol only, thus we need to create our own signaling system, for example, to tell users that they supplied wrong authentication (using HTTP 401 would be incorrect as we probably wouldn't supply Www-Authenticate
to a client, as HTTP specs require :) ). It should also be noted that Set-Cookie
is only a recommendation for client. Its contents may be or may not be saved (for example, if cookies are disabled), while Authorization
header is sent automatically on every request.
Another point is that, to obtain an authorization cookie, you'll probably want to supply your credentials somewhere first? If so, then wouldn't it be RESTless? Simple example:
GET /a
without cookiePOST /auth
Set-Cookie
GET /a
with cookie. But does GET /a
behave idempotently in this case?To sum this up, I believe that if we access some resource and we need to authenticate, then we must authenticate on that same resource, not anywhere else.
Whatever is specified in the command
in docker-compose.yml should get appended to the entrypoint
defined in the Dockerfile, provided entrypoint
is defined in exec form in the Dockerfile.
If the EntryPoint is defined in shell form, then any CMD arguments will be ignored.
You can use toLocaleString(). This is a javascript method.
var event = new Date("01/02/1993");_x000D_
_x000D_
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };_x000D_
_x000D_
console.log(event.toLocaleString('en', options));_x000D_
_x000D_
// expected output: "Saturday, January 2, 1993"
_x000D_
Almost all formats supported. Have look on this link for more details.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
While the other posters addressed why is True
does what it does, I wanted to respond to this part of your post:
I thought Python treats anything with value as True. Why is this happening?
Coming from Java, I got tripped up by this, too. Python does not treat anything with a value as True
. Witness:
if 0:
print("Won't get here")
This will print nothing because 0 is treated as False
. In fact, zero of any numeric type evaluates to False
. They also made decimal
work the way you'd expect:
from decimal import *
from fractions import *
if 0 or 0.0 or 0j or Decimal(0) or Fraction(0, 1):
print("Won't get here")
Here are the other value which evaluate to False
:
if None or False or '' or () or [] or {} or set() or range(0):
print("Won't get here")
Sources:
SET JAVA_HOME=C:\Program Files\Java\jdk1.8.0
worked fine for me.
Note - Don't put double quotes over the path as mentioned above. Otherwise when you run
mvn -version
it will give following error
Files\java\jdk1.8.0_201\jre""==""
was unexpected at this time.
maybe something like this:
foreach (var keyvaluepair in dict)
{
if(Object.ReferenceEquals(keyvaluepair.Value, searchedObject))
{
//dict.Remove(keyvaluepair.Key);
break;
}
}
Great answers. Adding one that loads the color from an Android resources xml but still sets it programmatically:
textView.setTextColor(getResources().getColor(R.color.some_color));
Please note that from API 23, getResources().getColor()
is deprecated. Use instead:
textView.setTextColor(ContextCompat.getColor(context, R.color.some_color));
where the required color is defined in an xml as:
<resources>
<color name="some_color">#bdbdbd</color>
</resources>
Update:
This method was deprecated in API level 23. Use getColor(int, Theme) instead.
Check this.
I doubt css understands left
by itself. You need to use it specifying position. You are using .css() correctly
position: relative/absolute/whatever;
left: 900px;
heres a fiddle of it working
and without the position here's what you get
Change your if statement to be like this - with quotes around -900px
var n = $("items").css("left");
if(n == '-900px'){
$(".items span").fadeOut("slow");
}
It is indeed depending on the test runner as @jonzim mentioned.
For NUnit 3 I had to use NUnit.Framework.TestContext.Progress.WriteLine()
to get running output in the Output window of Visual Studio 2017.
NUnit describes how to: here
To my understanding this revolves around the added parallelization of test execution the test runners have received.
I meet the same problem.
it lies in the .xls file itself - it looks like an Excel file however it isn't. (see if there's a pop up when you plainly open the .xls from Excel)
sjmachin commented on Jan 19, 2013 from https://github.com/python-excel/xlrd/issues/26 helps.
The JavaScript Object()
constructor makes an Object that you can assign members to.
myObj = new Object()
myObj.key = value;
myObj[key2] = value2; // Alternative
To turn a 2D JavaScript array into an HTML table, you really need but a little bit of code :
function arrayToTable(tableData) {_x000D_
var table = $('<table></table>');_x000D_
$(tableData).each(function (i, rowData) {_x000D_
var row = $('<tr></tr>');_x000D_
$(rowData).each(function (j, cellData) {_x000D_
row.append($('<td>'+cellData+'</td>'));_x000D_
});_x000D_
table.append(row);_x000D_
});_x000D_
return table;_x000D_
}_x000D_
_x000D_
$('body').append(arrayToTable([_x000D_
["John","Slegers",34],_x000D_
["Tom","Stevens",25],_x000D_
["An","Davies",28],_x000D_
["Miet","Hansen",42],_x000D_
["Eli","Morris",18]_x000D_
]));
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
_x000D_
If you want to load your 2D array from a JSON file, you'll also need a little bit of Ajax code :
$.ajax({
type: "GET",
url: "data.json",
dataType: 'json',
success: function (data) {
$('body').append(arrayToTable(data));
}
});
you need to add 3 dependency ( API+ API implementation + log4j dependency)
Add also this
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.5</version>
</dependency>
# And to see log in command line , set log4j.properties
# Root logger option
log4j.rootLogger=INFO, file, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
#And to see log in file , set log4j.properties
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./logs/logging.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
It should be something like...
<xsl:if test="contains($hhref, '1234')">
(not tested)
See w3schools (always a good reference BTW)
You've already done it correctly by using a DateTime
parameter with the value from the DateTime
, so it should already work. Forget about ToString()
- since that isn't used here.
If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).
I have a table and the date-times in it are in the format:
2011-07-01 15:17:33.357
Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281
. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.
As has been said, using unset is different with arrays as well
$ foo=(4 5 6)
$ foo[2]=
$ echo ${#foo[*]}
3
$ unset foo[2]
$ echo ${#foo[*]}
2
Make the outer loop a while loop, and "Exit While" in the if statement.
In Ubuntu it looks like this :
$ sudo apt-get install python-dev libldap2-dev libsasl2-dev libssl-dev
$ sudo pip install python-ldap
I used a local distribution of gradle downloaded from gradle website and used it in android studio.
It fixed the gradle build error.
Use the selectedIndex
property:
document.getElementById("Mobility").selectedIndex = 12; //Option 10
Alternate method:
Loop through each value:
//Get select object
var objSelect = document.getElementById("Mobility");
//Set selected
setSelectedValue(objSelect, "10");
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
I Faced the same issue while installing a setup using a jar file. Solution thta worked for me is
java -jar <<jar fully qualified path>>
It worked for me :)
Maybe I'll help someone else. None of the above answers worked for Catalina. Finally, this solved the problem
echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> /Users/$(whoami)/.bash_profile
Of course, you have to change for the version of mysql you have installed
I was looking into the explanation " If you only override hashCode then when you call myMap.put(first,someValue)
it takes first, calculates its hashCode and stores it in a given bucket. Then when you call myMap.put(first,someOtherValue)
it should replace first with second as per the Map Documentation because they are equal (according to our definition)." :
I think 2nd time when we are adding in myMap
then it should be the 'second' object like myMap.put(second,someOtherValue)
I found this to be a good solution for the most part:
SELECT * FROM table ORDER BY ISNULL(field), field ASC;
I realize this has been answered, but there is a slight issue with the accepted solution. It will return false positives. Easy to fix:
SELECT * FROM Products P
WHERE (@Status='published' and P.Status IN (1,3))
or (@Status='standby' and P.Status IN (2,5,9,6))
or (@Status='deleted' and P.Status IN (4,5,8,10))
or (@Status not in ('published','standby','deleted') and P.Status IN (1,2))
Parentheses aren't needed (although perhaps easier to read hence why I included them).
>>>print(*range(1,11))
1 2 3 4 5 6 7 8 9 10
Python one liner to print the range
Alternatively YUI has http://yuilibrary.com/yui/docs/api/classes/QueryString.html#method_stringify.
For example:
var data = { one: 'first', two: 'second' };
var result = Y.QueryString.stringify(data);
New introduction 2
In the previous version of macro "SaveEmailDetails" I used this statement to find Inbox:
Set FolderTgt = CreateObject("Outlook.Application"). _
GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
I have since installed a newer version of Outlook and I have discovered that it does not use the default Inbox. For each of my email accounts, it created a separate store (named for the email address) each with its own Inbox. None of those Inboxes is the default.
This macro, outputs the name of the store holding the default Inbox to the Immediate Window:
Sub DsplUsernameOfDefaultStore()
Dim NS As Outlook.NameSpace
Dim DefaultInboxFldr As MAPIFolder
Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")
Set DefaultInboxFldr = NS.GetDefaultFolder(olFolderInbox)
Debug.Print DefaultInboxFldr.Parent.Name
End Sub
On my installation, this outputs: "Outlook Data File".
I have added an extra statement to macro "SaveEmailDetails" that shows how to access the Inbox of any store.
New introduction 1
A number of people have picked up the macro below, found it useful and have contacted me directly for further advice. Following these contacts I have made a few improvements to the macro so I have posted the revised version below. I have also added a pair of macros which together will return the MAPIFolder object for any folder with the Outlook hierarchy. These are useful if you wish to access other than a default folder.
The original text referenced one question by date which linked to an earlier question. The first question has been deleted so the link has been lost. That link was to Update excel sheet based on outlook mail (closed)
Original text
There are a surprising number of variations of the question: "How do I extract data from Outlook emails to Excel workbooks?" For example, two questions up on [outlook-vba] the same question was asked on 13 August. That question references a variation from December that I attempted to answer.
For the December question, I went overboard with a two part answer. The first part was a series of teaching macros that explored the Outlook folder structure and wrote data to text files or Excel workbooks. The second part discussed how to design the extraction process. For this question Siddarth has provided an excellent, succinct answer and then a follow-up to help with the next stage.
What the questioner of every variation appears unable to understand is that showing us what the data looks like on the screen does not tell us what the text or html body looks like. This answer is an attempt to get past that problem.
The macro below is more complicated than Siddarth’s but a lot simpler that those I included in my December answer. There is more that could be added but I think this is enough to start with.
The macro creates a new Excel workbook and outputs selected properties of every email in Inbox to create this worksheet:
Near the top of the macro there is a comment containing eight hashes (#). The statement below that comment must be changed because it identifies the folder in which the Excel workbook will be created.
All other comments containing hashes suggest amendments to adapt the macro to your requirements.
How are the emails from which data is to be extracted identified? Is it the sender, the subject, a string within the body or all of these? The comments provide some help in eliminating uninteresting emails. If I understand the question correctly, an interesting email will have Subject = "Task Completed"
.
The comments provide no help in extracting data from interesting emails but the worksheet shows both the text and html versions of the email body if they are present. My idea is that you can see what the macro will see and start designing the extraction process.
This is not shown in the screen image above but the macro outputs two versions on the text body. The first version is unchanged which means tab, carriage return, line feed are obeyed and any non-break spaces look like spaces. In the second version, I have replaced these codes with the strings [TB], [CR], [LF] and [NBSP] so they are visible. If my understanding is correct, I would expect to see the following within the second text body:
Activity[TAB]Count[CR][LF]Open[TAB]35[CR][LF]HCQA[TAB]42[CR][LF]HCQC[TAB]60[CR][LF]HAbst[TAB]50 45 5 2 2 1[CR][LF] and so on
Extracting the values from the original of this string should not be difficult.
I would try amending my macro to output the extracted values in addition to the email’s properties. Only when I have successfully achieved this change would I attempt to write the extracted data to an existing workbook. I would also move processed emails to a different folder. I have shown where these changes must be made but give no further help. I will respond to a supplementary question if you get to the point where you need this information.
Good luck.
Latest version of macro included within the original text
Option Explicit
Public Sub SaveEmailDetails()
' This macro creates a new Excel workbook and writes to it details
' of every email in the Inbox.
' Lines starting with hashes either MUST be changed before running the
' macro or suggest changes you might consider appropriate.
Dim AttachCount As Long
Dim AttachDtl() As String
Dim ExcelWkBk As Excel.Workbook
Dim FileName As String
Dim FolderTgt As MAPIFolder
Dim HtmlBody As String
Dim InterestingItem As Boolean
Dim InxAttach As Long
Dim InxItemCrnt As Long
Dim PathName As String
Dim ReceivedTime As Date
Dim RowCrnt As Long
Dim SenderEmailAddress As String
Dim SenderName As String
Dim Subject As String
Dim TextBody As String
Dim xlApp As Excel.Application
' The Excel workbook will be created in this folder.
' ######## Replace "C:\DataArea\SO" with the name of a folder on your disc.
PathName = "C:\DataArea\SO"
' This creates a unique filename.
' #### If you use a version of Excel 2003, change the extension to "xls".
FileName = Format(Now(), "yymmdd hhmmss") & ".xlsx"
' Open own copy of Excel
Set xlApp = Application.CreateObject("Excel.Application")
With xlApp
' .Visible = True ' This slows your macro but helps during debugging
.ScreenUpdating = False ' Reduces flash and increases speed
' Create a new workbook
' #### If updating an existing workbook, replace with an
' #### Open workbook statement.
Set ExcelWkBk = xlApp.Workbooks.Add
With ExcelWkBk
' #### None of this code will be useful if you are adding
' #### to an existing workbook. However, it demonstrates a
' #### variety of useful statements.
.Worksheets("Sheet1").Name = "Inbox" ' Rename first worksheet
With .Worksheets("Inbox")
' Create header line
With .Cells(1, "A")
.Value = "Field"
.Font.Bold = True
End With
With .Cells(1, "B")
.Value = "Value"
.Font.Bold = True
End With
.Columns("A").ColumnWidth = 18
.Columns("B").ColumnWidth = 150
End With
End With
RowCrnt = 2
End With
' FolderTgt is the folder I am going to search. This statement says
' I want to seach the Inbox. The value "olFolderInbox" can be replaced
' to allow any of the standard folders to be searched.
' See FindSelectedFolder() for a routine that will search for any folder.
Set FolderTgt = CreateObject("Outlook.Application"). _
GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
' #### Use the following the access a non-default Inbox.
' #### Change "Xxxx" to name of one of your store you want to access.
Set FolderTgt = Session.Folders("Xxxx").Folders("Inbox")
' This examines the emails in reverse order. I will explain why later.
For InxItemCrnt = FolderTgt.Items.Count To 1 Step -1
With FolderTgt.Items.Item(InxItemCrnt)
' A folder can contain several types of item: mail items, meeting items,
' contacts, etc. I am only interested in mail items.
If .Class = olMail Then
' Save selected properties to variables
ReceivedTime = .ReceivedTime
Subject = .Subject
SenderName = .SenderName
SenderEmailAddress = .SenderEmailAddress
TextBody = .Body
HtmlBody = .HtmlBody
AttachCount = .Attachments.Count
If AttachCount > 0 Then
ReDim AttachDtl(1 To 7, 1 To AttachCount)
For InxAttach = 1 To AttachCount
' There are four types of attachment:
' * olByValue 1
' * olByReference 4
' * olEmbeddedItem 5
' * olOLE 6
Select Case .Attachments(InxAttach).Type
Case olByValue
AttachDtl(1, InxAttach) = "Val"
Case olEmbeddeditem
AttachDtl(1, InxAttach) = "Ebd"
Case olByReference
AttachDtl(1, InxAttach) = "Ref"
Case olOLE
AttachDtl(1, InxAttach) = "OLE"
Case Else
AttachDtl(1, InxAttach) = "Unk"
End Select
' Not all types have all properties. This code handles
' those missing properties of which I am aware. However,
' I have never found an attachment of type Reference or OLE.
' Additional code may be required for them.
Select Case .Attachments(InxAttach).Type
Case olEmbeddeditem
AttachDtl(2, InxAttach) = ""
Case Else
AttachDtl(2, InxAttach) = .Attachments(InxAttach).PathName
End Select
AttachDtl(3, InxAttach) = .Attachments(InxAttach).FileName
AttachDtl(4, InxAttach) = .Attachments(InxAttach).DisplayName
AttachDtl(5, InxAttach) = "--"
' I suspect Attachment had a parent property in early versions
' of Outlook. It is missing from Outlook 2016.
On Error Resume Next
AttachDtl(5, InxAttach) = .Attachments(InxAttach).Parent
On Error GoTo 0
AttachDtl(6, InxAttach) = .Attachments(InxAttach).Position
' Class 5 is attachment. I have never seen an attachment with
' a different class and do not see the purpose of this property.
' The code will stop here if a different class is found.
Debug.Assert .Attachments(InxAttach).Class = 5
AttachDtl(7, InxAttach) = .Attachments(InxAttach).Class
Next
End If
InterestingItem = True
Else
InterestingItem = False
End If
End With
' The most used properties of the email have been loaded to variables but
' there are many more properies. Press F2. Scroll down classes until
' you find MailItem. Look through the members and note the name of
' any properties that look useful. Look them up using VB Help.
' #### You need to add code here to eliminate uninteresting items.
' #### For example:
'If SenderEmailAddress <> "[email protected]" Then
' InterestingItem = False
'End If
'If InStr(Subject, "Accounts payable") = 0 Then
' InterestingItem = False
'End If
'If AttachCount = 0 Then
' InterestingItem = False
'End If
' #### If the item is still thought to be interesting I
' #### suggest extracting the required data to variables here.
' #### You should consider moving processed emails to another
' #### folder. The emails are being processed in reverse order
' #### to allow this removal of an email from the Inbox without
' #### effecting the index numbers of unprocessed emails.
If InterestingItem Then
With ExcelWkBk
With .Worksheets("Inbox")
' #### This code creates a dividing row and then
' #### outputs a property per row. Again it demonstrates
' #### statements that are likely to be useful in the final
' #### version
' Create dividing row between emails
.Rows(RowCrnt).RowHeight = 5
.Range(.Cells(RowCrnt, "A"), .Cells(RowCrnt, "B")) _
.Interior.Color = RGB(0, 255, 0)
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Sender name"
.Cells(RowCrnt, "B").Value = SenderName
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Sender email address"
.Cells(RowCrnt, "B").Value = SenderEmailAddress
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Received time"
With .Cells(RowCrnt, "B")
.NumberFormat = "@"
.Value = Format(ReceivedTime, "mmmm d, yyyy h:mm")
End With
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Subject"
.Cells(RowCrnt, "B").Value = Subject
RowCrnt = RowCrnt + 1
If AttachCount > 0 Then
.Cells(RowCrnt, "A").Value = "Attachments"
.Cells(RowCrnt, "B").Value = "Inx|Type|Path name|File name|Display name|Parent|Position|Class"
RowCrnt = RowCrnt + 1
For InxAttach = 1 To AttachCount
.Cells(RowCrnt, "B").Value = InxAttach & "|" & _
AttachDtl(1, InxAttach) & "|" & _
AttachDtl(2, InxAttach) & "|" & _
AttachDtl(3, InxAttach) & "|" & _
AttachDtl(4, InxAttach) & "|" & _
AttachDtl(5, InxAttach) & "|" & _
AttachDtl(6, InxAttach) & "|" & _
AttachDtl(7, InxAttach)
RowCrnt = RowCrnt + 1
Next
End If
If TextBody <> "" Then
' ##### This code was in the original version of the macro
' ##### but I did not find it as useful as the other version of
' ##### the text body. See below
' This outputs the text body with CR, LF and TB obeyed
'With .Cells(RowCrnt, "A")
' .Value = "text body"
' .VerticalAlignment = xlTop
'End With
'With .Cells(RowCrnt, "B")
' ' The maximum size of a cell 32,767
' .Value = Mid(TextBody, 1, 32700)
' .WrapText = True
'End With
'RowCrnt = RowCrnt + 1
' This outputs the text body with NBSP, CR, LF and TB
' replaced by strings.
With .Cells(RowCrnt, "A")
.Value = "text body"
.VerticalAlignment = xlTop
End With
TextBody = Replace(TextBody, Chr(160), "[NBSP]")
TextBody = Replace(TextBody, vbCr, "[CR]")
TextBody = Replace(TextBody, vbLf, "[LF]")
TextBody = Replace(TextBody, vbTab, "[TB]")
With .Cells(RowCrnt, "B")
' The maximum size of a cell 32,767
.Value = Mid(TextBody, 1, 32700)
.WrapText = True
End With
RowCrnt = RowCrnt + 1
End If
If HtmlBody <> "" Then
' ##### This code was in the original version of the macro
' ##### but I did not find it as useful as the other version of
' ##### the html body. See below
' This outputs the html body with CR, LF and TB obeyed
'With .Cells(RowCrnt, "A")
' .Value = "Html body"
' .VerticalAlignment = xlTop
'End With
'With .Cells(RowCrnt, "B")
' .Value = Mid(HtmlBody, 1, 32700)
' .WrapText = True
'End With
'RowCrnt = RowCrnt + 1
' This outputs the html body with NBSP, CR, LF and TB
' replaced by strings.
With .Cells(RowCrnt, "A")
.Value = "Html body"
.VerticalAlignment = xlTop
End With
HtmlBody = Replace(HtmlBody, Chr(160), "[NBSP]")
HtmlBody = Replace(HtmlBody, vbCr, "[CR]")
HtmlBody = Replace(HtmlBody, vbLf, "[LF]")
HtmlBody = Replace(HtmlBody, vbTab, "[TB]")
With .Cells(RowCrnt, "B")
.Value = Mid(HtmlBody, 1, 32700)
.WrapText = True
End With
RowCrnt = RowCrnt + 1
End If
End With
End With
End If
Next
With xlApp
With ExcelWkBk
' Write new workbook to disc
If Right(PathName, 1) <> "\" Then
PathName = PathName & "\"
End If
.SaveAs FileName:=PathName & FileName
.Close
End With
.Quit ' Close our copy of Excel
End With
Set xlApp = Nothing ' Clear reference to Excel
End Sub
Macros not included in original post but which some users of above macro have found useful.
Public Sub FindSelectedFolder(ByRef FolderTgt As MAPIFolder, _
ByVal NameTgt As String, ByVal NameSep As String)
' This routine (and its sub-routine) locate a folder within the hierarchy and
' returns it as an object of type MAPIFolder
' NameTgt The name of the required folder in the format:
' FolderName1 NameSep FolderName2 [ NameSep FolderName3 ] ...
' If NameSep is "|", an example value is "Personal Folders|Inbox"
' FolderName1 must be an outer folder name such as
' "Personal Folders". The outer folder names are typically the names
' of PST files. FolderName2 must be the name of a folder within
' Folder1; in the example "Inbox". FolderName2 is compulsory. This
' routine cannot return a PST file; only a folder within a PST file.
' FolderName3, FolderName4 and so on are optional and allow a folder
' at any depth with the hierarchy to be specified.
' NameSep A character or string used to separate the folder names within
' NameTgt.
' FolderTgt On exit, the required folder. Set to Nothing if not found.
' This routine initialises the search and finds the top level folder.
' FindSelectedSubFolder() is used to find the target folder within the
' top level folder.
Dim InxFolderCrnt As Long
Dim NameChild As String
Dim NameCrnt As String
Dim Pos As Long
Dim TopLvlFolderList As Folders
Set FolderTgt = Nothing ' Target folder not found
Set TopLvlFolderList = _
CreateObject("Outlook.Application").GetNamespace("MAPI").Folders
' Split NameTgt into the name of folder at current level
' and the name of its children
Pos = InStr(NameTgt, NameSep)
If Pos = 0 Then
' I need at least a level 2 name
Exit Sub
End If
NameCrnt = Mid(NameTgt, 1, Pos - 1)
NameChild = Mid(NameTgt, Pos + 1)
' Look for current name. Drop through and return nothing if name not found.
For InxFolderCrnt = 1 To TopLvlFolderList.Count
If NameCrnt = TopLvlFolderList(InxFolderCrnt).Name Then
' Have found current name. Call FindSelectedSubFolder() to
' look for its children
Call FindSelectedSubFolder(TopLvlFolderList.Item(InxFolderCrnt), _
FolderTgt, NameChild, NameSep)
Exit For
End If
Next
End Sub
Public Sub FindSelectedSubFolder(FolderCrnt As MAPIFolder, _
ByRef FolderTgt As MAPIFolder, _
ByVal NameTgt As String, ByVal NameSep As String)
' See FindSelectedFolder() for an introduction to the purpose of this routine.
' This routine finds all folders below the top level
' FolderCrnt The folder to be seached for the target folder.
' NameTgt The NameTgt passed to FindSelectedFolder will be of the form:
' A|B|C|D|E
' A is the name of outer folder which represents a PST file.
' FindSelectedFolder() removes "A|" from NameTgt and calls this
' routine with FolderCrnt set to folder A to search for B.
' When this routine finds B, it calls itself with FolderCrnt set to
' folder B to search for C. Calls are nested to whatever depth are
' necessary.
' NameSep As for FindSelectedSubFolder
' FolderTgt As for FindSelectedSubFolder
Dim InxFolderCrnt As Long
Dim NameChild As String
Dim NameCrnt As String
Dim Pos As Long
' Split NameTgt into the name of folder at current level
' and the name of its children
Pos = InStr(NameTgt, NameSep)
If Pos = 0 Then
NameCrnt = NameTgt
NameChild = ""
Else
NameCrnt = Mid(NameTgt, 1, Pos - 1)
NameChild = Mid(NameTgt, Pos + 1)
End If
' Look for current name. Drop through and return nothing if name not found.
For InxFolderCrnt = 1 To FolderCrnt.Folders.Count
If NameCrnt = FolderCrnt.Folders(InxFolderCrnt).Name Then
' Have found current name.
If NameChild = "" Then
' Have found target folder
Set FolderTgt = FolderCrnt.Folders(InxFolderCrnt)
Else
'Recurse to look for children
Call FindSelectedSubFolder(FolderCrnt.Folders(InxFolderCrnt), _
FolderTgt, NameChild, NameSep)
End If
Exit For
End If
Next
' If NameCrnt not found, FolderTgt will be returned unchanged. Since it is
' initialised to Nothing at the beginning, that will be the returned value.
End Sub
Unfortunately, Dictionary has problems with Model Binding in MVC. Read the full story here. Instead, create a custom model binder to get the Dictionary as a parameter for the controller action.
To solve your requirement, here is the working solution -
First create your ViewModels in following way. PersonModel can have list of RoleModels.
public class PersonModel
{
public List<RoleModel> Roles { get; set; }
public string Name { get; set; }
}
public class RoleModel
{
public string RoleName { get; set;}
public string Description { get; set;}
}
Then have a index action which will be serving basic index view -
public ActionResult Index()
{
return View();
}
Index view will be having following JQuery AJAX POST operation -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click1').click(function (e) {
var jsonObject = {
"Name" : "Rami",
"Roles": [{ "RoleName": "Admin", "Description" : "Admin Role"}, { "RoleName": "User", "Description" : "User Role"}]
};
$.ajax({
url: "@Url.Action("AddUser")",
type: "POST",
data: JSON.stringify(jsonObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
});
});
</script>
<input type="button" value="click1" id="click1" />
Index action posts to AddUser action -
[HttpPost]
public ActionResult AddUser(PersonModel model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
So now when the post happens you can get all the posted data in the model parameter of action.
Update:
For asp.net core, to get JSON data as your action parameter you should add the [FromBody]
attribute before your param name in your controller action. Note: if you're using ASP.NET Core 2.1, you can also use the [ApiController]
attribute to automatically infer the [FromBody] binding source for your complex action method parameters. (Doc)
In your XML for the image view, where you have android:background="@drawable/thumbs_down
change this to android:src="@drawable/thumbs_down"
Currently it is placing that image as the background to the view and not the actual image in it.
There can be many possible reasons for this failure.
Some are listed above. I faced the same issue, it is very hard to find the root cause of the failure.
I will recommend you to check the session timeout for shh from ssh_config file. Try to increase the session timeout and see if it fails again
Not exactly an answer, but I have never heard of a way to do this in Apache itself. I guess it might be possible with an extension module, but I don't know whether one has been written.
One concern is that POST data can be pretty large, and if you don't put some kind of limit on how much is being logged, you might run out of disk space after a while. It's a possible route for hackers to mess with your server.
How about this?
List<string> monValues = Application["mondayValues"] as List<string>;
int sum = monValues.ConvertAll(Convert.ToInt32).Sum();
You can find every file what is created/modified in the last day, use this example:
find /directory -newermt $(date +%Y-%m-%d -d '1 day ago') -type f -print
for finding everything in the last week, use '1 week ago' or '7 day ago' anything you want
In the question above the right answer would be to use Mock
, or to be more precise create_autospec
(because it will add spec to the mock methods of the class you are mocking), the defined spec
on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some
from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch
class MyClass:
@staticmethod
def method(foo, bar):
print(foo)
def something(some_class: MyClass):
arg = 1
# Would fail becuase of wrong parameters passed to methd.
return some_class.method(arg)
def second(some_class: MyClass):
arg = 1
return some_class.unexisted_method(arg)
class TestSomethingTestCase(TestCase):
def test_something_with_autospec(self):
mock = create_autospec(MyClass)
mock.method.return_value = True
# Fails because of signature misuse.
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_something(self):
mock = Mock() # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
mock.method.return_value = True
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
class TestSecondTestCase(TestCase):
def test_second_with_autospec(self):
mock = Mock(spec=MyClass)
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second(self):
mock = Mock()
mock.unexisted_method.return_value = True
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
The test cases with defined spec used fail because methods called from something
and second
functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock
will display.
As a side note there is one more option: use patch.object to mock just the class method which is called with.
The good use cases for patch would be the case when the class is used as inner part of function:
def something():
arg = 1
return MyClass.method(arg)
Then you will want to use patch as a decorator to mock the MyClass.
This error means that file was not found. Either path is wrong or file is not present where you want it to be. Try to access it by entering source address in your browser to check if it really is there. Browse the directories on server to ensure the path is correct. You may even copy and paste the relative path to be certain it is alright.
I had the same problem with one of my projects, however, none of the above helped to solve the warning. I checked the detailed build logfile, I used AsmSpy to verify that I used the correct versions for each project in the affected solution, I double checked the actual entries in each project file - nothing helped.
Eventually it turned out that the problem was a nested dependency of one of the references I had in one project. This reference (A) in turn required a different version of (B) which was referenced directly from all other projects in my solution. Updating the reference in the referenced project solved it.
Solution A
+--Project A
+--Reference A (version 1.1.0.0)
+--Reference B
+--Project B
+--Reference A (version 1.1.0.0)
+--Reference B
+--Reference C
+--Project C
+--Reference X (this indirectly references Reference A, but with e.g. version 1.1.1.0)
Solution B
+--Project A
+--Reference A (version 1.1.1.0)
I hope the above shows what I mean, took my a couple of hours to find out, so hopefully someone else will benefit as well.
String whole = "something";
String first = whole.substring(0, 1);
System.out.println(first);
There's no need to declare new variables in Python. If we're talking about variables in functions or modules, no declaration is needed. Just assign a value to a name where you need it: mymagic = "Magic"
. Variables in Python can hold values of any type, and you can't restrict that.
Your question specifically asks about classes, objects and instance variables though. The idiomatic way to create instance variables is in the __init__
method and nowhere else — while you could create new instance variables in other methods, or even in unrelated code, it's just a bad idea. It'll make your code hard to reason about or to maintain.
So for example:
class Thing(object):
def __init__(self, magic):
self.magic = magic
Easy. Now instances of this class have a magic
attribute:
thingo = Thing("More magic")
# thingo.magic is now "More magic"
Creating variables in the namespace of the class itself leads to different behaviour altogether. It is functionally different, and you should only do it if you have a specific reason to. For example:
class Thing(object):
magic = "Magic"
def __init__(self):
pass
Now try:
thingo = Thing()
Thing.magic = 1
# thingo.magic is now 1
Or:
class Thing(object):
magic = ["More", "magic"]
def __init__(self):
pass
thing1 = Thing()
thing2 = Thing()
thing1.magic.append("here")
# thing1.magic AND thing2.magic is now ["More", "magic", "here"]
This is because the namespace of the class itself is different to the namespace of the objects created from it. I'll leave it to you to research that a bit more.
The take-home message is that idiomatic Python is to (a) initialise object attributes in your __init__
method, and (b) document the behaviour of your class as needed. You don't need to go to the trouble of full-blown Sphinx-level documentation for everything you ever write, but at least some comments about whatever details you or someone else might need to pick it up.
For those like me who wonder how legacy apps are treated, I did a bit of testing and computation on the subject.
Thanks to @hannes-sverrisson hint, I started on the assumption that a legacy app is treated with a 320x568 view in iPhone 6 and iPhone 6 plus.
The test was made with a simple black background [email protected]
with a white border. The background has a size of 640x1136 pixels, and it is black with an inner white border of 1 pixel.
Below are the screenshots provided by the simulator:
On the iPhone 6 screenshot, we can see a 1 pixel margin on top and bottom of the white border, and a 2 pixel margin on the iPhone 6 plus screenshot. This gives us a used space of 1242x2204 on iPhone 6 plus, instead of 1242x2208, and 750x1332 on the iPhone 6, instead of 750x1334.
We can assume that those dead pixels are meant to respect the iPhone 5 aspect ratio:
iPhone 5 640 / 1136 = 0.5634
iPhone 6 (used) 750 / 1332 = 0.5631
iPhone 6 (real) 750 / 1334 = 0.5622
iPhone 6 plus (used) 1242 / 2204 = 0.5635
iPhone 6 plus (real) 1242 / 2208 = 0.5625
Second, it is important to know that @2x resources will be scaled not only on iPhone 6 plus (which expects @3x assets), but also on iPhone 6. This is probably because not scaling the resources would have led to unexpected layouts, due to the enlargement of the view.
However, that scaling is not equivalent in width and height. I tried it with a 264x264 @2x resource. Given the results, I have to assume that the scaling is directly proportional to the pixels / points ratio.
Device Width scale Computed width Screenshot width
iPhone 5 640 / 640 = 1.0 264 px
iPhone 6 750 / 640 = 1.171875 309.375 309 px
iPhone 6 plus 1242 / 640 = 1.940625 512.325 512 px
Device Height scale Computed height Screenshot height
iPhone 5 1136 / 1136 = 1.0 264 px
iPhone 6 1332 / 1136 = 1.172535 309.549 310 px
iPhone 6 plus 2204 / 1136 = 1.940141 512.197 512 px
It's important to note the iPhone 6 scaling is not the same in width and height (309x310). This tends to confirm the above theory that scaling is not proportional in width and height, but uses the pixels / points ratio.
I hope this helps.
String.format()
to the rescue!!
I just wanted to use the import
and export
in JavaScript files.
Everyone says it's not possible. But, as of May 2018, it's possible to use above in plain Node.js, without any modules like Babel, etc.
Here is a simple way to do it.
Create the below files, run, and see the output for yourself.
Also don't forget to see Explanation
below.
function myFunc() {
console.log("Hello from myFunc")
}
export default myFunc;
import myFunc from "./myfile.mjs" // Simply using "./myfile" may not work in all resolvers
myFunc();
node --experimental-modules index.mjs
(node:12020) ExperimentalWarning: The ESM module loader is experimental.
Hello from myFunc
Explanation:
--experimental-modules
to the node index.mjs
node --version
, it gives me "v10.3.0", though the LTE/stable/recommended version is 8.11.2 LTS.Notepad++ also handles multiple cursors now.
Go into Settings => Preferences => Editing and check "Enable" in "Multi editing settings" Then, just use Ctrl+click to use multiple cursors.
Feature demo on official website here : https://npp-user-manual.org/docs/editing/
A bit reversed, but this should work:
def foo():
foo.counter += 1
print "Counter is %d" % foo.counter
foo.counter = 0
If you want the counter initialization code at the top instead of the bottom, you can create a decorator:
def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
Then use the code like this:
@static_vars(counter=0)
def foo():
foo.counter += 1
print "Counter is %d" % foo.counter
It'll still require you to use the foo.
prefix, unfortunately.
(Credit: @ony)
Char
has a fixed length (supports 2000 characters), it is stand for character is a data type
Varchar
has a variable length (supports 4000 characters)
I was also looking for the global .gitconfig
on my Windows machine and found this neat trick using git.
Do a: git config --global -e
and then, if you are lucky, you will get a text editor loaded with your global .gitconfig
file. Simply lookup the folder from there (or try a save as...), et voilà! :-)
I was looking for the same thing and I've just seen that MySQL 5.6 has a couple of new string functions supporting this functionality: TO_BASE64 and FROM_BASE64.
You should add AutoPostBack="true" to DropDownList1
<asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
DataSourceID="Sql_fur_model_manu"
DataTextField="manufacturer" DataValueField="manufacturer"
onselectedindexchanged="ddmanu_SelectedIndexChanged">
</asp:DropDownList>
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.
Use cursors.
A cursor can be thought of like a buffered reader, when reading through a document. If you think of each row as a line in a document, then you would read the next line, perform your operations, and then advance the cursor.
Here's how I test javascript using PhantomJS and Django:
mobile/test_no_js_errors.js:
var page = require('webpage').create(),
system = require('system'),
url = system.args[1],
status_code;
page.onError = function (msg, trace) {
console.log(msg);
trace.forEach(function(item) {
console.log(' ', item.file, ':', item.line);
});
};
page.onResourceReceived = function(resource) {
if (resource.url == url) {
status_code = resource.status;
}
};
page.open(url, function (status) {
if (status == "fail" || status_code != 200) {
console.log("Error: " + status_code + " for url: " + url);
phantom.exit(1);
}
phantom.exit(0);
});
mobile/tests.py:
import subprocess
from django.test import LiveServerTestCase
class MobileTest(LiveServerTestCase):
def test_mobile_js(self):
args = ["phantomjs", "mobile/test_no_js_errors.js", self.live_server_url]
result = subprocess.check_output(args)
self.assertEqual(result, "") # No result means no error
Run tests:
manage.py test mobile
Turns out that a simple hidden input field does the job:
<input type="hidden" id="dp" />
And then use the buttonImage attribute for your image, like normal:
$("#dp").datepicker({
buttonImage: '../images/icon_star.gif',
buttonImageOnly: true,
changeMonth: true,
changeYear: true,
showOn: 'both',
});
Initially I tried a text input field and then set a display:none
style on it, but that caused the calendar to emerge from the top of the browser, rather than from where the user clicked. But the hidden field works as desired.
I had a simular issue and resolved it using android:adjustViewBounds="true"
on the ImageView.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/banner_alt"
android:src="@drawable/banner_portrait" />
you may check from a python notebook cell as follows
!pip install --upgrade nltk # needed if nltk is not already installed
import nltk
print('The nltk version is {}.'.format(nltk.__version__))
print('The nltk version is '+ str(nltk.__version__))
and
#!pip install --upgrade sklearn # needed if sklearn is not already installed
import sklearn
print('The scikit-learn version is {}.'.format(sklearn.__version__))
print('The scikit-learn version is '+ str(nltk.__version__))
Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head.
I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have SomeClass.doSomething()
than SomeClass.do_something()
. If you look around in the global module index in python, you will find both, which is due to the fact that it's a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it's just a question of personal taste.
With netcat
you can check whether a port is open like this:
nc my.example.com 80 < /dev/null
The return value of nc
will be success if the TCP port was opened, and failure (typically the return code 1) if it could not make the TCP connection.
Some versions of nc
will hang when you try this, because they do not close the sending half of their socket even after receiving the end-of-file from /dev/null
. On my own Ubuntu laptop (18.04), the netcat-openbsd
version of netcat that I have installed offers a workaround: the -N
option is necessary to get an immediate result:
nc -N my.example.com 80 < /dev/null
Yes, very right that the -R
option in chmod
command makes the files/sub-directories under the given directory will get 777 permission. But generally, it's not a good practice to give 777 to all files and dirs as it can lead to data insecurity. Try to be very specific on giving all rights to all files and directories. And to answer your question:
chmod -R 777 your_directory_name
... will work
I prefer to have symlinks in the home directory, in this case at least. Here's how I have things setup:
: cat ~/.bash_profile | grep PATH
# places ~/bin first in PATH
export PATH=~/bin:$PATH
So I symlinked to the VSCode binary like so:
ln -s /Applications/Visual\ Studio\ Code.app/Contents/Resources/app/bin/code ~/bin/code
Now I can issue code .
in whichever directory I desire.
I had run into a similar issue with terminal not updating the java version to match the version installed on the mac.
There was no issue with the JAVA_HOME environmental variable being set
I have come up with a temporary and somewhat painful but working solution.
In you .bash_profile add the line:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_11.jdk/Contents/Home"
(This is the path on my machine but may be different on yours, make sure to get yours. The paths should match up to /Library/Java/JavaVirtualMachines/)
the run source ~/.bash_profile
As I mentioned this is a temporary band-aid solution because the java home path is being hard-coded. There is really no way to set the path to get the latest as that is what Apple is supposedly doing for terminal already and the issue is that Apple's java_home environment variable is not getting updated.
I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable and the underlying data was a IEnumerable and the properties couldn't be enumerated. This did the trick:
// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
List<IDataRecord> list = data.Cast<IDataRecord>().ToList();
PropertyDescriptorCollection props = null;
DataTable table = new DataTable();
if (list != null && list.Count > 0)
{
props = TypeDescriptor.GetProperties(list[0]);
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
}
if (props != null)
{
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(values);
}
}
return table;
}
You can use move
for this. The documentation from help move
states:
Moves files and renames files and directories.
To move one or more files:
MOVE [/Y | /-Y] [drive:][path]filename1[,...] destination
To rename a directory:
MOVE [/Y | /-Y] [drive:][path]dirname1 dirname2
[drive:][path]filename1 Specifies the location and name of the file
or files you want to move.
destination Specifies the new location of the file. Destination
can consist of a drive letter and colon, a
directory name, or a combination. If you are moving
only one file, you can also include a filename if
you want to rename the file when you move it.
[drive:][path]dirname1 Specifies the directory you want to rename.
dirname2 Specifies the new name of the directory.
/Y Suppresses prompting to confirm you want to
overwrite an existing destination file.
/-Y Causes prompting to confirm you want to overwrite
an existing destination file.
The switch /Y may be present in the COPYCMD environment variable.
This may be overridden with /-Y on the command line. Default is
to prompt on overwrites unless MOVE command is being executed from
within a batch script.
See the following transcript for an example where it initially shows the qq1
and qq2
directories as having three and no files respectively. Then, we do the move
and we find that the three files have been moved from qq1
to qq2
as expected.
C:\Documents and Settings\Pax\My Documents>dir qq1
Volume in drive C is Primary
Volume Serial Number is 04F7-0E7B
Directory of C:\Documents and Settings\Pax\My Documents\qq1
20/01/2011 11:36 AM <DIR> .
20/01/2011 11:36 AM <DIR> ..
20/01/2011 11:36 AM 13 xx1
20/01/2011 11:36 AM 13 xx2
20/01/2011 11:36 AM 13 xx3
3 File(s) 39 bytes
2 Dir(s) 20,092,547,072 bytes free
C:\Documents and Settings\Pax\My Documents>dir qq2
Volume in drive C is Primary
Volume Serial Number is 04F7-0E7B
Directory of C:\Documents and Settings\Pax\My Documents\qq2
20/01/2011 11:36 AM <DIR> .
20/01/2011 11:36 AM <DIR> ..
0 File(s) 0 bytes
2 Dir(s) 20,092,547,072 bytes free
C:\Documents and Settings\Pax\My Documents>move qq1\* qq2
C:\Documents and Settings\Pax\My Documents\qq1\xx1
C:\Documents and Settings\Pax\My Documents\qq1\xx2
C:\Documents and Settings\Pax\My Documents\qq1\xx3
C:\Documents and Settings\Pax\My Documents>dir qq1
Volume in drive C is Primary
Volume Serial Number is 04F7-0E7B
Directory of C:\Documents and Settings\Pax\My Documents\qq1
20/01/2011 11:37 AM <DIR> .
20/01/2011 11:37 AM <DIR> ..
0 File(s) 0 bytes
2 Dir(s) 20,092,547,072 bytes free
C:\Documents and Settings\Pax\My Documents>dir qq2
Volume in drive C is Primary
Volume Serial Number is 04F7-0E7B
Directory of C:\Documents and Settings\Pax\My Documents\qq2
20/01/2011 11:37 AM <DIR> .
20/01/2011 11:37 AM <DIR> ..
20/01/2011 11:36 AM 13 xx1
20/01/2011 11:36 AM 13 xx2
20/01/2011 11:36 AM 13 xx3
3 File(s) 39 bytes
2 Dir(s) 20,092,547,072 bytes free
You can not "attach" a SASS/SCSS file to an HTML document.
SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.
There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.
It's as simple as adding 2 lines of code to your HTML file.
<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>
You can use pconf: https://www.npmjs.com/package/pconf
Example:
var Config = require("pconf");
var testConfig = new Config("testConfig");
testConfig.onload = function(){
testConfig.setValue("test", 1);
testConfig.getValue("test");
//testConfig.saveConfig(); Not needed
}
This question has appeared often when searching for a similar problem, so I feel a fully implemented solution is warranted. Especially since I (and I would assume others) have struggled piecing all the various answers together.
Below is a sample Makefile which supports multiple build types in separate directories. The example illustrated shows debug and release builds.
Supports ...
#
# Compiler flags
#
CC = gcc
CFLAGS = -Wall -Werror -Wextra
#
# Project files
#
SRCS = file1.c file2.c file3.c file4.c
OBJS = $(SRCS:.c=.o)
EXE = exefile
#
# Debug build settings
#
DBGDIR = debug
DBGEXE = $(DBGDIR)/$(EXE)
DBGOBJS = $(addprefix $(DBGDIR)/, $(OBJS))
DBGCFLAGS = -g -O0 -DDEBUG
#
# Release build settings
#
RELDIR = release
RELEXE = $(RELDIR)/$(EXE)
RELOBJS = $(addprefix $(RELDIR)/, $(OBJS))
RELCFLAGS = -O3 -DNDEBUG
.PHONY: all clean debug prep release remake
# Default build
all: prep release
#
# Debug rules
#
debug: $(DBGEXE)
$(DBGEXE): $(DBGOBJS)
$(CC) $(CFLAGS) $(DBGCFLAGS) -o $(DBGEXE) $^
$(DBGDIR)/%.o: %.c
$(CC) -c $(CFLAGS) $(DBGCFLAGS) -o $@ $<
#
# Release rules
#
release: $(RELEXE)
$(RELEXE): $(RELOBJS)
$(CC) $(CFLAGS) $(RELCFLAGS) -o $(RELEXE) $^
$(RELDIR)/%.o: %.c
$(CC) -c $(CFLAGS) $(RELCFLAGS) -o $@ $<
#
# Other rules
#
prep:
@mkdir -p $(DBGDIR) $(RELDIR)
remake: clean all
clean:
rm -f $(RELEXE) $(RELOBJS) $(DBGEXE) $(DBGOBJS)
Can't you just set left
to 50%
and then have margin-left
set to -25px
to account for it's width: http://jsfiddle.net/9AbYc/
.hero:after {
content:'';
position: absolute;
top: 100%;
left: 50%;
margin-left: -50px;
width: 0;
height: 0;
border-top: solid 50px #e15915;
border-left: solid 50px transparent;
border-right: solid 50px transparent;
}
or if you needed a variable width you could use: http://jsfiddle.net/9AbYc/1/
.hero:after {
content:'';
position: absolute;
top: 100%;
left: 0;
right: 0;
margin: 0 auto;
width: 0;
height: 0;
border-top: solid 50px #e15915;
border-left: solid 50px transparent;
border-right: solid 50px transparent;
}
According to WWDC2015 Distribution Whats New
Setting "ITSAppUsesNonExemptEncryption" to "NO" in info.plist works fine. if no cryptographic content in your app.
I had got this pop up During selecting build for internal testing i didn't included "ITSAppUsesNonExemptEncryption" key in my info.plist but still worked for me.
Even i successfully uploaded new application didn't included "ITSEncryptionExportComplianceCode" and "ITSAppUsesNonExemptEncryption" keys.
Also Apple Doc.
Important: If your app requires that you provide additional documents for the encryption review, your app won’t have the Ready for Sale status on the store until Export Compliance has reviewed and approved your documents. The app can’t be distributed for prerelease testing until Export Compliance has reviewed and approved it.
If your app is not using encryption and you don’t want to have to answer these questions at the time of submission, you can provide export compliance information with your build. You can also provide new or updated documentation via iTunes Connect to receive the appropriate key string value to include with your build before uploading it to iTunes Connect.
To add export compliance documentation in iTunes Connect:
Go to the Encryption section under Features. Click the plus sign next to the appropriate platform section. Answer the questions appropriately. Attach the file when prompted. Click Save. Your documents will then be sent for review immediately and the status of your document will show in Compliance Review. A key value will also be generated automatically that you can include in your Info.plist file. For more information on including the key value with your build, see the Resources and Help section Trade Compliance.
You can upload a build without an export compliance key. If you include a key, it can indicate that you do not need export compliance documentation; this requires no approval. If you include a key that references a specific export compliance document, that document must be approved; it cannot be in In Review or Rejected.
You can review your answers at any time by clicking the document file name and selecting More Information. If you need to update your documentation or change any of the answers to the questions, you will need to repeat the steps above to add a new document that corresponds with your changes.
This is similar to the solution referred by Mark Heath but with not as much code to just create a very basic button, without the built-in mouse over animation effect. It preserves a simple mouse over effect of showing the button border in black.
The style can be inserted into the Window.Resources or UserControl.Resources section for example (as shown).
<UserControl.Resources>
<!-- This style is used for buttons, to remove the WPF default 'animated' mouse over effect -->
<Style x:Key="MyButtonStyle" TargetType="Button">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Margin" Value="5"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="border"
BorderThickness="1"
Padding="4,2"
BorderBrush="DarkGray"
CornerRadius="3"
Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="BorderBrush" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<!-- usage in xaml -->
<Button Style="{StaticResource MyButtonStyle}">Hello!</Button>
This is because of
String outStr = obj.toString("UTF-8");
Send the byte[]
which you can get from your ByteArrayOutputStream
and use it as such in your ByteArrayInputStream
to construct your GZIPInputStream
. Following are the changes which need to be done in your code.
byte[] compressed = compress(string); //In the main method
public static byte[] compress(String str) throws Exception {
...
...
return obj.toByteArray();
}
public static String decompress(byte[] bytes) throws Exception {
...
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
...
}
Solution Steps:
Unchecked "Automatically manage signing".
Select "Provisioning profile" in "Signing (Release)" section.
No signing certificate error will be show.
Then below the error has a "Manage Certificates" button. click the button.
Old question, but some of us are in git-posh
(powershell). This is the solution for that:
git ls-files -ci --exclude-standard | foreach { git rm --cached $_ }
public class Class1
{
private void btn_click(object sender, EventArgs e)
{
ServerRequest sr = new ServerRequest();
sr.Callback += new ServerRequest.CallbackEventHandler(sr_Callback);
sr.DoRequest("myrequest");
}
void sr_Callback(string something)
{
}
}
public class ServerRequest
{
public delegate void CallbackEventHandler(string something);
public event CallbackEventHandler Callback;
public void DoRequest(string request)
{
// do stuff....
if (Callback != null)
Callback("bla");
}
}
const express = require('express')
const bodyParser = require('body-parser')
const { usersNdJobs, userByJob, addUser , addUserToCompany } = require ('./db/db.js')
const app = express()
app.set('view engine', 'pug')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.get('/', (req, res) => {
usersNdJobs()
.then((users) => {
res.render('users', { users })
})
.catch(console.error)
})
app.get('/api/company/users', (req, res) => {
const companyname = req.query.companyName
console.log(companyname)
userByJob(companyname)
.then((users) => {
res.render('job', { users })
}).catch(console.error)
})
app.post('/api/users/add', (req, res) => {
const userName = req.body.userName
const jobName = req.body.jobName
console.log("user name = "+userName+", job name : "+jobName)
addUser(userName, jobName)
.then((result) => {
res.status(200).json(result)
})
.catch((error) => {
res.status(404).json({ 'message': error.toString() })
})
})
app.post('/users/add', (request, response) => {
const { userName, job } = request.body
addTeam(userName, job)
.then((user) => {
response.status(200).json({
"userName": user.name,
"city": user.job
})
.catch((err) => {
request.status(400).json({"message": err})
})
})
app.post('/api/user/company/add', (req, res) => {
const userName = req.body.userName
const companyName = req.body.companyName
console.log(userName, companyName)
addUserToCompany(userName, companyName)
.then((result) => {
res.json(result)
})
.catch(console.error)
})
app.get('/api/company/user', (req, res) => {
const companyname = req.query.companyName
console.log(companyname)
userByJob(companyname)
.then((users) => {
res.render('jobs', { users })
})
})
app.listen(3000, () =>
console.log('Example app listening on port 3000!')
)
You can specify gradients for colours in certain circumstances in CSS3, and of course borders can be set to a colour, so you should be able to use a gradient as a border colour. This would include the option of specifying a transparent colour, which means you should be able to achieve the effect you're after.
However, I've never seen it used, and I don't know how well supported it is by current browsers. You'll certainly need to accept that at least some of your users won't be able to see it.
A quick google turned up these two pages which should help you on your way:
Hope that helps.
Building on @Michael Kropat's answer I added a parameter to prepend the new path to the existing PATH
variable and a check to avoid the addition of a non-existing path:
function Add-EnvPath {
param(
[Parameter(Mandatory=$true)]
[string] $Path,
[ValidateSet('Machine', 'User', 'Session')]
[string] $Container = 'Session',
[Parameter(Mandatory=$False)]
[Switch] $Prepend
)
if (Test-Path -path "$Path") {
if ($Container -ne 'Session') {
$containerMapping = @{
Machine = [EnvironmentVariableTarget]::Machine
User = [EnvironmentVariableTarget]::User
}
$containerType = $containerMapping[$Container]
$persistedPaths = [Environment]::GetEnvironmentVariable('Path', $containerType) -split ';'
if ($persistedPaths -notcontains $Path) {
if ($Prepend) {
$persistedPaths = ,$Path + $persistedPaths | where { $_ }
[Environment]::SetEnvironmentVariable('Path', $persistedPaths -join ';', $containerType)
}
else {
$persistedPaths = $persistedPaths + $Path | where { $_ }
[Environment]::SetEnvironmentVariable('Path', $persistedPaths -join ';', $containerType)
}
}
}
$envPaths = $env:Path -split ';'
if ($envPaths -notcontains $Path) {
if ($Prepend) {
$envPaths = ,$Path + $envPaths | where { $_ }
$env:Path = $envPaths -join ';'
}
else {
$envPaths = $envPaths + $Path | where { $_ }
$env:Path = $envPaths -join ';'
}
}
}
}
We can use either Pattern.compile("[0-9]+.[0-9]+")
or Pattern.compile("\\d+.\\d+")
. They have the same meaning.
the pattern [0-9] means digit. The same as '\d'. '+' means it appears more times. '.' for integer or float.
Try following code:
import java.util.regex.Pattern;
public class PatternSample {
public boolean containNumbersOnly(String source){
boolean result = false;
Pattern pattern = Pattern.compile("[0-9]+.[0-9]+"); //correct pattern for both float and integer.
pattern = Pattern.compile("\\d+.\\d+"); //correct pattern for both float and integer.
result = pattern.matcher(source).matches();
if(result){
System.out.println("\"" + source + "\"" + " is a number");
}else
System.out.println("\"" + source + "\"" + " is a String");
return result;
}
public static void main(String[] args){
PatternSample obj = new PatternSample();
obj.containNumbersOnly("123456.a");
obj.containNumbersOnly("123456 ");
obj.containNumbersOnly("123456");
obj.containNumbersOnly("0123456.0");
obj.containNumbersOnly("0123456a.0");
}
}
Output:
"123456.a" is a String
"123456 " is a String
"123456" is a number
"0123456.0" is a number
"0123456a.0" is a String
I created an enhanced version, based on Trey Copland's fiddle, that I think is more like what you wanted. Added here for future reference to those who come here later. Fiddle example
<body>
<style>
.modal {
height: 390px;
border: 5px solid green;
}
.heading {
padding: 10px;
}
.content {
height: 300px;
overflow:auto;
border: 5px solid red;
}
.scrollable {
height: 1200px;
border: 5px solid yellow;
}
.footer {
height: 2em;
padding: .5em;
}
</style>
<div class="modal">
<div class="heading">
<h4>Heading</h4>
</div>
<div class="content">
<div class="scrollable" >hello</div>
</div>
<div class="footer">
Footer
</div>
</div>
</body>
If you want to truncate by a number of words and add an ellipsis you can use this function:
truncate(value: string, limit: number = 40, trail: String = '…'): string {
let result = value || '';
if (value) {
const words = value.split(/\s+/);
if (words.length > Math.abs(limit)) {
if (limit < 0) {
limit *= -1;
result = trail + words.slice(words.length - limit, words.length).join(' ');
} else {
result = words.slice(0, limit).join(' ') + trail;
}
}
}
return result;
}
Example:
truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 5, '…')
> "Bacon ipsum dolor amet sirloin…"
taken from: https://github.com/yellowspot/ng2-truncate/blob/master/src/truncate-words.pipe.ts
If you want to truncate by a number of letters but don't cut words out use this:
truncate(value: string, limit = 25, completeWords = true, ellipsis = '…') {
let lastindex = limit;
if (completeWords) {
lastindex = value.substr(0, limit).lastIndexOf(' ');
}
return `${value.substr(0, limit)}${ellipsis}`;
}
Example:
truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 19, true, '…')
> "Bacon ipsum dolor…"
truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 19, false, '…')
> "Bacon ipsum dolor a…"
Here's a way that I consider easier: The general idea is that you want to append a text element to a circle element then play around with its "dx" and "dy" attributes until you position the text at the point in the circle that you like. In my example, I used a negative number for the dx since I wanted to have text start towards the left of the centre.
const nodes = [ {id: ABC, group: 1, level: 1}, {id:XYZ, group: 2, level: 1}, ]
const nodeElems = svg.append('g')
.selectAll('circle')
.data(nodes)
.enter().append('circle')
.attr('r',radius)
.attr('fill', getNodeColor)
const textElems = svg.append('g')
.selectAll('text')
.data(nodes)
.enter().append('text')
.text(node => node.label)
.attr('font-size',8)//font size
.attr('dx', -10)//positions text towards the left of the center of the circle
.attr('dy',4)
I do something like this :
all_lines = ""
ARGV.each do |line|
all_lines << line + "\n"
end
puts all_lines
if you wish to hide URL from the user, Show an AlertDialog as below.
myWebView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d(TAG, "onJsAlert url: " + url + "; message: " + message);
AlertDialog.Builder builder = new AlertDialog.Builder(
mContext);
builder.setMessage(message)
.setNeutralButton("OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
}).show();
result.cancel();
return true;
}
}
var app = angular.module('myApp', []);_x000D_
app.controller('myCtrl', function($scope) {_x000D_
_x000D_
$scope.minus = function() { _x000D_
_x000D_
var a = Number($scope.a || 0);_x000D_
var b = Number($scope.b || 0);_x000D_
$scope.sum1 = a-b;_x000D_
// $scope.sum = $scope.sum1+1; _x000D_
alert($scope.sum1);_x000D_
}_x000D_
_x000D_
$scope.add = function() { _x000D_
_x000D_
var c = Number($scope.c || 0);_x000D_
var d = Number($scope.d || 0);_x000D_
$scope.sum2 = c+d;_x000D_
alert($scope.sum2);_x000D_
}_x000D_
});
_x000D_
<head>_x000D_
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
<h3>Using Double Negation</h3>_x000D_
_x000D_
<p>First Number:_x000D_
<input type="text" ng-model="a" />_x000D_
</p>_x000D_
<p>Second Number:_x000D_
<input type="text" ng-model="b" />_x000D_
</p>_x000D_
<button id="minus" ng-click="minus()">Minus</button>_x000D_
<!-- <p>Sum: {{ a - b }}</p> -->_x000D_
<p>Sum: {{ sum1 }}</p>_x000D_
_x000D_
<p>First Number:_x000D_
<input type="number" ng-model="c" />_x000D_
</p>_x000D_
<p>Second Number:_x000D_
<input type="number" ng-model="d" />_x000D_
</p>_x000D_
<button id="minus" ng-click="add()">Add</button>_x000D_
<p>Sum: {{ sum2 }}</p>_x000D_
</div>
_x000D_
There is no need to install Anaconda again. Conda, the package manager for Anaconda, fully supports separated environments. The easiest way to create an environment for Python 2.7 is to do
conda create -n python2 python=2.7 anaconda
This will create an environment named python2
that contains the Python 2.7 version of Anaconda. You can activate this environment with
source activate python2
This will put that environment (typically ~/anaconda/envs/python2
) in front in your PATH
, so that when you type python
at the terminal it will load the Python from that environment.
If you don't want all of Anaconda, you can replace anaconda
in the command above with whatever packages you want. You can use conda
to install packages in that environment later, either by using the -n python2
flag to conda
, or by activating the environment.
In Internet Explorer, parentElement
is undefined for SVG elements, whereas parentNode
is defined.
Two likely definitions:
getActivity()
in a Fragment
returns the Activity
the Fragment
is currently associated with. (see http://developer.android.com/reference/android/app/Fragment.html#getActivity()).getActivity()
is user-defined.Following code calculates Palidrom for even length and odd length strings.
Not the best solution but works for both the cases
HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE HYTBCABADEFGHABCDEDCBAGHTFYW1234567887654321ZWETYGDE
private static String getLongestPalindrome(String string) {
String odd = getLongestPalindromeOdd(string);
String even = getLongestPalindromeEven(string);
return (odd.length() > even.length() ? odd : even);
}
public static String getLongestPalindromeOdd(final String input) {
int rightIndex = 0, leftIndex = 0;
String currentPalindrome = "", longestPalindrome = "";
for (int centerIndex = 1; centerIndex < input.length() - 1; centerIndex++) {
leftIndex = centerIndex;
rightIndex = centerIndex + 1;
while (leftIndex >= 0 && rightIndex < input.length()) {
if (input.charAt(leftIndex) != input.charAt(rightIndex)) {
break;
}
currentPalindrome = input.substring(leftIndex, rightIndex + 1);
longestPalindrome = currentPalindrome.length() > longestPalindrome
.length() ? currentPalindrome : longestPalindrome;
leftIndex--;
rightIndex++;
}
}
return longestPalindrome;
}
public static String getLongestPalindromeEven(final String input) {
int rightIndex = 0, leftIndex = 0;
String currentPalindrome = "", longestPalindrome = "";
for (int centerIndex = 1; centerIndex < input.length() - 1; centerIndex++) {
leftIndex = centerIndex - 1;
rightIndex = centerIndex + 1;
while (leftIndex >= 0 && rightIndex < input.length()) {
if (input.charAt(leftIndex) != input.charAt(rightIndex)) {
break;
}
currentPalindrome = input.substring(leftIndex, rightIndex + 1);
longestPalindrome = currentPalindrome.length() > longestPalindrome
.length() ? currentPalindrome : longestPalindrome;
leftIndex--;
rightIndex++;
}
}
return longestPalindrome;
}
$this->db->where('accommodation BETWEEN '' . $sdate . '' AND '' . $edate . ''');
this is my solution
While zolley's answer is perfectly right for the question, here's a more general solution for any range, plus explanation:
=COUNTIF($A$1:$C$50, INDIRECT(ADDRESS(ROW(), COLUMN(), 4))) > 1
Please note that in this example I will be using the range A1:C50
.
The first parameter ($A$1:$C$50
) should be replaced with the range on which you would like to highlight duplicates!
to highlight duplicates:
Format
> Conditional formatting...
Apply to range
, select the range to which the rule should be applied.Format cells if
, select Custom formula is
on the dropdown.Why does it work?
COUNTIF(range, criterion)
, will compare every cell in range
to the criterion
, which is processed similarly to formulas. If no special operators are provided, it will compare every cell in the range with the given cell, and return the number of cells found to be matching the rule (in this case, the comparison). We are using a fixed range (with $
signs) so that we always view the full range.
The second block, INDIRECT(ADDRESS(ROW(), COLUMN(), 4))
, will return current cell's content. If this was placed inside the cell, docs will have cried about circular dependency, but in this case, the formula is evaluated as if it was in the cell, without changing it.
ROW()
and COLUMN()
will return the row number and column number of the given cell respectively. If no parameter is provided, the current cell will be returned (this is 1-based, for example, B3
will return 3 for ROW()
, and 2 for COLUMN()
).
Then we use: ADDRESS(row, column, [absolute_relative_mode])
to translate the numeric row and column to a cell reference (like B3
. Remember, while we are inside the cell's context, we don't know it's address OR content, and we need the content in order to compare with). The third parameter takes care for the formatting, and 4
returns the formatting INDIRECT()
likes.
INDIRECT()
, will take a cell reference and return its content. In this case, the current cell's content. Then back to the start, COUNTIF()
will test every cell in the range against ours, and return the count.
The last step is making our formula return a boolean, by making it a logical expression: COUNTIF(...) > 1
. The > 1
is used because we know there's at least one cell identical to ours. That's our cell, which is in the range, and thus will be compared to itself. So to indicate a duplicate, we need to find 2 or more cells matching ours.
Sources:
If your input rows are lists rather than dictionaries, then the following is a simple solution:
import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])
pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
# A B C
# 0 1 2 3
# 1 4 5 6
In my case, IIS suddenly stoped working, and after that Windows process activation service was unable to restart.
The solution to fix this was:
Hope it will be usefull.
We got it working by copying the routes from Router.php instead of using Auth::routes(), these are the routes you need:
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');
Simply do this:
IF EXISTS (SELECT * FROM tablename)
BEGIN
DELETE from tablename
DBCC checkident ('tablename', reseed, 0)
END
You can use regular old javascript for that:
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
A quick way would be to modify the tux filename so that your move command will not match.
For example:
mv Tux.png .Tux.png
mv * ~/somefolder
mv .Tux.png Tux.png
If you are using Theme then you can the below Syntax
Yii::app()->theme->baseUrl
include CSS File :
<link href="<?php echo Yii::app()->theme->baseUrl;?>/css/bootstrap.css" type="text/css" rel="stylesheet" media="all">
Include JS File
<script src="<?php echo Yii::app()->theme->baseUrl;?>/js/jquery-2.2.3.min.js"></script>
If you are not using theme
Yii::app()->request->baseUrl
Use Like this
<link href="<?php echo Yii::app()->request->baseUrl; ?>/css/bootstrap.css" type="text/css" rel="stylesheet" media="all">
<script src="<?php echo Yii::app()->request->baseUrl; ?>/js/jquery-2.2.3.min.js"></script>
I found the best answer for my purposes was to use:
.topics tr {
overflow: hidden;
height: 14px;
white-space: nowrap;
}
The white-space: nowrap
is important as it prevents your row's cells from breaking across multiple lines.
I personally like to add text-overflow: ellipsis
to my th
and td
elements to make the overflowing text look nicer by adding the trailing fullstops, for example Too long gets dots...
You can simply simply achieve it with any python module that gives you an interaction with command line(cmd
) like subprocess
, os
, etc.
but here I came up with examples on only two modules.
Here is syntax (command) cmd /c start browser_name "URL"
import os
# or open with iexplore
os.system('cmd /c start iexplore "http://your_url"')
# or open with chrome
os.system('cmd /c start chrome "http://your_url"')
__import__('subprocess').getoutput('cmd /c start iexplore "http://your_url"')
You can also run the command in the cmd it will work to or use other module call
click
which mainly used for writing command line utilities.
import click
click.launch('http://your_url')
Add to your panel's style code something like this:
<asp:Panel ID="myPanel" runat="Server" CssClass="myPanelCSS" style="overflow-y:auto; overflow-x:hidden"></asp:Panel>
You have specified different colors for the li elements but it is being overridden by the specified color in the a within the li. Remove color: #C1C1C1; style from a element and it should work.
Implement a function that, given a linked list that may be circular, swaps the first two elements, the third with the fourth, etc...
A more up to date answer for anyone else who comes across this:
(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)
Compile automatically:
To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option
Show all errors in one place:
The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.
Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.
While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.
Example:
import React from 'react';
import PropTypes from 'prop-types';
class MenuItem extends React.Component {
render() {
return (
<li>
<a href={this.props.href}>{this.props.children}</a>
</li>
);
}
}
MenuItem.defaultProps = {
href: "/",
children: "Main page"
};
MenuItem.propTypes = {
href: PropTypes.string.isRequired,
children: PropTypes.string.isRequired
};
export default MenuItem;
Picture: Shows you error in console if the expected type is different
hymloth and sven's answers work, but they do not modify the list (the create a new one). If you need the object modification you need to assign to a slice:
x[:] = [value for value in x if len(value)==2]
However, for large lists in which you need to remove few elements, this is memory consuming, but it runs in O(n).
glglgl's answer suffers from O(n²) complexity, because list.remove
is O(n).
Depending on the structure of your data, you may prefer noting the indexes of the elements to remove and using the del
keywork to remove by index:
to_remove = [i for i, val in enumerate(x) if len(val)==2]
for index in reversed(to_remove): # start at the end to avoid recomputing offsets
del x[index]
Now del x[i]
is also O(n) because you need to copy all elements after index i
(a list is a vector), so you'll need to test this against your data. Still this should be faster than using remove
because you don't pay for the cost of the search step of remove, and the copy step cost is the same in both cases.
[edit] Very nice in-place, O(n) version with limited memory requirements, courtesy of @Sven Marnach. It uses itertools.compress
which was introduced in python 2.7:
from itertools import compress
selectors = (len(s) == 2 for s in x)
for i, s in enumerate(compress(x, selectors)): # enumerate elements of length 2
x[i] = s # move found element to beginning of the list, without resizing
del x[i+1:] # trim the end of the list
To get the IP address and host port of a container:
docker inspect containerId | awk '/IPAddress/ || /HostPort/'
Output:
"HostPort": "4200"
"HostPort": "4200"
"SecondaryIPAddresses": null,
"IPAddress": "172.17.0.2",
"IPAddress": "172.17.0.2",
you can just do $scope.todo = Todo.get({ id: 123 })
. .get()
and .query()
on a Resource return an object immediately and fill it with the result of the promise later (to update your template). It's not a typical promise which is why you need to either use a callback or the $promise property if you have some special code you want executed after the call. But there is no need to assign it to your scope in a callback if you are only using it in the template.
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
We need to remember that the {% endif %}
comes after the {% else %}
.
So this is an example:
{% if someTest %}
<p> Something is True </p>
{% else %}
<p> Something is False </p>
{% endif %}
The exact solution is;
$("#dialogDiv").dialog({ other options...,
open: function (type, data) {
$(this).parent().appendTo("form");
}
});
Googling gives me this:
Command A & Command B
Execute Command A, then execute Command B (no evaluation of anything)
Command A | Command B
Execute Command A, and redirect all its output into the input of Command B
Command A && Command B
Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B
Command A || Command B
Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B
You can use inline styling to limit the height:
<img src="" class="img-responsive" alt="" style="max-height: 400px;">
The following simple code worked for me.
[imageView setContentMode:UIViewContentModeScaleAspectFill];
[imageView setClipsToBounds:YES];