a
is an array local to the function.Once the function returns it does not exist anymore and hence you should not return the address of a local variable.
In other words the lifetime of a
is within the scope({
,}
) of the function and if you return a pointer to it what you have is a pointer pointing to some memory which is not valid. Such variables are also called automatic variabels because their lifetime is automatically managed you do not need to manage it explicitly.
Since you need to extend the variable to persist beyond the scope of the function you You need to allocate a array on heap and return a pointer to it.
char *a = malloc(1000);
This way the array a
resides in memory untill you call a free()
on the same address.
Do not forget to do so or you end up with a memory leak.
/* comment here */
here is an example: SELECT 1 /* this is an in-line comment */ + 1;
Try this.
using System.Xml.Linq;
void Main()
{
StringBuilder result = new StringBuilder();
//Load xml
XDocument xdoc = XDocument.Load("data.xml");
//Run query
var lv1s = from lv1 in xdoc.Descendants("level1")
select new {
Header = lv1.Attribute("name").Value,
Children = lv1.Descendants("level2")
};
//Loop through results
foreach (var lv1 in lv1s){
result.AppendLine(lv1.Header);
foreach(var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
Console.WriteLine(result);
}
In my case, I had created the map, but was missing the ReverseMap function. Adding it got rid of the error.
private static void RegisterServices(ContainerBuilder bldr)
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new CampMappingProfile());
});
...
}
public CampMappingProfile()
{
CreateMap<Talk, TalkModel>().ReverseMap();
...
}
If you are using a screen with filters for example, and you want to set the background of the filter regarding if it was selected or not, you can do:
<TouchableOpacity style={this.props.venueFilters.includes('Bar')?styles.filterBtnActive:styles.filterBtn} onPress={()=>this.setFilter('Bar')}>
<Text numberOfLines={1}>
Bar
</Text>
</TouchableOpacity>
On which set filter is:
setVenueFilter(filter){
var filters = this.props.venueFilters;
filters.push(filter);
console.log(filters.includes('Bar'), "Inclui Bar");
this.setState(previousState => {
return { updateFilter: !previousState.updateFilter };
});
this.props.setVenueFilter(filters);
}
PS: the function this.props.setVenueFilter(filters)
is a redux action, and this.props.venueFilters
is a redux state.
You could store this into a temporary table.
So instead of doing the CTE/sub query you would use a temp table.
Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/
The reason is one servlet container is already running on port 8080 and you are trying to run another one on port 8080.
Check what processes are running at available ports.
For Windows :
netstat -ao |find /i "listening"
OR
netstat -ano | find "8080"
(Note: 8080 is port fail to start)
Now try to reLaunch or stop your application.
Taskkill /F /IM 6592 Note: Mention correct Process Id
right click on the console and select terminate/disconnect all
Task Manager
and end Java(tm) platform se binaryAnother option is :
Go to application.properties
file set server.port=0
. This will cause Spring Boot to use a random free port every time it starts.
Imagine you have a Computer entity, this entity also cannot live without its Software entity and Hardware entity. These form the Computer
aggregate, the mini-ecosystem for the Computer portion of the domain.
Aggregate Root is the mothership entity inside the aggregate (in our case Computer
), it is a common practice to have your repository only work with the entities that are Aggregate Roots, and this entity is responsible for initializing the other entities.
Consider Aggregate Root as an Entry-Point to an Aggregate.
In C# code:
public class Computer : IEntity, IAggregateRoot
{
public Hardware Hardware { get; set; }
public Software Software { get; set; }
}
public class Hardware : IEntity { }
public class Software : IValueObject { }
public class Repository<T> : IRepository<T> where T : IAggregateRoot {}
Keep in mind that Hardware would likely be a ValueObject too (do not have identity on its own), consider it as an example only.
There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.
version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}" # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}" # 7 1
Go to the Properties
of your dateTimePicker
in Visual Studio and set Format
to Custom
. Under CustomFormat
enter your format. In my case I used MMMMdd, yyyy | hh:mm
The reason for nan
, inf
or -inf
often comes from the fact that division by 0.0
in TensorFlow doesn't result in a division by zero exception. It could result in a nan
, inf
or -inf
"value". In your training data you might have 0.0
and thus in your loss function it could happen that you perform a division by 0.0
.
a = tf.constant([2., 0., -2.])
b = tf.constant([0., 0., 0.])
c = tf.constant([1., 1., 1.])
print((a / b) + c)
Output is the following tensor:
tf.Tensor([ inf nan -inf], shape=(3,), dtype=float32)
Adding a small eplison
(e.g., 1e-5
) often does the trick. Additionally, since TensorFlow 2 the opteration tf.math.division_no_nan
is defined.
One more solution REPLACE (CHAR(current date, ISO),'-','')
No, the problem is that *
is a reserved character in regexes, so you need to escape it.
String [] separado = line.split("\\*");
*
means "zero or more of the previous expression" (see the Pattern
Javadocs), and you weren't giving it any previous expression, making your split expression illegal. This is why the error was a PatternSyntaxException
.
Change visible="false"
to style="visibility:hidden"
on your tags..
or better use a class to show/hide the labels..
.hidden{
visibility:hidden;
}
then on your labels add class="hidden"
and with your script remove the class
document.getElementById("endTimeLabel").className = 'hidden'; // to hide
and
document.getElementById("endTimeLabel").className = ''; // to show
If you would like a visual tool with Desktop interface including validation .. you may well like this Excel tool. You can also use the tool to create multi user data-edit tasks, or even paste data to SQL server from any source..
How to Validate and Import Excel spreadsheet to SQL Server database:
A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib
to include all the .jar files in that directory, it won't. You have to name them explicitly.
Returning the function name without ()
returns a reference to the function, which can be assigned as you've done with var s = a()
. s
now contains a reference to the function b()
, and calling s()
is functionally equivalent to calling b()
.
// Return a reference to the function b().
// In your example, the reference is assigned to var s
return b;
Calling the function with ()
in a return statement executes the function, and returns whatever value was returned by the function. It is similar to calling var x = b();
, but instead of assigning the return value of b()
you are returning it from the calling function a()
. If the function b()
itself does not return a value, the call returns undefined
after whatever other work is done by b()
.
// Execute function b() and return its value
return b();
// If b() has no return value, this is equivalent to calling b(), followed by
// return undefined;
I know the question has been answered, but in my case I was trying to send the content of a text file to the Slack Webhook api and for some reason the above answer did not work. Anywho, this is what finally did the trick for me:
curl -X POST -H --silent --data-urlencode "payload={\"text\": \"$(cat file.txt | sed "s/\"/'/g")\"}" https://hooks.slack.com/services/XXX
The only way to determine this is to try it. FWIW I have seen some really good improvements using Apple's LLVM gcc 4.2 compared to the regular gcc 4.2 (for x86-64 code with quite a lot of SSE), but YMMV for different code bases. Assuming you're working with x86/x86-64 and that you really do care about the last few percent then you ought to try Intel's ICC too, as this can often beat gcc - you can get a 30 day evaluation license from intel.com and try it.
Adding context to hopefully help provide a bit of additional clarity on this subject. To a BaSH newbie, it's sense of true/false statements is rather odd. Take the following simple examples and their results.
This statement will return "true":
foo=" "; if [ "$foo" ]; then echo "true"; else echo "false"; fi
But this will return "false":
foo=" "; if [ $foo ]; then echo "true"; else echo "false"; fi
Do you see why? The first example has a quoted "" string. This causes BaSH to treat it literally. So, in a literal sense, a space is not null. While in a non-literal sense (the 2nd example above), a space is viewed by BaSH (as a value in $foo) as 'nothing' and therefore it equates to null (interpreted here as 'false').
These statements will all return a text string of "false":
foo=; if [ $foo ]; then echo "true"; else echo "false"; fi
foo=; if [ "$foo" ]; then echo "true"; else echo "false"; fi
foo=""; if [ $foo ]; then echo "true"; else echo "false"; fi
foo=""; if [ "$foo" ]; then echo "true"; else echo "false"; fi
Interestingly, this type of conditional will always return true:
These statements will all return a result of "true":
foo=""; if [ foo ]; then echo "true"; else echo "false"; fi
Notice the difference; the $ symbol has been omitted from preceding the variable name in the conditional. It doesn't matter what word you insert between the brackets. BaSH will always see this statement as true, even if you use a word that has never been associated with a variable in the same shell before.
if [ sooperduper ]; then echo "true"; else echo "false"; fi
Likewise, defining it as an undeclared variable ensures it will always return false:
if [ $sooperduper ]; then echo "true"; else echo "false"; fi
As to BaSH it's the same as writing:
sooperduper="";if [ $sooperduper ]; then echo "true"; else echo "false"; fi
One more tip....
Brackets vs No Brackets
Making matters more confusing, these variations on the IF/THEN conditional both work, but return opposite results.
These return false:
if [ $foo ]; then echo "true"; else echo "false"; fi
if [ ! foo ]; then echo "true"; else echo "false"; fi
However, these will return a result of true:
if $foo; then echo "true"; else echo "false"; fi
if [ foo ]; then echo "true"; else echo "false"; fi
if [ ! $foo ]; then echo "true"; else echo "false"; fi
And, of course this returns a syntax error (along with a result of 'false'):
if foo; then echo "true"; else echo "false"; fi
Confused yet? It can be quite challenging to keep it straight in your head in the beginning, especially if you're used to other, higher level programming languages.
The one that worked for me is:
grep -e '->'
The -e means that the next argument is the pattern, and won't be interpreted as an argument.
From: http://www.linuxquestions.org/questions/programming-9/how-to-grep-for-string-769460/
__PRETTY_FUNCTION__
handles C++ features: classes, namespaces, templates and overload
main.cpp
#include <iostream>
namespace N {
class C {
public:
template <class T>
static void f(int i) {
(void)i;
std::cout << "__func__ " << __func__ << std::endl
<< "__FUNCTION__ " << __FUNCTION__ << std::endl
<< "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
}
template <class T>
static void f(double f) {
(void)f;
std::cout << "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
}
};
}
int main() {
N::C::f<char>(1);
N::C::f<void>(1.0);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Output:
__func__ f
__FUNCTION__ f
__PRETTY_FUNCTION__ static void N::C::f(int) [with T = char]
__PRETTY_FUNCTION__ static void N::C::f(double) [with T = void]
You may also be interested in stack traces with function names: print call stack in C or C++
Tested in Ubuntu 19.04, GCC 8.3.0.
C++20 std::source_location::function_name
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1208r5.pdf went into C++20, so we have yet another way to do it.
The documentation says:
constexpr const char* function_name() const noexcept;
6 Returns: If this object represents a position in the body of a function, returns an implementation-defined NTBS that should correspond to the function name. Otherwise, returns an empty string.
where NTBS means "Null Terminated Byte String".
I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a
still doesn't support it.
https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:
#include <iostream>
#include <string_view>
#include <source_location>
void log(std::string_view message,
const std::source_location& location std::source_location::current()
) {
std::cout << "info:"
<< location.file_name() << ":"
<< location.line() << ":"
<< location.function_name() << " "
<< message << '\n';
}
int main() {
log("Hello world!");
}
Possible output:
info:main.cpp:16:main Hello world!
so note how this returns the caller information, and is therefore perfect for usage in logging, see also: Is there a way to get function name inside a C++ function?
If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr
function, like this
>>> chr(65)
'A'
similarly if you have 97,
>>> chr(97)
'a'
EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord
and the result has to be converted using unichr
instead of chr
.
>>> print unichr(ord(u'\u0B85'))
?
>>> print unichr(1 + ord(u'\u0B85'))
?
NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf
First, install the URL Rewrite from a download or from the Web Platform Installer. Second, restart IIS. And, finally, close IIS and open again. The last step worked for me.
The compiler may well optimize the second form into the first form, but it doesn't have to.
#include <iostream>
class A
{
public:
A() { std::cerr << "Empty constructor" << std::endl; }
A(const A&) { std::cerr << "Copy constructor" << std::endl; }
A(const char* str) { std::cerr << "char constructor: " << str << std::endl; }
~A() { std::cerr << "destructor" << std::endl; }
};
void direct()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a(__FUNCTION__);
static_cast<void>(a); // avoid warnings about unused variables
}
void assignment()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a = A(__FUNCTION__);
static_cast<void>(a); // avoid warnings about unused variables
}
void prove_copy_constructor_is_called()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a(__FUNCTION__);
A b = a;
static_cast<void>(b); // avoid warnings about unused variables
}
int main()
{
direct();
assignment();
prove_copy_constructor_is_called();
return 0;
}
Output from gcc 4.4:
TEST: direct
char constructor: direct
destructor
TEST: assignment
char constructor: assignment
destructor
TEST: prove_copy_constructor_is_called
char constructor: prove_copy_constructor_is_called
Copy constructor
destructor
destructor
You may can use -Xlinker option.
g++ -o foobar -Xlinker -start-group -Xlinker libA.a -Xlinker libB.a -Xlinker libC.a -Xlinker -end-group
is ALMOST equal to
g++ -o foobar -Xlinker -start-group -Xlinker libC.a -Xlinker libB.a -Xlinker libA.a -Xlinker -end-group
Careful !
Working code, I have used Java Mail 1.4.7 jar
import java.util.Properties;
import javax.activation.*;
import javax.mail.*;
public class MailProjectClass {
public static void main(String[] args) {
final String username = "[email protected]";
final String password = "your.password";
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
String file = "path of file to be attached";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
you use that code
ImageView[] ivCard = new ImageView[1];
@override
protected void onCreate(Bundle savedInstanceState)
ivCard[0]=(ImageView)findViewById(R.id.imageView1);
You can create a Blob
from your base64 data, and then read it asDataURL
:
var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];
var the_file = new Blob([window.atob(png)], {type: 'image/png', encoding: 'utf-8'});
var fr = new FileReader();
fr.onload = function ( oFREvent ) {
var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
v = atob(v);
var good_b64 = btoa(decodeURIComponent(escape(v)));
document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);
Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/
Alternatively, you can use .readAsText
, it works fine, and its more elegant.. but for some reason text does not sound right ;)
fr.onload = function ( oFREvent ) {
document.getElementById("uploadPreview").src = "data:image/png;base64,"
+ btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here
Full example: http://jsfiddle.net/tTYb8/3/
See RFC 2822, section 2.1.1 to start.
There are two limits that this standard places on the number of characters in a line. Each line of characters MUST be no more than 998 characters, and SHOULD be no more than 78 characters, excluding the CRLF.
As the RFC states later, you can work around this limit (not that you should) by folding the subject over multiple lines.
Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding". The general rule is that wherever this standard allows for folding white space (not simply WSP characters), a CRLF may be inserted before any WSP. For example, the header field:
Subject: This is a test
can be represented as:
Subject: This is a test
The recommendation for no more than 78 characters in the subject header sounds reasonable. No one wants to scroll to see the entire subject line, and something important might get cut off on the right.
I would handle it like so:
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'watch-me') {
$('#show-me').show();
}
else {
$('#show-me').hide();
}
});
});
<pre>
<input type="text" #titleInput>
<button type="submit" (click) = 'addTodo(titleInput.value)'>Add</button>
</pre>
{
addTodo(title:string) {
console.log(title);
}
}
For a single string String.ToCharArray should be used
string str = "One";
var charArray = str.ToCharArray();
For an array of strings
string[] arrayStrings = { "One", "Two", "Three" };
var charArrayList = arrayStrings.Select(str => str.ToCharArray()).ToList();
For a single character from a single string:
string str = "One";
var ch = str[0]; // means 'O'
You have done it correctly. The pull request will automatically update. The process is:
The pull request will automatically add the new commits at the bottom of the pull request discussion (ie, it's already there, scroll down!)
You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix
component is no longer included:
Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.
I can reproduce your problem if there are no files in the directory that were modified in the last hour. In that case, find . -mmin -60
returns nothing. The command find . -mmin -60 |xargs ls -l
, however, returns every file in the directory which is consistent with what happens when ls -l
is run without an argument.
To make sure that ls -l
is only run when a file is found, try:
find . -mmin -60 -type f -exec ls -l {} +
Sometimes you can have multiple fields with similar validation in your application. In such a case I recommend to create common component field where you keep this validation.
For instance, let's assume that you have mandatory text input in a few places in your application. You can create a TextInput component:
constructor(props) {
super(props);
this.state = {
touched: false, error: '', class: '', value: ''
}
}
onValueChanged = (event) => {
let [error, validClass, value] = ["", "", event.target.value];
[error, validClass] = (!value && this.props.required) ?
["Value cannot be empty", "is-invalid"] : ["", "is-valid"]
this.props.onChange({value: value, error: error});
this.setState({
touched: true,
error: error,
class: validClass,
value: value
})
}
render() {
return (
<div>
<input type="text"
value={this.props.value}
onChange={this.onValueChanged}
className={"form-control " + this.state.class}
id="{this.props.id}"
placeholder={this.props.placeholder} />
{this.state.error ?
<div className="invalid-feedback">
{this.state.error}
</div> : null
}
</div>
)
}
And then you can use such a component anywhere in your application:
constructor(props) {
super(props);
this.state = {
user: {firstName: '', lastName: ''},
formState: {
firstName: { error: '' },
lastName: { error: '' }
}
}
}
onFirstNameChange = (model) => {
let user = this.state.user;
user.firstName = model.value;
this.setState({
user: user,
formState: {...this.state.formState, firstName: { error: model.error }}
})
}
onLastNameChange = (model) => {
let user = this.state.user;
user.lastName = model.value;
this.setState({
user: user,
formState: {...this.state.formState, lastName: { error: model.error }}
})
}
onSubmit = (e) => {
// submit logic
}
render() {
return (
<form onSubmit={this.onSubmit}>
<TextInput id="input_firstName"
value={this.state.user.firstName}
onChange={this.onFirstNameChange}
required = {true}
placeholder="First name" />
<TextInput id="input_lastName"
value={this.state.user.lastName}
onChange={this.onLastNameChange}
required = {true}
placeholder="Last name" />
{this.state.formState.firstName.error || this.state.formState.lastName.error ?
<button type="submit" disabled className="btn btn-primary margin-left disabled">Save</button>
: <button type="submit" className="btn btn-primary margin-left">Save</button>
}
</form>
)
}
Benefits:
A late answer, but and approach using data.table
library(data.table)
DT <- data.table(dat)
DT[, .SD[which.max(Score),], by = Group]
Or, if it is possible to have more than one equally highest score
DT[, .SD[which(Score == max(Score)),], by = Group]
Noting that (from ?data.table
.SD
is a data.table containing the Subset of x's Data for each group, excluding the group column(s)
Based on http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b,
EqualAll is the approach that best meets your needs.
public void Linq96()
{
var wordsA = new string[] { "cherry", "apple", "blueberry" };
var wordsB = new string[] { "cherry", "apple", "blueberry" };
bool match = wordsA.SequenceEqual(wordsB);
Console.WriteLine("The sequences match: {0}", match);
}
CURL request by default is GET, you don't have to set any options to make a GET CURL request.
Josh says: "....Something to keep in mind when you are using Unicode although you can store different languages in a single column you can only sort using a single collation. There are some languages that use latin characters but do not sort like other latin languages. Accents is a good example of this, I can't remeber the example but there was a eastern european language whose Y didn't sort like the English Y. Then there is the spanish ch which spanish users expet to be sorted after h."
I'm a native Spanish Speaker and "ch" is not a letter but two "c" and "h" and the Spanish alphabet is like: abcdefghijklmn ñ opqrstuvwxyz We don't expect "ch" after "h" but "i" The alphabet is the same as in English except for the ñ or in HTML "ñ ;"
Alex
I have been puzzled a lot with this problem, since I am relively new in Python. I cannot apply the solution to the code given by the questioned, since it's not self executable. So I bring a very simple code:
from turtle import *
ts = Screen(); tu = Turtle()
def move(x,y):
print "move()"
tu.goto(100,100)
ts.listen();
ts.onclick(move)
done()
As you can see, the solution consists in using two (dummy) arguments, even if they are not used either by the function itself or in calling it! It sounds crazy, but I believe there must be a reason for it (hidden from the novice!).
I have tried a lot of other ways ('self' included). It's the only one that works (for me, at least).
you just need to use word boundary (\b
) instead of ^
and $
:
\bgarp\b
String a ="dgfa";
char [] c = a.toCharArray();
Arrays.sort(c);
return new String(c);
Note that this will not work as expected if it is a mixed case String (It'll put uppercase before lowercase). You can pass a comparator to the Sort method to change that.
I couldn't get the accepted answer to work using the Netbeans IDE "Create Table" GUI, and I'm on Netbeans 8.2. To get it to working, create the id column with the following options e.g.
and then use 'New Entity Classes from Database' option to generate the entity for the table (I created a simple table called PERSON with an ID column created exactly as above and a NAME column which is simple varchar(255) column). These generated entities leave it to the user to add the auto generated id mechanism.
GENERATION.AUTO seems to try and use sequences which Derby doesn't seem to like (error stating failed to generate sequence/sequence does not exist), GENERATION.SEQUENCE therefore doesn't work either, GENERATION.IDENTITY doesn't work (get error stating ID is null), so that leaves GENERATION.TABLE.
Set your persistence unit's 'Table Generation Strategy' button to Create. This will create tables that don't exist in the DB when your jar is run (loaded?) i.e. the table your PU needs to create in order to store ID increments. In your entity replace the generated annotations above your id field with the following...
I also created a controller for my entity class using 'JPA Controller Classes from Entity Classes' option. I then create a simple main class to test the id was auto generated i.e.
The result is that the PERSON_ID_TABLE is generated correctly and my PERSON table has two PERSON entries in it with correct, auto generated ids.
ngRepeat creates a copy of the array when it applies a filter, so you can't use the source array to reference only the filtered elements.
In your case, in may be better to apply the filter inside of your controller using the $filter
service:
function MainCtrl( $scope, filterFilter ) {
// ...
$scope.filteredData = myNormalData;
$scope.$watch( 'myInputModel', function ( val ) {
$scope.filteredData = filterFilter( myNormalData, val );
});
// ...
}
And then you use the filteredData
property in your view instead. Here is a working Plunker: http://plnkr.co/edit/7c1l24rPkuKPOS5o2qtx?p=preview
count = 0 if count == N else N+1
- the ternary operator. Although I'd say your solution is more readable than this.
You can also take a look at PDFMiner (or for older versions of Python see PDFMiner and PDFMiner).
A particular feature of interest in PDFMiner is that you can control how it regroups text parts when extracting them. You do this by specifying the space between lines, words, characters, etc. So, maybe by tweaking this you can achieve what you want (that depends of the variability of your documents). PDFMiner can also give you the location of the text in the page, it can extract data by Object ID and other stuff. So dig in PDFMiner and be creative!
But your problem is really not an easy one to solve because, in a PDF, the text is not continuous, but made from a lot of small groups of characters positioned absolutely in the page. The focus of PDF is to keep the layout intact. It's not content oriented but presentation oriented.
Unless you accidentally read in the whole input file instead of reading it line by line, then your primary limitation will be disk speed. You may want to try starting with a file containing 100 lines and write it to 100 different files one line in each and make the triggering mechanism work on the number of lines written to the current file. That program will be easily scalable to your situation.
1 unless file exists will rewrite to index.php
Add the following to your location ~ \.php$
try_files = $uri @missing;
this will first try to serve the file and if it's not found it will move to the @missing
part. so also add the following to your config (outside the location
block), this will redirect to your index page
location @missing {
rewrite ^ $scheme://$host/index.php permanent;
}
2 on the urls you never see the file extension (.php)
to remove the php extension read the following: http://www.nullis.net/weblog/2011/05/nginx-rewrite-remove-file-extension/
and the example configuration from the link:
location / {
set $page_to_view "/index.php";
try_files $uri $uri/ @rewrites;
root /var/www/site;
index index.php index.html index.htm;
}
location ~ \.php$ {
include /etc/nginx/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/site$page_to_view;
}
# rewrites
location @rewrites {
if ($uri ~* ^/([a-z]+)$) {
set $page_to_view "/$1.php";
rewrite ^/([a-z]+)$ /$1.php last;
}
}
I'm not familiar with resolve, but I've used the others:
Recursive is the default for non-fast-forward merges. We're all familiar with that one.
I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.
An octopus branch merges multiple heads in one commit as long as it can do it cleanly.
For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).
A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):
However, a single octopus merge would look like this:
commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...
Ours == I want to pull in another head, but throw away all of the changes that head introduces.
This keeps the history of a branch without any of the effects of the branch.
(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use git merge -X ours
)
Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.
7-zip understands most kinds of archives, including rpm and the included cpio.
I know the question asks about macOS, but here is a solution for Linux users who arrive here via Google.
I was having the issue described in this question, having installed the pdfx package via pip.
When I ran it however, nothing...
pip list | grep pdfx
pdfx (1.3.0)
Yet:
which pdfx
pdfx not found
The problem on Linux is that pip install ...
drops scripts into ~/.local/bin
and this is not on the default Debian/Ubuntu $PATH
.
Here's a GitHub issue going into more detail: https://github.com/pypa/pip/issues/3813
To fix, just add ~/.local/bin
to your $PATH
, for example by adding the following line to your .bashrc
file:
export PATH="$HOME/.local/bin:$PATH"
After that, restart your shell and things should work as expected.
This solution works for me:
<select ng-model="mymodel">
<option ng-value="''" style="display:none;" selected>Country</option>
<option value="US">USA</option>
</select>
Use ord
when reading reading bytes:
byte_binary = bin(ord(f.read(1))) # Add [2:] to remove the "0b" prefix
Or
Using str.format()
:
'{:08b}'.format(ord(f.read(1)))
To populate a List of String, you need not use custom row mapper. Implement it using queryForList
.
List<String>data=jdbcTemplate.queryForList(query,String.class)
Unrelated to the question (Mehrdad's answer should get you going), and I hope this isn't taken as nitpicky: classes don't inherit interfaces, they implement them.
.NET does not support multiple-inheritance, so keeping the terms straight can help in communication. A class can inherit from one superclass and can implement as many interfaces as it wishes.
In response to Eric's comment... I had a discussion with another developer about whether or not interfaces "inherit", "implement", "require", or "bring along" interfaces with a declaration like:
public interface ITwo : IOne
The technical answer is that ITwo
does inherit IOne
for a few reasons:
ITwo
implements IOne
is flat wrongITwo
inherits IOne
methods, if MethodOne()
exists on IOne
then it is also accesible from ITwo
. i.e: ((ITwo)someObject).MethodOne())
is valid, even though ITwo
does not explicitly contain a definition for MethodOne()
typeof(IOne).IsAssignableFrom(typeof(ITwo))
returns true
We finally agreed that interfaces support true/full inheritance. The missing inheritance features (such as overrides, abstract/virtual accessors, etc) are missing from interfaces, not from interface inheritance. It still doesn't make the concept simple or clear, but it helps understand what's really going on under the hood in Eric's world :-)
I have always used keyup and e.which to catch escape key.
You may or may not have to use setOpaque method to ensure that the colors show up by passing true to the method.
[ ]
- this is used whenever we are declaring an empty array,
{ }
- this is used whenever we declare an empty object
typeof([ ]) //object
typeof({ }) //object
but if your run
[ ].constructor.name //Array
so from this, you will understand it is an array here Array is the name of the base class. The JavaScript Array class is a global object that is used in the construction of arrays which are high-level, list-like objects.
The best way to work with already created tables is that, Go to Sql Server Query Editor
Type: sp_help <tablename>
This will show table's structure , see the details for the desired field under COLLATE column.
then type in the query like :
SELECT myColumn FROM myTable
WHERE myColumn COLLATE SQL_Latin1_General_CP1_CI_AS = 'Case'
It could be different character schema <SQL_Latin1_General_CP1_CI_AS
>, so better to find out the exact schema that has been used against that column.
I created a function:
CREATE FUNCTION [dbo].[fnPadLeft](@int int, @Length tinyint)
RETURNS varchar(255)
AS
BEGIN
DECLARE @strInt varchar(255)
SET @strInt = CAST(@int as varchar(255))
RETURN (REPLICATE('0', (@Length - LEN(@strInt))) + @strInt);
END;
Use: select dbo.fnPadLeft(123, 10)
Returns: 0000000123
My case was to print horizontal (landscape) summary section - so:
}).then((canvas) => {
const img = canvas.toDataURL('image/jpg');
new jsPDF({
orientation: 'l', // landscape
unit: 'pt', // points, pixels won't work properly
format: [canvas.width, canvas.height] // set needed dimensions for any element
});
pdf.addImage(img, 'JPEG', 0, 0, canvas.width, canvas.height);
pdf.save('your-filename.pdf');
});
see the picture. but I have to type enough chars to post the picture.:)
FOR EXAMPLE YOU HAVE RECIEVED JASON DATA FROM SERVER.
var obj = JSON.parse(msg);
var tableString ="<table id='tbla'>";
tableString +="<th><td>Name<td>City<td>Birthday</th>";
for (var i=0; i<obj.length; i++){
//alert(obj[i].name);
tableString +=gg_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>",obj[i].name, obj[i].age, obj[i].birthday);
}
tableString +="</table>";
alert(tableString);
$('#divb').html(tableString);
HERE IS THE CODE FOR gg_stringformat
function gg_stringformat() {
var argcount = arguments.length,
string,
i;
if (!argcount) {
return "";
}
if (argcount === 1) {
return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;
}
There are several ways to do it, but here is one solution (for 4 columns).
string[] row1 = { "s1", "s2", "s3" };
listView1.Items.Add("Column1Text").SubItems.AddRange(row1);
And a more verbose way is here:
ListViewItem item1 = new ListViewItem("Something");
item1.SubItems.Add("SubItem1a");
item1.SubItems.Add("SubItem1b");
item1.SubItems.Add("SubItem1c");
ListViewItem item2 = new ListViewItem("Something2");
item2.SubItems.Add("SubItem2a");
item2.SubItems.Add("SubItem2b");
item2.SubItems.Add("SubItem2c");
ListViewItem item3 = new ListViewItem("Something3");
item3.SubItems.Add("SubItem3a");
item3.SubItems.Add("SubItem3b");
item3.SubItems.Add("SubItem3c");
ListView1.Items.AddRange(new ListViewItem[] {item1,item2,item3});
For me I had forgot to add closing quote
/p:DeployOnBuild=true;OutDir="$(build.artifactstagingdirectory)
to
/p:DeployOnBuild=true;OutDir="$(build.artifactstagingdirectory)"
The current answers are fine and should work ok, but what's wrong with the more simple, more obvious, and more maintainable:
IF @flag = 1
UPDATE table_name SET column_A = column_A + @new_value WHERE ID = @ID;
ELSE
UPDATE table_name SET column_B = column_B + @new_value WHERE ID = @ID;
This is much easier to read albeit this is a very simple query.
Here's a working example courtesy of @snyder: SqlFiddle.
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
An elegant way to count the occurrence of '?'
or any symbol in any column, is to use built-in function isin
of a dataframe object.
Suppose that we have loaded the 'Automobile' dataset into df
object.
We do not know which columns contain missing value ('?'
symbol), so let do:
df.isin(['?']).sum(axis=0)
DataFrame.isin(values)
official document says:
it returns boolean DataFrame showing whether each element in the DataFrame is contained in values
Note that isin
accepts an iterable as input, thus we need to pass a list containing the target symbol to this function. df.isin(['?'])
will return a boolean dataframe as follows.
symboling normalized-losses make fuel-type aspiration-ratio ...
0 False True False False False
1 False True False False False
2 False True False False False
3 False False False False False
4 False False False False False
5 False True False False False
...
To count the number of occurrence of the target symbol in each column, let's take sum
over all the rows of the above dataframe by indicating axis=0
.
The final (truncated) result shows what we expect:
symboling 0
normalized-losses 41
...
bore 4
stroke 4
compression-ratio 0
horsepower 2
peak-rpm 2
city-mpg 0
highway-mpg 0
price 4
The permament pool contains everything that is not your application data, but rather things required for the VM: typically it contains interned strings, the byte code of defined classes, but also other "not yours" pieces of data.
You can use following code which generate pdf file in background as like on button click and then would popup in brwoser with SaveAs and cancel option.
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;`enter code here`
string extension = string.Empty;
DataSet dsGrpSum, dsActPlan, dsProfitDetails,
dsProfitSum, dsSumHeader, dsDetailsHeader, dsBudCom = null;
enter code here
//This is optional if you have parameter then you can add parameters as much as you want
ReportParameter[] param = new ReportParameter[5];
param[0] = new ReportParameter("Report_Parameter_0", "1st Para", true);
param[1] = new ReportParameter("Report_Parameter_1", "2nd Para", true);
param[2] = new ReportParameter("Report_Parameter_2", "3rd Para", true);
param[3] = new ReportParameter("Report_Parameter_3", "4th Para", true);
param[4] = new ReportParameter("Report_Parameter_4", "5th Para");
DataSet dsData= "Fill this dataset with your data";
ReportDataSource rdsAct = new ReportDataSource("RptActDataSet_usp_GroupAccntDetails", dsActPlan.Tables[0]);
ReportViewer viewer = new ReportViewer();
viewer.LocalReport.Refresh();
viewer.LocalReport.ReportPath = "Reports/AcctPlan.rdlc"; //This is your rdlc name.
viewer.LocalReport.SetParameters(param);
viewer.LocalReport.DataSources.Add(rdsAct); // Add datasource here
byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
// byte[] bytes = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
// Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
// System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename= filename" + "." + extension);
Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file
Response.Flush(); // send it to the client to download
Response.End();
As people have said, in Windows, I just dropped my pem file in C:\Users[user].ssh\ and that solved it. Although you can do chmod and other command line options from a bash or powershell prompt that didn't work. I didn't change rsa or anything else. Then when running the connection you have to put the path to the pem file in the .ssh folder:
ssh -i "C:\Users[user].ssh\ubuntukp01.pem" ubuntu@ec[ipaddress].us-west-2.compute.amazonaws.com
After doing a lot of things, I upgraded pip
, setuptools
and virtualenv
.
python -m pip install -U pip
pip install -U setuptools
pip install -U virtualenv
I did steps 1, 2 in my virtual environment as well as globally.
Next, I installed the package through pip
and it worked.
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
I see most people confused about tf.shape(tensor)
and tensor.get_shape()
Let's make it clear:
tf.shape
tf.shape
is used for dynamic shape. If your tensor's shape is changable, use it.
An example: a input is an image with changable width and height, we want resize it to half of its size, then we can write something like:
new_height = tf.shape(image)[0] / 2
tensor.get_shape
tensor.get_shape
is used for fixed shapes, which means the tensor's shape can be deduced in the graph.
Conclusion:
tf.shape
can be used almost anywhere, but t.get_shape
only for shapes can be deduced from graph.
Without actually seeing your output file for confirmation, my guess is that you've got to get rid of the FIELDS ESCAPED BY
value.
MySQL's FIELDS ESCAPED BY
is probably behaving in two ways that you were not counting on: (1) it is only meant to be one character, so in your case it is probably equal to just one quotation mark; (2) it is used to precede each character that MySQL thinks needs escaping, including the FIELDS TERMINATED BY
and LINES TERMINATED BY
values. This makes sense to most of the computing world, but it isn't the way Excel does escaping.
I think your double REPLACE
is working, and that you are successfully replacing literal newlines with spaces (two spaces in the case of Windows-style newlines). But if you have any commas in your data (literals, not field separators), these are being preceded by quotation marks, which Excel treats much differently than MySQL. If that's the case, then the erroneous newlines that are tripping up Excel are actually newlines that MySQL had intended as line terminators.
In FF also CSS filter works fine. E.g. hue-rotate:
option {
filter: hue-rotate(90deg);
}
The first c++ compiler actually was a preprocessor which translated the C++ code into C.
So it's very possible to have classes in C. You might try and dig up an old C++ preprocessor and see what kind of solutions it creates.
docker ps -a
to get container ids then
docker exec -it psql -U -W
You can make use of location service available in @angular/common and via this below code you can get the location or current URL
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
@Component({
selector: 'app-top-nav',
templateUrl: './top-nav.component.html',
styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {
route: string;
constructor(location: Location, router: Router) {
router.events.subscribe((val) => {
if(location.path() != ''){
this.route = location.path();
} else {
this.route = 'Home'
}
});
}
ngOnInit() {
}
}
here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts
In windows using "Windows PowerShell" I used the command mentioned below to achieve this
Get-Content .\file.txt | Group-Object | Select Name, Count
Also we can use the where-object Cmdlet to filter the result
Get-Content .\file.txt | Group-Object | Where-Object { $_.Count -gt 1 } | Select Name, Count
You need to simple use following function.
function GetQueryStringByParameter(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
--- How to Use ---
var QueryString= GetQueryStringByParameter('QueryString');
Something like this worked for me. I am guessing this should work for you.
Run webpack-dev using this
webpack-dev-server --host 0.0.0.0 --port 80
And set this in webpack.config.js
entry: [
'webpack-dev-server/client?http://0.0.0.0:80',
config.paths.demo
]
Note If you are using hot loading, you will have to do this.
Run webpack-dev using this
webpack-dev-server --host 0.0.0.0 --port 80
And set this in webpack.config.js
entry: [
'webpack-dev-server/client?http://0.0.0.0:80',
'webpack/hot/only-dev-server',
config.paths.demo
],
....
plugins:[new webpack.HotModuleReplacementPlugin()]
A particular feature of a HashMap is that unlike, say, balanced trees, its behavior is probabilistic. In these cases its usually most helpful to talk about complexity in terms of the probability of a worst-case event occurring would be. For a hash map, that of course is the case of a collision with respect to how full the map happens to be. A collision is pretty easy to estimate.
pcollision = n / capacity
So a hash map with even a modest number of elements is pretty likely to experience at least one collision. Big O notation allows us to do something more compelling. Observe that for any arbitrary, fixed constant k.
O(n) = O(k * n)
We can use this feature to improve the performance of the hash map. We could instead think about the probability of at most 2 collisions.
pcollision x 2 = (n / capacity)2
This is much lower. Since the cost of handling one extra collision is irrelevant to Big O performance, we've found a way to improve performance without actually changing the algorithm! We can generalzie this to
pcollision x k = (n / capacity)k
And now we can disregard some arbitrary number of collisions and end up with vanishingly tiny likelihood of more collisions than we are accounting for. You could get the probability to an arbitrarily tiny level by choosing the correct k, all without altering the actual implementation of the algorithm.
We talk about this by saying that the hash-map has O(1) access with high probability
If you don't need the gap to be exactly 2 lines high, you can add an empty view like this:
<View
android:layout_width="fill_parent"
android:layout_height="30dp">
</View>
I just used less
on top of Cygwin to read a 3GB file, though I ended up using grep
to find what I needed in it.
(less
is more
, but better.)
See this answer for more details on less
: https://stackoverflow.com/a/1343576/1005039
Rather than creating empty directories in source to exclude, you can supply the full destination path to the /XD switch to have the destination directories untouched
robocopy "%SOURCE_PATH%" "%DEST_PATH%" /MIR /XD "%DEST_PATH%"\hq04s2dba301
if(A && B){ }
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
Easy approach:
CREATE TABLE T
(
C [nvarchar](100) NOT NULL UNIQUE,
);
SET XACT_ABORT ON -- Turns on rollback if T-SQL statement raises a run-time error.
SELECT * FROM T; -- Check before.
BEGIN TRAN
INSERT INTO T VALUES ('A');
INSERT INTO T VALUES ('B');
INSERT INTO T VALUES ('B');
INSERT INTO T VALUES ('C');
COMMIT TRAN
SELECT * FROM T; -- Check after.
DELETE T;
I will reuse the data example from @PaulRougieux
x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)
Here's a short and sweet solution using purrr
and tidyr
library(tidyverse)
list(x, y, z) %>%
map_df(gather, key=key, value=value, -i) %>%
spread(key, value)
I'm not sure that there isn't a bit too much fussing around here. I recently had problems with md5 and files stored as blobs on MySQL so I experimented with various file sizes and the straightforward Python approach, viz:
FileHash=hashlib.md5(FileData).hexdigest()
I could detect no noticeable performance difference with a range of file sizes 2Kb to 20Mb and therefore no need to 'chunk' the hashing. Anyway, if Linux has to go to disk, it will probably do it at least as well as the average programmer's ability to keep it from doing so. As it happened, the problem was nothing to do with md5. If you're using MySQL, don't forget the md5() and sha1() functions already there.
You don't have to have a method for that. You could create a property like this instead:
class SalesPerson
{
string firstName, lastName;
public string FirstName { get { return firstName; } set { firstName = value; } }
public string LastName { get { return lastName; } set { lastName = value; } }
public string FullName { get { return this.FirstName + " " + this.LastName; } }
}
The class could even be shortened to:
class SalesPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName {
get { return this.FirstName + " " + this.LastName; }
}
}
The property could then be accessed like any other property:
class Program
{
static void Main(string[] args)
{
SalesPerson x = new SalesPerson("John", "Doe");
Console.WriteLine(x.FullName); // Will print John Doe
}
}
if you are using SQL Server use convert
e.g. select convert(varchar(10), DeliveryDate, 103) as ShortDate
more information here: http://msdn.microsoft.com/en-us/library/aa226054(v=sql.80).aspx
I propose a simple TLDR:; example for the un-initiated.
Create a bash script called helloworld.sh
#!/bin/bash
while getopts "n:" arg; do
case $arg in
n) Name=$OPTARG;;
esac
done
echo "Hello $Name!"
You can then pass an optional parameter -n
when executing the script.
Execute the script as such:
$ bash helloworld.sh -n 'World'
Output
$ Hello World!
Notes
If you'd like to use multiple parameters:
while getops "n:" arg: do
with more paramaters such as
while getops "n:o:p:" arg: do
o) Option=$OPTARG
and p) Parameter=$OPTARG
SELECT DISTINCT *
FROM people
WHERE names = 'Smith'
ORDER BY
names
LIMIT 10
Is there any difference?
Yes. A Timeout executes a certain amount of time after setTimeout() is called; an Interval executes a certain amount of time after the previous interval fired.
You will notice the difference if your doStuff() function takes a while to execute. For example, if we represent a call to setTimeout/setInterval with .
, a firing of the timeout/interval with *
and JavaScript code execution with [-----]
, the timelines look like:
Timeout:
. * . * . * . * .
[--] [--] [--] [--]
Interval:
. * * * * * *
[--] [--] [--] [--] [--] [--]
The next complication is if an interval fires whilst JavaScript is already busy doing something (such as handling a previous interval). In this case, the interval is remembered, and happens as soon as the previous handler finishes and returns control to the browser. So for example for a doStuff() process that is sometimes short ([-]) and sometimes long ([-----]):
. * * • * • * *
[-] [-----][-][-----][-][-] [-]
• represents an interval firing that couldn't execute its code straight away, and was made pending instead.
So intervals try to ‘catch up’ to get back on schedule. But, they don't queue one on top of each other: there can only ever be one execution pending per interval. (If they all queued up, the browser would be left with an ever-expanding list of outstanding executions!)
. * • • x • • x
[------][------][------][------]
x represents an interval firing that couldn't execute or be made pending, so instead was discarded.
If your doStuff() function habitually takes longer to execute than the interval that is set for it, the browser will eat 100% CPU trying to service it, and may become less responsive.
Which do you use and why?
Chained-Timeout gives a guaranteed slot of free time to the browser; Interval tries to ensure the function it is running executes as close as possible to its scheduled times, at the expense of browser UI availability.
I would consider an interval for one-off animations I wanted to be as smooth as possible, whilst chained timeouts are more polite for ongoing animations that would take place all the time whilst the page is loaded. For less demanding uses (such as a trivial updater firing every 30 seconds or something), you can safely use either.
In terms of browser compatibility, setTimeout predates setInterval, but all browsers you will meet today support both. The last straggler for many years was IE Mobile in WinMo <6.5, but hopefully that too is now behind us.
^[0-9][0-9]?[^A-Za-z0-9]?po$
You can test it here: http://www.regextester.com/
To use this in C#,
Regex r = new Regex(@"^[0-9][0-9]?[^A-Za-z0-9]?po$");
if (r.Match(someText).Success) {
//Do Something
}
Remember, @ is a useful symbol that means the parser takes the string literally (eg, you don't need to write \\ for one backslash)
If you need a body in your response, you can call
return StatusCode(StatusCodes.Status500InternalServerError, responseObject);
This will return a 500 with the response object...
I have added few lines inside package.json:
"scripts": {
...
"clean": "rmdir /s /q node_modules",
"reinstall": "npm run clean && npm install",
"rebuild": "npm run clean && npm install && rmdir /s /q dist && npm run build --prod",
...
}
If you want to clean
only you can use this rimraf node_modules
or rm -rf node_modules
.
It works fine
git
on Centos 6/7Install epel:
For EL6, use:
sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
For EL7, use:
sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
Install fedpkg
:
sudo yum install fedpkg
Add yourself into group mock (you might need to re-login to server after this change):
sudo usermod -a -G mock $USER
git
Download git
sources:
fedpkg clone -a git && cd git
fedpkg sources
Verify sources:
sha512sum -c sources
Create srmp. Use el6
for RHEL6, el7
for RHEL7.
fedpkg --dist el7 srpm
Build package in mock:
mock -r epel-7-x86_64 git-2.16.0-1.el7.src.rpm
Install latest version of git
rpm from /var/lib/mock/epel-7-x86_64/result/
. Note, you might need to uninstall existing version of the git from your system first.
This instruction is based on the mailing list post by Todd Zullinger.
Codehaus Jackson - I have been this awesome API since 2012 for my RESTful webservice and JUnit tests. With their API, you can:
(1) Convert JSON String to Java bean
public static String beanToJSONString(Object myJavaBean) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.writeValueAsString(myJavaBean);
}
(2) Convert JSON String to JSON object (JsonNode)
public static JsonNode stringToJSONObject(String jsonString) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.readTree(jsonString);
}
//Example:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JsonNode jsonNode = stringToJSONObject(jsonString);
Assert.assertEquals("Phonetype value not legit!", "N95", jsonNode.get("phonetype").getTextValue());
Assert.assertEquals("Cat value is tragic!", "WP", jsonNode.get("cat").getTextValue());
(3) Convert Java bean to JSON String
public static Object JSONStringToBean(Class myBeanClass, String JSONString) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.readValue(JSONString, beanClass);
}
REFS:
JsonNode API - How to use, navigate, parse and evaluate values from a JsonNode object
Tutorial - Simple tutorial how to use Jackson to convert JSON string to JsonNode
You can just use a Hook
add_filter( 'nav_menu_submenu_css_class', 'some_function', 10, 3 );
function some_function( $classes, $args, $depth ){
foreach ( $classes as $key => $class ) {
if ( $class == 'sub-menu' ) {
$classes[ $key ] = 'my-sub-menu';
}
}
return $classes;
}
where
$classes(array) - The CSS classes that are applied to the menu <ul> element.
$args(stdClass) - An object of wp_nav_menu() arguments.
$depth(int) - Depth of menu item. Used for padding.
You don't need to do special things in the form. You just build the comment correctly in the show action:
class ArticlesController < ActionController::Base
....
def show
@article = Article.find(params[:id])
@new_comment = @article.comments.build
end
....
end
and then make a form for it in the article view:
<% form_for @new_comment do |f| %>
<%= f.text_area :text %>
<%= f.submit "Post Comment" %>
<% end %>
by default, this comment will go to the create
action of CommentsController
, which you will then probably want to put redirect :back
into so you're routed back to the Article
page.
// Disable #x
$( "#x" ).prop( "disabled", true );
// Enable #x
$( "#x" ).prop( "disabled", false );
Sometimes you need to disable/enable the form element like input or textarea. Jquery helps you to easily make this with setting disabled attribute to "disabled". For e.g.:
//To disable
$('.someElement').attr('disabled', 'disabled');
To enable disabled element you need to remove "disabled" attribute from this element or empty it's string. For e.g:
//To enable
$('.someElement').removeAttr('disabled');
// OR you can set attr to ""
$('.someElement').attr('disabled', '');
refer :http://garmoncheg.blogspot.fr/2011/07/how-to-disableenable-element-with.html
A more elegant solution could be:
def progressBar(current, total, barLength = 20):
percent = float(current) * 100 / total
arrow = '-' * int(percent/100 * barLength - 1) + '>'
spaces = ' ' * (barLength - len(arrow))
print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')
call this function with value
and endvalue
, result should be
Progress: [-------------> ] 69 %
Note: Python 2.x version here.
You can use multiple repositories syntax for the registry
entry in your .npmrc
file:
registry=http://serverA.url/repository-uri/
//serverB.url/repository-uri/
//serverC.url/repository-uri/:_authToken=00000000-0000-0000-0000-0000000000000
//registry.npmjs.org/
That would make your npm look for packages in different servers.
Earlier,I was facing problem in using jquery with React js,so I did following steps to make it working-
npm install jquery --save
Then, import $ from "jquery";
Just in case your PC is not a "Western" PC and you don't know which code page is used, you can have a look at this page: National Language Support (NLS) API Reference
[Microsoft removed this reference, take it form web-archive National Language Support (NLS) API Reference
Or you can query your registry:
C:\>reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage /f ACP
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage
ACP REG_SZ 1252
End of search: 1 match(es) found.
C:\>
You can use my plug-in to create tests easily:
The plug-in is available here. Hope this helps.
From GC Performance Tuning training documents of Oracle:
-Xmn[size]: Size of young generation heap space.
Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.
In short, it sets the NewSize and MaxNewSize values of New generation to the same value.
You can think it as a CSS style visibility & display.
<div style="visibility:visible; display:block">
This is View.VISIBLE : Content is displayed normally.
</div>
<div style="visibility:hidden; display:block">
This is View.INVISIBLE : Content is not displayed, but div still takes up place, but empty.
</div>
<div style="display:none">
This is View.GONE : Container div is not shown, you can say the content is not displayed.
</div>
All of these answers are wrong! Do not use InsecureSkipVerify
to deal with a CN that doesn't match the hostname. The Go developers unwisely were adamant about not disabling hostname checks (which has legitimate uses - tunnels, nats, shared cluster certs, etc), while also having something that looks similar but actually completely ignores the certificate check. You need to know that the certificate is valid and signed by a cert that you trust. But in common scenarios, you know that the CN won't match the hostname you connected with. For those, set ServerName
on tls.Config
. If tls.Config.ServerName
== remoteServerCN, then the certificate check will succeed. This is what you want. InsecureSkipVerify
means that there is NO authentication; and it's ripe for a Man-In-The-Middle; defeating the purpose of using TLS.
There is one legitimate use for InsecureSkipVerify
: use it to connect to a host and grab its certificate, then immediately disconnect. If you setup your code to use InsecureSkipVerify
, it's generally because you didn't set ServerName
properly (it will need to come from an env var or something - don't belly-ache about this requirement... do it correctly).
In particular, if you use client certs and rely on them for authentication, you basically have a fake login that doesn't actually login any more. Refuse code that does InsecureSkipVerify
, or you will learn what is wrong with it the hard way!
Here's a nice answer from the FAQ on the scipy.org website:
What advantages do NumPy arrays offer over (nested) Python lists?
Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate. However, they have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element. This also means that very few list operations can be carried out by efficient C loops – each iteration would require type checks and other Python API bookkeeping.
Assuming the column is set to support NULL as a value:
UPDATE YOUR_TABLE
SET column = NULL
Be aware of the database NULL handling - by default in SQL Server, NULL is an INT. So if the column is a different data type you need to CAST/CONVERT NULL to the proper data type:
UPDATE YOUR_TABLE
SET column = CAST(NULL AS DATETIME)
...assuming column
is a DATETIME data type in the example above.
See other solutions for median calculation in SQL here: "Simple way to calculate median with MySQL" (the solutions are mostly vendor-independent).
Query A is the same as:
select 'true' where 3 = 1 or 3 = 2 or 3 = 3 or 3 = null
Since 3 = 3
is true, you get a result.
Query B is the same as:
select 'true' where 3 <> 1 and 3 <> 2 and 3 <> null
When ansi_nulls
is on, 3 <> null
is UNKNOWN, so the predicate evaluates to UNKNOWN, and you don't get any rows.
When ansi_nulls
is off, 3 <> null
is true, so the predicate evaluates to true, and you get a row.
In gobuffalo.io framework I got it to work like this:
// say we are in some resource Show action
// some code is omitted
user := &models.User{}
if c.Request().Header.Get("Content-type") == "application/json" {
return c.Render(200, r.JSON(user))
} else {
// Make user available inside the html template
c.Set("user", user)
return c.Render(200, r.HTML("users/show.html"))
}
and then when I want to get JSON response for that resource I have to set "Content-type" to "application/json" and it works.
I think Rails has more convenient way to handle multiple response types, I didn't see the same in gobuffalo so far.
div{
background-image:url('');
background-size:cover;
background-position:top center;
position:relative;
}
div:before{
content:'';
position:absolute;
left:0;
top:0;
height:100%;
width:100%;
background-color:rgba(0,0,0,0.7);
}
I don't hear about "apstring".If you want to use string with c++ ,you can do like this:
#include<string>
using namespace std;
int main()
{
string str;
cin>>str;
cout<<str;
...
return 0;
}
I hope this can avail
You can do injection on Directives, and it looks just like it does everywhere else.
app.directive('changeIt', ['myData', function(myData){
return {
restrict: 'C',
link: function (scope, element, attrs) {
scope.name = myData.name;
}
}
}]);
UPDATE test SET a = CONCAT(a, "more text")
with open(filename, 'a') as f:
df.to_csv(f, header=f.tell()==0)
If you want to allow all origins and keep credentials true, this worked for me:
app.use(cors({
origin: function(origin, callback){
return callback(null, true);
},
optionsSuccessStatus: 200,
credentials: true
}));
If you have an element that does not have a specific selector and you still want to check if it is a descendant of another element, you can use jQuery.contains()
jQuery.contains( container, contained )
Description: Check to see if a DOM element is a descendant of another DOM element.
You can pass the parent element and the element that you want to check to that function and it returns if the latter is a descendant of the first.
A realtime priority thread can never be pre-empted by timer interrupts and runs at a higher priority than any other thread in the system. As such a CPU bound realtime priority thread can totally ruin a machine.
Creating realtime priority threads requires a privilege (SeIncreaseBasePriorityPrivilege) so it can only be done by administrative users.
For Vista and beyond, one option for applications that do require that they run at realtime priorities is to use the Multimedia Class Scheduler Service (MMCSS) and let it manage your threads priority. The MMCSS will prevent your application from using too much CPU time so you don't have to worry about tanking the machine.
It may be too late for my answer, but I think this is not that hard. You can extend the PDFTextStripper class and override the writePage() and processTextPosition(...) methods. In your case I assume that the column headers are always the same. That means that you know the x-coordinate of each column heading and you can compare the the x-coordinate of the numbers to those of the column headings. If they are close enough (you have to test to decide how close) then you can say that that number belongs to that column.
Another approach would be to intercept the "charactersByArticle" Vector after each page is written:
@Override
public void writePage() throws IOException {
super.writePage();
final Vector<List<TextPosition>> pageText = getCharactersByArticle();
//now you have all the characters on that page
//to do what you want with them
}
Knowing your columns, you can do your comparison of the x-coordinates to decide what column every number belongs to.
The reason you don't have any spaces between numbers is because you have to set the word separator string.
I hope this is useful to you or to others who might be trying similar things.
if ( ! $("input").is(':checked') )
Doesn't work?
You might also try iterating over the elements like so:
var iz_checked = true;
$('input').each(function(){
iz_checked = iz_checked && $(this).is(':checked');
});
if ( ! iz_checked )
If you add your site to "Local Intranet" in
Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.
Add you site URL here and it will work.
Update for New Version of Chrome
Chrome > Settings > Advanced > System > Open Proxy Settings > Security (tab) > Local Intranet > Sites (button) > Advanced.
Creating a property with only a getter makes your property read-only for any code that is outside the class.
You can however change the value using methods provided by your class :
public class FuelConsumption {
private double fuel;
public double Fuel
{
get { return this.fuel; }
}
public void FillFuelTank(double amount)
{
this.fuel += amount;
}
}
public static void Main()
{
FuelConsumption f = new FuelConsumption();
double a;
a = f.Fuel; // Will work
f.Fuel = a; // Does not compile
f.FillFuelTank(10); // Value is changed from the method's code
}
Setting the private field of your class as readonly
allows you to set the field value only once (using an inline assignment or in the class constructor).
You will not be able to change it later.
public class ReadOnlyFields {
private readonly double a = 2.0;
private readonly double b;
public ReadOnlyFields()
{
this.b = 4.0;
}
}
readonly
class fields are often used for variables that are initialized during class construction, and will never be changed later on.
In short, if you need to ensure your property value will never be changed from the outside, but you need to be able to change it from inside your class code, use a "Get-only" property.
If you need to store a value which will never change once its initial value has been set, use a readonly
field.
For ASP.NET Web Api 2, this post from MS suggests to change the method's return type to IHttpActionResult
. You can then return a built in IHttpActionResult
implementation like Ok
, BadRequest
, etc (see here) or return your own implementation.
For your code, it could be done like:
public IHttpActionResult GetUser(int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
return StatusCode(HttpStatusCode.NotModified);
}
return Ok(user);
}
I hope the answers are already posted
I am adding the framework to find multiple words and negate those from dataFrame.
Here 'word1','word2','word3','word4'
= list of patterns to search
df
= DataFrame
column_a
= A column name from from DataFrame df
Search_for_These_values = ['word1','word2','word3','word4']
pattern = '|'.join(Search_for_These_values)
result = df.loc[~(df['column_a'].str.contains(pattern, case=False)]
In shell you assign to a variable without the dollar-sign:
TEST=`pwd`
echo $TEST
that's better (and can be nested) but is not as portable as the backtics:
TEST=$(pwd)
echo $TEST
Always remember: the dollar-sign is only used when reading a variable.
This answer works with any count of digit groups. Example:
$ echo 'Num123that456are7899900contained0018166intext' \
| sed -En 's/[^0-9]*([0-9]{1,})[^0-9]*/\1 /gp'
123 456 7899900 0018166
Is there any way to tell sed to output only captured groups?
Yes. replace all text by the capture group:
$ echo 'Number 123 inside text' \
| sed 's/[^0-9]*\([0-9]\{1,\}\)[^0-9]*/\1/'
123
s/[^0-9]* # several non-digits
\([0-9]\{1,\}\) # followed by one or more digits
[^0-9]* # and followed by more non-digits.
/\1/ # gets replaced only by the digits.
Or with extended syntax (less backquotes and allow the use of +):
$ echo 'Number 123 in text' \
| sed -E 's/[^0-9]*([0-9]+)[^0-9]*/\1/'
123
To avoid printing the original text when there is no number, use:
$ echo 'Number xxx in text' \
| sed -En 's/[^0-9]*([0-9]+)[^0-9]*/\1/p'
And to match several numbers (and also print them):
$ echo 'N 123 in 456 text' \
| sed -En 's/[^0-9]*([0-9]+)[^0-9]*/\1 /gp'
123 456
That works for any count of digit runs:
$ str='Test Num(s) 123 456 7899900 contained as0018166df in text'
$ echo "$str" \
| sed -En 's/[^0-9]*([0-9]{1,})[^0-9]*/\1 /gp'
123 456 7899900 0018166
Which is very similar to the grep command:
$ str='Test Num(s) 123 456 7899900 contained as0018166df in text'
$ echo "$str" | grep -Po '\d+'
123
456
7899900
0018166
and pattern:
/([\d]+)/
Sed does not recognize the '\d' (shortcut) syntax. The ascii equivalent used above [0-9]
is not exactly equivalent. The only alternative solution is to use a character class: '[[:digit:]]`.
The selected answer use such "character classes" to build a solution:
$ str='This is a sample 123 text and some 987 numbers'
$ echo "$str" | sed -rn 's/[^[:digit:]]*([[:digit:]]+)[^[:digit:]]+([[:digit:]]+)[^[:digit:]]*/\1 \2/p'
That solution only works for (exactly) two runs of digits.
Of course, as the answer is being executed inside the shell, we can define a couple of variables to make such answer shorter:
$ str='This is a sample 123 text and some 987 numbers'
$ d=[[:digit:]] D=[^[:digit:]]
$ echo "$str" | sed -rn "s/$D*($d+)$D+($d+)$D*/\1 \2/p"
But, as has been already explained, using a s/…/…/gp
command is better:
$ str='This is 75577 a sam33ple 123 text and some 987 numbers'
$ d=[[:digit:]] D=[^[:digit:]]
$ echo "$str" | sed -rn "s/$D*($d+)$D*/\1 /gp"
75577 33 123 987
That will cover both repeated runs of digits and writing a short(er) command.
Assuming SQL Server 2000, the following StackOverflow question should address your problem.
If using SQL Server 2005/2008, you can use the following code (taken from here):
select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable
SELECT id, amount
FROM report
WHERE type='P'
UNION
SELECT id, (amount * -1) AS amount
FROM report
WHERE type = 'N'
ORDER BY id;
it really depends on your application. If you're looping through hundreds of words and want to append them all into a list, .join()
is better. But if you're putting together a long sentence, you're better off using +=
.
The stash command will stash any changes you have made since your last commit. In your case there is no reason to stash if you are gonna continue working on it the next day. I would only use stash to undo changes that you don't want to commit.
(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).
In your server this line:
var data = udpServer.Receive(ref groupEP);
re-assigns groupEP
from what you had to a the address you receive something on.
This line:
udpServer.Send(new byte[] { 1 }, 1);
Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:
UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);
while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP);
udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data
}
Also if you have server and client on the same machine you should have them on different ports.
You don't say what system you're using, but as you already have some answers that may or may not work for Windows, I'll answer for POSIX systems.
In POSIX, keyboard input comes through something called a terminal interface, which by default buffers lines of input until Return/Enter is hit, so as to deal properly with backspace. You can change that with the tcsetattr call:
#include <termios.h>
struct termios info;
tcgetattr(0, &info); /* get current terminal attirbutes; 0 is the file descriptor for stdin */
info.c_lflag &= ~ICANON; /* disable canonical mode */
info.c_cc[VMIN] = 1; /* wait until at least one keystroke available */
info.c_cc[VTIME] = 0; /* no timeout */
tcsetattr(0, TCSANOW, &info); /* set immediately */
Now when you read from stdin (with getchar()
, or any other way), it will return characters immediately, without waiting for a Return/Enter. In addition, backspace will no longer 'work' -- instead of erasing the last character, you'll read an actual backspace character in the input.
Also, you'll want to make sure to restore canonical mode before your program exits, or the non-canonical handling may cause odd effects with your shell or whoever invoked your program.
This is older but placing this here for my reference too. boto3.resource is just implementing the default Session, you can pass through boto3.resource session details.
Help on function resource in module boto3:
resource(*args, **kwargs)
Create a resource service client by name using the default session.
See :py:meth:`boto3.session.Session.resource`.
https://github.com/boto/boto3/blob/86392b5ca26da57ce6a776365a52d3cab8487d60/boto3/session.py#L265
you can see that it just takes the same arguments as Boto3.Session
import boto3
S3 = boto3.resource('s3', region_name='us-west-2', aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY)
S3.Object( bucket_name, key_name ).delete()
In typescript it is possible to do an instanceof
check in an if statement and you will have access to the same variable with the Typed
properties.
So let's say MarkerSymbolInfo
has a property on it called marker
. You can do the following:
if (symbolInfo instanceof MarkerSymbol) {
// access .marker here
const marker = symbolInfo.marker
}
It's a nice little trick to get the instance of a variable using the same variable without needing to reassign it to a different variable name.
Check out these two resources for more information:
This is a CSS trick, not a formal solution. I leave the code with the period black because it helps me position the element. Afterward, color your content (color:white) and (margin-top:-5px or so) to make it as though the period is not there.
div.yourdivname:after {
content: ".";
border-bottom:1px solid grey;
width:60%;
display:block;
margin:0 auto;
}
To answer your question with a working example:
<script type="text/javascript">
function DownloadJSON2CSV(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = new Array();
for (var index in array[i]) {
line.push('"' + array[i][index] + '"');
}
str += line.join(';');
str += '\r\n';
}
window.open( "data:text/csv;charset=utf-8," + encodeURIComponent(str));
}
</script>
For Swift4 to get weekday from string
func getDayOfWeek(today:String)->Int {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let todayDate = formatter.date(from: today)!
let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
let myComponents = myCalendar.components(NSCalendar.Unit.weekday, from: todayDate)
let weekDay = myComponents.weekday
return weekDay!
}
let weekday = getDayOfWeek(today: "2018-10-10")
print(weekday) // 4
I've meet the probleme recently. The trouble is coming when the filename lenght is greather than 20 characters. So the bypass is to change your filename length, but the trick is also a good one.
$.ajaxSetup({async: false}); // passage en mode synchrone
$.ajax({
url: pathpays,
success: function(data) {
//debug(data);
$(data).find("a:contains(.png),a:contains(.jpg)").each(function() {
var image = $(this).attr("href");
// will loop through
debug("Found a file: " + image);
text += '<img class="arrondie" src="' + pathpays + image + '" />';
});
text = text + '</div>';
//debug(text);
}
});
After more investigation the trouble is coming from ajax request: Put an eye to the html code returned by ajax:
<a href="Paris-Palais-de-la-cite%20-%20Copie.jpg">Paris-Palais-de-la-c..></a>
</td>
<td align="right">2015-09-05 09:50 </td>
<td align="right">4.3K</td>
<td> </td>
</tr>
As you can see the filename is splitted after the character 20, so the $(data).find("a:contains(.png))
is not able to find the correct extention.
But if you check the value of the href
parameter it contents the fullname of the file.
I dont know if I can to ask to ajax to return the full filename in the text area?
Hope to be clear
I've found the right test to gather all files:
$(data).find("[href$='.jpg'],[href$='.png']").each(function() {
var image = $(this).attr("href");
You can use strpos
and strrpos
$bStartsWith = strpos($sHaystack, $sNeedle) == 0;
$bEndsWith = strrpos($sHaystack, $sNeedle) == strlen($sHaystack)-strlen($sNeedle);
I'd get a logic analyzer and wire it up to the serial port. I think there are probably only two lines you need (Tx/Rx), so there should be plenty of cheap logic analyzers available. You don't have a clock line handy though, so that could get tricky.
Your issue is, that you have an apache webserver already running that is already using port 80. So, you can either:
Kill apache: You should probably do this via /etc/init.d/apache2 stop
, rather than simply killing them.
Deploy your flask app in your apache process, as flask in apache describes.
Use screen. It is very simple to use and works like vnc for terminals. http://www.bangmoney.org/presentations/screen.html
I've found that using the Moment.js library with some of the concepts described here (comparing Jan to June) works very well.
This simple function will return whether the timezone that the user is in observes Daylight Saving Time:
function HasDST() {
return moment([2017, 1, 1]).isDST() != moment([2017, 6, 1]).isDST();
}
A simple way to check that this works (on Windows) is to change your timezone to a non DST zone, for example Arizona will return false, whereas EST or PST will return true.
Run SQL Server Management Studio as an administrator (right-click the shortcut/exe, then select "Run as Administrator"), then try to restore.
Here is what needs to go in D1: =VLOOKUP(C1, $A$1:$B$4, 2, FALSE)
You should then be able to copy this down to the rest of column D.
This worked like a charm for me, of-course it requires super-user privileges :-)
# hcitool cc <target-bdaddr>; hcitool auth <target-bdaddr>
To get <target-bdaddr>
you may issue below command:
$ hcitool scan
Note: Exclude #
& $
as they are command line prompts.
In Java, char is technically a "16-bit integer", so you can simply cast it to int and you'll get it's code. From Oracle:
The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
So you can simply cast it to int.
char registered = '®';
System.out.println(String.format("This is an int-code: %d", (int) registered));
System.out.println(String.format("And this is an hexa code: %x", (int) registered));
Two solutions: 1- if the type of the target column is [nvarchar] it should be change to [varchar]
2- Add a "Derived Column" component to the SSIS package and add a new column with the following expression:
(DT_WSTR, «length») [ColumnName]
Length is the length of the column in the target table and ColumnName is the name of the column in the target table. finally at the mapping part you should use this new added column instead of the original column.
This worked for me.
Code to simply get the contents as text instead of html:
'html_text' parameter is the string which you will pass in this function to get the text
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_text, 'lxml')
text = soup.get_text()
print(text)
Regarding to netbeans, you could set max heap size to solve the problem.
Go to 'Run', then --> 'Set Project Configuration' --> 'Customise' --> 'run' of its popped up window --> 'VM Option' --> fill in '-Xms2048m -Xmx2048m'.
See in the android sdk directory.
In \platforms\android-X\data\res\values\themes.xml
:
<item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
<item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
<item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>
In \platforms\android-X\data\res\values\styles.xml
:
<style name="TextAppearance.Large">
<item name="android:textSize">22sp</item>
</style>
<style name="TextAppearance.Medium">
<item name="android:textSize">18sp</item>
</style>
<style name="TextAppearance.Small">
<item name="android:textSize">14sp</item>
<item name="android:textColor">?textColorSecondary</item>
</style>
TextAppearance.Large
means style is inheriting from TextAppearance
style, you have to trace it also if you want to see full definition of a style.
Link: http://developer.android.com/design/style/typography.html
Until the end of 2014, a common source of this error was omitting the mandatory sensor
parameter from the request, as below. However since then this is no longer required:
The sensor Parameter
The Google Maps API previously required that you include the sensor parameter to indicate whether your application used a sensor to determine the user's location. This parameter is no longer required.
Did you specify the sensor
parameter on the request?
"REQUEST_DENIED" indicates that your request was denied, generally because of lack of a sensor parameter.
sensor (required) — Indicates whether or not the geocoding request comes from a device with a location sensor. This value must be either true or false
See this article: http://www.unilogica.com/mysql-innodb-recovery/ (It's in portuguese)
Are explained how to use innodb_force_recovery and innodb_file_per_table. I discovered this after need to recovery a crashed database with a single ibdata1.
Using innodb_file_per_table, all tables in InnoDB will create a separated table file, like MyISAM.
If you have access to a linux box with mdbtools installed, you can use this Bash shell script (save as mdbconvert.sh):
#!/bin/bash
TABLES=$(mdb-tables -1 $1)
MUSER="root"
MPASS="yourpassword"
MDB="$2"
MYSQL=$(which mysql)
for t in $TABLES
do
$MYSQL -u $MUSER -p$MPASS $MDB -e "DROP TABLE IF EXISTS $t"
done
mdb-schema $1 mysql | $MYSQL -u $MUSER -p$MPASS $MDB
for t in $TABLES
do
mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t | $MYSQL -u $MUSER -p$MPASS $MDB
done
To invoke it simply call it like this:
./mdbconvert.sh accessfile.mdb mysqldatabasename
It will import all tables and all data.
No, destructors are called automatically in the reverse order of construction. (Base classes last). Do not call base class destructors.
In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string.
\xXX is for chars < 127, and \uXXXX for Unicode, so armed with this knowledge you can create a robust JSEncode function for all characters that are out of the usual whitelist.
For example,
<a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a>
I also had this problem recently, and it was the SELinux which caused it. I was trying to have the post-commit of subversion to notify Jenkins that the code has change so Jenkins would do a build and deploy to Nexus.
I had to do the following to get it to work.
1) First I checked if SELinux is enabled:
less /selinux/enforce
This will output 1 (for on) or 0 (for off)
2) Temporary disable SELinux:
echo 0 > /selinux/enforce
Now test see if it works now.
3) Enable SELinux:
echo 1 > /selinux/enforce
Change the policy for SELinux.
4) First view the current configuration:
/usr/sbin/getsebool -a | grep httpd
This will give you: httpd_can_network_connect --> off
5) Set this to on and your post-commit will work with SELinux:
/usr/sbin/setsebool -P httpd_can_network_connect on
Now it should be working again.
Use the LocationManager
.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation()
doesn't block - which means it will return null
if no position is currently available - so you probably want to have a look at passing a LocationListener
to the requestLocationUpdates()
method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION
permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the ACCESS_COARSE_LOCATION
permission for when GPS isn't available and select your location provider with the getBestProvider()
method.
JLabel label = new JLabel("fax", SwingConstants.RIGHT);
This is absolutely possible. Although you shouldn't do it unless you know what you are dealing with. Took me about 2 days to figure it out. Here is a stored procedure where i enter: ---database name (schema name is "_" for readability) ---table name ---column ---column data type (column added is always null, otherwise you won't be able to insert) ---the position of the new column.
Since I'm working with tables from SAM toolkit (and some of them have > 80 columns) , the typical variable won't be able to contain the query. That forces the need of external file. Now be careful where you store that file and who has access on NTFS and network level.
Cheers!
USE [master]
GO
/****** Object: StoredProcedure [SP_Set].[TrasferDataAtColumnLevel] Script Date: 8/27/2014 2:59:30 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [SP_Set].[TrasferDataAtColumnLevel]
(
@database varchar(100),
@table varchar(100),
@column varchar(100),
@position int,
@datatype varchar(20)
)
AS
BEGIN
set nocount on
exec ('
declare @oldC varchar(200), @oldCDataType varchar(200), @oldCLen int,@oldCPos int
create table Test ( dummy int)
declare @columns varchar(max) = ''''
declare @columnVars varchar(max) = ''''
declare @columnsDecl varchar(max) = ''''
declare @printVars varchar(max) = ''''
DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR
select column_name, data_type, character_maximum_length, ORDINAL_POSITION from ' + @database + '.INFORMATION_SCHEMA.COLUMNS where table_name = ''' + @table + '''
OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO @oldC, @oldCDataType, @oldCLen, @oldCPos WHILE @@FETCH_STATUS = 0 BEGIN
if(@oldCPos = ' + @position + ')
begin
exec(''alter table Test add [' + @column + '] ' + @datatype + ' null'')
end
if(@oldCDataType != ''timestamp'')
begin
set @columns += @oldC + '' , ''
set @columnVars += ''@'' + @oldC + '' , ''
if(@oldCLen is null)
begin
if(@oldCDataType != ''uniqueidentifier'')
begin
set @printVars += '' print convert('' + @oldCDataType + '',@'' + @oldC + '')''
set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', ''
exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
end
else
begin
set @printVars += '' print convert(varchar(50),@'' + @oldC + '')''
set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', ''
exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
end
end
else
begin
if(@oldCLen < 0)
begin
set @oldCLen = 4000
end
set @printVars += '' print @'' + @oldC
set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + ''('' + convert(character,@oldCLen) + '') , ''
exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + ''('' + @oldCLen + '') null'')
end
end
if exists (select column_name from INFORMATION_SCHEMA.COLUMNS where table_name = ''Test'' and column_name = ''dummy'')
begin
alter table Test drop column dummy
end
FETCH NEXT FROM MY_CURSOR INTO @oldC, @oldCDataType, @oldCLen, @oldCPos END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR
set @columns = reverse(substring(reverse(@columns), charindex('','',reverse(@columns)) +1, len(@columns)))
set @columnVars = reverse(substring(reverse(@columnVars), charindex('','',reverse(@columnVars)) +1, len(@columnVars)))
set @columnsDecl = reverse(substring(reverse(@columnsDecl), charindex('','',reverse(@columnsDecl)) +1, len(@columnsDecl)))
set @columns = replace(replace(REPLACE(@columns, '' '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnVars = replace(replace(REPLACE(@columnVars, '' '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnsDecl = replace(replace(REPLACE(@columnsDecl, '' '', ''''), char(9) + char(9),'' ''),char(9), '''')
set @printVars = REVERSE(substring(reverse(@printVars), charindex(''+'',reverse(@printVars))+1, len(@printVars)))
create table query (id int identity(1,1), string varchar(max))
insert into query values (''declare '' + @columnsDecl + ''
DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR '')
insert into query values (''select '' + @columns + '' from ' + @database + '._.' + @table + ''')
insert into query values (''OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO '' + @columnVars + '' WHILE @@FETCH_STATUS = 0 BEGIN '')
insert into query values (@printVars )
insert into query values ( '' insert into Test ('')
insert into query values (@columns)
insert into query values ( '') values ( '' + @columnVars + '')'')
insert into query values (''FETCH NEXT FROM MY_CURSOR INTO '' + @columnVars + '' END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR'')
declare @path varchar(100) = ''C:\query.sql''
declare @query varchar(500) = ''bcp "select string from query order by id" queryout '' + @path + '' -t, -c -S '' + @@servername + '' -T''
exec master..xp_cmdshell @query
set @query = ''sqlcmd -S '' + @@servername + '' -i '' + @path
EXEC xp_cmdshell @query
set @query = ''del '' + @path
exec xp_cmdshell @query
drop table ' + @database + '._.' + @table + '
select * into ' + @database + '._.' + @table + ' from Test
drop table query
drop table Test ')
END
From here:
ArrayList is internally backed by Array in Java, any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array.
In terms of performance Array and ArrayList provides similar performance in terms of constant time for adding or getting element if you know index. Though automatic resize of ArrayList may slow down insertion a bit Both Array and ArrayList is core concept of Java and any serious Java programmer must be familiar with these differences between Array and ArrayList or in more general Array vs List.
Beginning PowerShell 5.0 New-Item
, Remove-Item
, and Get-ChildItem
have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item
accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.
New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"
Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.
Anyway if you want to create a Run As Administrator shortcut using Powershell you can use
$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)
If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.
I Recommend you implement INotifyPropertyChanged and change your databinding code to this:
this.textBox.DataBindings.Add("Text",
this.Food,
"Name",
false,
DataSourceUpdateMode.OnPropertyChanged);
That'll fix it.
Note that the default DataSourceUpdateMode
is OnValidation
, so if you don't specify OnPropertyChanged
, the model object won't be updated until after your validations have occurred.
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
You can now (as of Webpack v5.0.0) specify a unique output path for each entry using the new "descriptor" syntax (https://webpack.js.org/configuration/entry-context/#entry-descriptor) –
module.exports = {
entry: {
home: { import: './home.js', filename: 'unique/path/1/[name][ext]' },
about: { import: './about.js', filename: 'unique/path/2/[name][ext]' }
}
};
You can access the values in a vector just as you access any other array.
for (int i = 0; i < v.size(); i++)
{
v[i] -= 1;
}
If appears to me that rows where Visible is set to false won't be accessible, that they are removed from the DOM rather than hidden, so I also used the Display: None approach. In my case, I wanted to have a hidden column that contained the key of the Row. To me, this declarative approach is a little cleaner than some of the other approaches that use code.
<style>
.HiddenCol{display:none;}
</style>
<%--ROW ID--%>
<asp:TemplateField HeaderText="Row ID">
<HeaderStyle CssClass="HiddenCol" />
<ItemTemplate>
<asp:Label ID="lblROW_ID" runat="server" Text='<%# Bind("ROW_ID") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Right" CssClass="HiddenCol" />
<EditItemTemplate>
<asp:TextBox ID="txtROW_ID" runat="server" Text='<%# Bind("ROW_ID") %>'></asp:TextBox>
</EditItemTemplate>
<FooterStyle CssClass="HiddenCol" />
</asp:TemplateField>
Another simple way get by using findall in yii
$id =101;
$comments = EmailArchive::model()->findAll(array("condition"=>"':email_id'=$id"));
foreach($comments as $comments_1)
{
echo "email:".$comments_1['email_id'];
}
TLDR; Performance-wise Any
seems to be slower (if I have set this up properly to evaluate both values at almost same time)
var list1 = Generate(1000000);
var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
if (forceListEval != "sdsdf")
{
var s = string.Empty;
var start2 = DateTime.Now;
if (!list1.Exists(o => o == "0123456789012"))
{
var end2 = DateTime.Now;
s += " Exists: " + end2.Subtract(start2);
}
var start1 = DateTime.Now;
if (!list1.Any(o => o == "0123456789012"))
{
var end1 = DateTime.Now;
s +=" Any: " +end1.Subtract(start1);
}
if (!s.Contains("sdfsd"))
{
}
testing list generator:
private List<string> Generate(int count)
{
var list = new List<string>();
for (int i = 0; i < count; i++)
{
list.Add( new string(
Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 13)
.Select(s =>
{
var cryptoResult = new byte[4];
new RNGCryptoServiceProvider().GetBytes(cryptoResult);
return s[new Random(BitConverter.ToInt32(cryptoResult, 0)).Next(s.Length)];
})
.ToArray()));
}
return list;
}
With 10M records
" Any: 00:00:00.3770377 Exists: 00:00:00.2490249"
With 5M records
" Any: 00:00:00.0940094 Exists: 00:00:00.1420142"
With 1M records
" Any: 00:00:00.0180018 Exists: 00:00:00.0090009"
With 500k, (I also flipped around order in which they get evaluated to see if there is no additional operation associated with whichever runs first.)
" Exists: 00:00:00.0050005 Any: 00:00:00.0100010"
With 100k records
" Exists: 00:00:00.0010001 Any: 00:00:00.0020002"
It would seem Any
to be slower by magnitude of 2.
Edit: For 5 and 10M records I changed the way it generates the list and Exists
suddenly became slower than Any
which implies there's something wrong in the way I am testing.
New testing mechanism:
private static IEnumerable<string> Generate(int count)
{
var cripto = new RNGCryptoServiceProvider();
Func<string> getString = () => new string(
Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 13)
.Select(s =>
{
var cryptoResult = new byte[4];
cripto.GetBytes(cryptoResult);
return s[new Random(BitConverter.ToInt32(cryptoResult, 0)).Next(s.Length)];
})
.ToArray());
var list = new ConcurrentBag<string>();
var x = Parallel.For(0, count, o => list.Add(getString()));
return list;
}
private static void Test()
{
var list = Generate(10000000);
var list1 = list.ToList();
var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
if (forceListEval != "sdsdf")
{
var s = string.Empty;
var start1 = DateTime.Now;
if (!list1.Any(o => o == "0123456789012"))
{
var end1 = DateTime.Now;
s += " Any: " + end1.Subtract(start1);
}
var start2 = DateTime.Now;
if (!list1.Exists(o => o == "0123456789012"))
{
var end2 = DateTime.Now;
s += " Exists: " + end2.Subtract(start2);
}
if (!s.Contains("sdfsd"))
{
}
}
Edit2: Ok so to eliminate any influence from generating test data I wrote it all to file and now read it from there.
private static void Test()
{
var list1 = File.ReadAllLines("test.txt").Take(500000).ToList();
var forceListEval = list1.SingleOrDefault(o => o == "0123456789012");
if (forceListEval != "sdsdf")
{
var s = string.Empty;
var start1 = DateTime.Now;
if (!list1.Any(o => o == "0123456789012"))
{
var end1 = DateTime.Now;
s += " Any: " + end1.Subtract(start1);
}
var start2 = DateTime.Now;
if (!list1.Exists(o => o == "0123456789012"))
{
var end2 = DateTime.Now;
s += " Exists: " + end2.Subtract(start2);
}
if (!s.Contains("sdfsd"))
{
}
}
}
10M
" Any: 00:00:00.1640164 Exists: 00:00:00.0750075"
5M
" Any: 00:00:00.0810081 Exists: 00:00:00.0360036"
1M
" Any: 00:00:00.0190019 Exists: 00:00:00.0070007"
500k
" Any: 00:00:00.0120012 Exists: 00:00:00.0040004"
To start video
var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);
To stop video
var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);
You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters
works for both vimeo and youtube on FF & Chrome
struct Bool {
int true;
int false;
}
int main() {
/* bool is a variable of data type – bool*/
struct Bool bool;
/*below I’m accessing struct members through variable –bool*/
bool = {1,0};
print("Student Name is: %s", bool.true);
return 0;
}
Hope this is something what you are trying to do :
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Test {
private Map ttp = new HashMap();
public void test() {
Field declaredField = null;
try {
declaredField = Test.class.getDeclaredField("ttp");
boolean accessible = declaredField.isAccessible();
declaredField.setAccessible(true);
ConcurrentHashMap<Object, Object> concHashMap = new ConcurrentHashMap<Object, Object>();
concHashMap.put("key1", "value1");
declaredField.set(this, concHashMap);
Object value = ttp.get("key1");
System.out.println(value);
declaredField.setAccessible(accessible);
} catch (NoSuchFieldException
| SecurityException
| IllegalArgumentException
| IllegalAccessException e) {
e.printStackTrace();
}
}
public static void main(String... args) {
Test test = new Test();
test.test();
}
}
It prints :
value1
I had the following problem:
I had a Android phone without drivers, and it could not be recognized by the Windows 8.1. Neither as phone, neither as USB storage device.
I searched Device manager.
I opened Device manager, I right click on Android Phone->Android Composite Interface.
I selected "Update Driver Software"
I choose "Browse My Computer for Driver Software"
Then I choose "Let me pick from a list of devices"
I selected "USB Composite Device"
A new USB device is added to the list, and I can connect to my phone using adb and Android SDK.
Also I can use the phone as storage device.
Good luck
Very first will declare outer Arraylist which will contain another inner Arraylist inside it
ArrayList> CompletesystemStatusArrayList; ArrayList systemStatusArrayList
CompletesystemStatusArrayList=new ArrayList
systemStatusArrayList=new ArrayList();
systemStatusArrayList.add("1");
systemStatusArrayList.add("2");
systemStatusArrayList.add("3");
systemStatusArrayList.add("4");
systemStatusArrayList.add("5");
systemStatusArrayList.add("6");
systemStatusArrayList.add("7");
systemStatusArrayList.add("8");
CompletesystemStatusArrayList.add(systemStatusArrayList);
In pure JS adding next option to select is easier and more direct
mySelect.innerHTML+= `<option value="${key}">${value}</option>`;
let selectValues = { "1": "test 1", "2": "test 2" };
for(let key in selectValues) {
mySelect.innerHTML+= `<option value="${key}">${selectValues[key]}</option>`;
}
_x000D_
<select id="mySelect">
<option value="0" selected="selected">test 0</option>
</select>
_x000D_
Your CSS is actually setting the rest of the document to not show overflow therefore the document itself isn't scrolling. The easiest fix for this is bind the event to the thing that is scrolling, which in your case is div#page
.
So its easy as changing:
$(document).scroll(function() { // OR $(window).scroll(function() {
didScroll = true;
});
to
$('div#page').scroll(function() {
didScroll = true;
});
You can get the mouse positions by using this snippet:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
};
}
This code takes into account both changing coordinates to canvas space (evt.clientX - rect.left
) and scaling when canvas logical size differs from its style size (/ (rect.right - rect.left) * canvas.width
see: Canvas width and height in HTML5).
Example: http://jsfiddle.net/sierawski/4xezb7nL/
Source: jerryj comment on http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
For finding the even number we should use
select num from table where ( num % 2 ) = 0
From the definition in objc.h
:
#if (TARGET_OS_IPHONE && __LP64__) || TARGET_OS_WATCH
typedef bool BOOL;
#else
typedef signed char BOOL;
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C"
// even if -funsigned-char is used.
#endif
#define YES ((BOOL)1)
#define NO ((BOOL)0)
So, yes, you can assume that BOOL is a char. You can use the (C99) bool
type, but all of Apple's Objective-C frameworks and most Objective-C/Cocoa code uses BOOL, so you'll save yourself headache if the typedef ever changes by just using BOOL.
Use show/hide method as below
$("div").show();//To Show
$("div").hide();//To Hide
Try below command:
chmod +x gradlew && ./gradlew compileDebug --stacktrace
When pip
tells you that you already have protobuf
,
but PyCharm (or other) tells you that you don't have it,
it means that pip
and PyCharm are using a different Python interpreter.
This is a very common issue, especially on a Mac, with no standard Python package management.
The best way to completely eliminate such issues is using a virtualenv
per Python project, which is essentially a directory of Python packages and environment variable settings to isolate the Python environment of the project from everything else.
Create a virtualenv
for your project like this:
cd project
virtualenv --distribute virtualenv -p /path/to/python/executable
This creates a directory called virtualenv
inside your project.
(Make sure to configure your VCS (for example Git) to ignore this directory.)
To install packages in this virtualenv
, you need to activate the environment variable settings:
. virtualenv/bin/activate
Verify that pip
will use the right Python executable inside the virtualenv
, by running pip -V
. It should tell you the Python library path used, which should be inside the virtualenv
.
Now you can use pip
to install protobuf
as you did.
And finally, you need to make PyCharm use this virtualenv
instead of the system libraries. Somewhere in the project settings you can configure an interpreter for the project, select the Python executable inside the virtualenv
.
A perl oneliner would do: perl -i.bak -pe 's/[^[:ascii:]]//g' <your file>
-i
says that the file is going to be edited inplace, and the backup is going to be saved with extension .bak
.
if you want to open incognito window, put the command below:
start chrome /incognito
Another way to do that through concat
var arr = [1, 2, 3, 4, 5, 6, 7];_x000D_
console.log([0].concat(arr));
_x000D_
The difference between concat
and unshift
is that concat
returns a new array. The performance between them could be found here.
function fn_unshift() {
arr.unshift(0);
return arr;
}
function fn_concat_init() {
return [0].concat(arr)
}
Here is the test result
import java.math.*;
public class TestRound11 {
public static void main(String args[]){
double d = 3.1537;
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
// output is 3.15
System.out.println(d + " : " + round(d, 2));
// output is 3.154
System.out.println(d + " : " + round(d, 3));
}
public static double round(double d, int decimalPlace){
// see the Javadoc about why we use a String in the constructor
// http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
}
This will add a global function to access to the queryString variables as a map.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query( [queryString] )' which returns an object
// of querystring keys and their values. An optional string parameter can be used as
// an alternative to 'window.location.search'.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query.makeString( object, [addQuestionMark] )'
// which returns a queryString from an object. An optional boolean parameter can be
// used to toggle a leading question mark.
// -------------------------------------------------------------------------------------
if (!window.location.query) {
window.location.query = function (source) {
var map = {};
source = source || this.search;
if ("" != source) {
var groups = source, i;
if (groups.indexOf("?") == 0) {
groups = groups.substr(1);
}
groups = groups.split("&");
for (i in groups) {
source = groups[i].split("=",
// For: xxx=, Prevents: [xxx, ""], Forces: [xxx]
(groups[i].slice(-1) !== "=") + 1
);
// Key
i = decodeURIComponent(source[0]);
// Value
source = source[1];
source = typeof source === "undefined"
? source
: decodeURIComponent(source);
// Save Duplicate Key
if (i in map) {
if (Object.prototype.toString.call(map[i]) !== "[object Array]") {
map[i] = [map[i]];
}
map[i].push(source);
}
// Save New Key
else {
map[i] = source;
}
}
}
return map;
}
window.location.query.makeString = function (source, addQuestionMark) {
var str = "", i, ii, key;
if (typeof source == "boolean") {
addQuestionMark = source;
source = undefined;
}
if (source == undefined) {
str = window.location.search;
}
else {
for (i in source) {
key = "&" + encodeURIComponent(i);
if (Object.prototype.toString.call(source[i]) !== "[object Array]") {
str += key + addUndefindedValue(source[i]);
}
else {
for (ii = 0; ii < source[i].length; ii++) {
str += key + addUndefindedValue(source[i][ii]);
}
}
}
}
return (addQuestionMark === false ? "" : "?") + str.substr(1);
}
function addUndefindedValue(source) {
return typeof source === "undefined"
? ""
: "=" + encodeURIComponent(source);
}
}
Enjoy.