You can configure the ObjectMapper as a bean in your Spring xml file. What holds a reference to the ObjectMapper is the MappingJacksonJsonView
class. You then need to attach the view to a ViewResolver.
Something like this should work:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="html" value="text/html" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prefixJson" value="false" />
<property name="objectMapper" value="customObjectMapper" />
</bean>
</list>
</property>
</bean>
Where customObjectMapper
is defined elsewhere in the xml file. Note that you can directly set Spring property values with the Enums Jackson defines; see this question.
Also, ContentNegotiatingViewResolver probably isn't required, it's just the code I am using in an existing project.
To your secondary question
var elem1 = $('#elem1'),
elem2 = $('#elem2'),
elem3 = $('#elem3');
You can use the variable as the replacement of selector.
elem1.css({'display':'none'}); //will work
In the below case selector is already stored in a variable.
$(elem1,elem2,elem3).css({'display':'none'}); // will not work
./gradlew
Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. .
means "current directory".
I read and read and read to figure out why I was getting a class not found error, it turns out the manifest.mf had an error in the line:
Main-Class: com.example.MainClass
I fixed the error by going to Project Properties dialog (right-click Project Files), then Run and Main Class and corrected whatever Netbeans decided to put here. Netbean inserted the project name instead of the class name. No idea why. Probably inebriated on muratina...
Using Java 8 you can do:
List<Object> list = ...;
List<String> strList = list.stream()
.map( Object::toString )
.collect( Collectors.toList() );
int index = std::distance(std::begin(myArray), std::find(begin(myArray), end(std::myArray), VALUE));
Returns an invalid index (length of the array) if not found.
From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.
The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.
If you wanted to use different proxy settings to the current user then you would need to code
WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);
or
WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);
You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call
webRequest.Proxy.GetProxy(new Uri("http://google.com.au"))
to see the actual details of the proxy server that would be used.
There seems to be some debate about whether you can set webRequest.Proxy
or WebRequest.DefaultWebProxy = null
to prevent the use of any proxy. This seems to work OK for me but you could set it to new DefaultProxy()
with no parameters to get the required behaviour. Another thing to check is that if a proxy element exists in your applications config file, the .NET Framework will NOT use the proxy settings in Internet Explorer.
The MSDN Magazine article Take the Burden Off Users with Automatic Configuration in .NET gives further details of what is happening under the hood.
It might be a good idea to use arithmetic expressions if you're dealing with numbers.
if (( $# != 1 )); then
>&2 echo "Illegal number of parameters"
fi
>&2
is used to write the error message to stderr.
A simple, although awk-less solution in bash:
while IFS=, read -r a a a b; do echo "$a"; done <inputfile
It works faster for small files (<100 lines) then awk as it uses less resources (avoids calling the expensive fork
and execve
system calls).
EDIT from Ed Morton (sorry for hi-jacking the answer, I don't know if there's a better way to address this):
To put to rest the myth that shell will run faster than awk for small files:
$ wc -l file
99 file
$ time while IFS=, read -r a a a b; do echo "$a"; done <file >/dev/null
real 0m0.016s
user 0m0.000s
sys 0m0.015s
$ time awk -F, '{print $3}' file >/dev/null
real 0m0.016s
user 0m0.000s
sys 0m0.015s
I expect if you get a REALY small enough file then you will see the shell script run in a fraction of a blink of an eye faster than the awk script but who cares?
And if you don't believe that it's harder to write robust shell scripts than awk scripts, look at this bug in the shell script you posted:
$ cat file
a,b,-e,d
$ cut -d, -f3 file
-e
$ awk -F, '{print $3}' file
-e
$ while IFS=, read -r a a a b; do echo "$a"; done <file
$
You were close. format=
needs to be added to the as.Date
call:
mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"
if you're receiving the error in parameter, so keep any
or any[]
type of input like below
getOptionLabel={(option: any) => option!.name}
<Autocomplete
options={tests}
getOptionLabel={(option: any) => option!.name}
....
/>
After validation and before INSERT check if username already exists, using mysqli(procedural). This works:
//check if username already exists
include 'phpscript/connect.php'; //connect to your database
$sql = "SELECT username FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$usernameErr = "username already taken"; //takes'em back to form
} else { // go on to INSERT new record
In VS, right click your project, select "Add Reference...", and you will see all the namespaces that exist in your GAC. Choose Microsoft.SqlServer.Management.RegisteredServers and click OK, and you should be good to go
EDIT:
That is the way you want to do this most of the time. However, after a bit of poking around I found this issue on MS Connect. MS says it is a known deployment issue, and they don't have a work around. The guy says if he copies the dll from the GAC folder and drops it in his bin, it works.
Access is a great multi-user database. It has lots of built in features to handle the multi-user situation. In fact, it is so very popular because it is such a great multi-user database. There is an upper limit on how many users can all use the database at the same time doing updates and edits - depending on how knowledgeable the developer is about access and how the database has been designed - anywhere from 20 users to approx 50 users. Some access databases can be built to handle up to 50 concurrent users, while many others can handle 20 or 25 concurrent users updating the database. These figures have been observed for databases that have been in use for several or more years and have been discussed many times on the access newsgroups.
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
I know this is old, but getoptlong wasn't mentioned here and it's probably the best way to parse command line arguments today.
I strongly recommend getoptlong. It's pretty easy to use and works like a charm. Here is an example extracted from the link above
require 'getoptlong'
opts = GetoptLong.new(
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
[ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
[ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
)
dir = nil
name = nil
repetitions = 1
opts.each do |opt, arg|
case opt
when '--help'
puts <<-EOF
hello [OPTION] ... DIR
-h, --help:
show help
--repeat x, -n x:
repeat x times
--name [name]:
greet user by name, if name not supplied default is John
DIR: The directory in which to issue the greeting.
EOF
when '--repeat'
repetitions = arg.to_i
when '--name'
if arg == ''
name = 'John'
else
name = arg
end
end
end
if ARGV.length != 1
puts "Missing dir argument (try --help)"
exit 0
end
dir = ARGV.shift
Dir.chdir(dir)
for i in (1..repetitions)
print "Hello"
if name
print ", #{name}"
end
puts
end
You can call it like this
ruby hello.rb -n 6 --name -- /tmp
In this case I think the best option is to use YAML files as suggested in this answer
I was successful via settings > Terminal > Integrated > Shell: Linux
from there I edited the path of the shell to be /bin/zsh from the default /bin/bash
@charlieParker - here's what i'm seeing for available commands in the command pallette
You can also use ObjectId.isValid like the following :
if (!ObjectId.isValid(userId)) return Error({ status: 422 })
You may need to add a JDK (Java Development Kit) to the installed JRE's within Eclipse
Go to Window->Preferences->Java->Installed JRE's
In the Name column if you do not have a JDK as your default, then you will need to add it.
Click the "Add" Button and locate the JDK on your machine.
You may find it in this location: C:\Program Files\Java\jdk1.x.y
Where x and y are numbers.
If there are no JDK's installed on your machine then download and install the Java SE (Standard Edition) from the Oracle website.
Then do the steps above again. Be sure that it is set as the default JRE to use.
Then go back to the Projects->Generate Javadoc... dialog
Now it should work.
Good Luck.
You Can try This To Run Command Then cmd
Exits
Process.Start("cmd", "/c YourCode")
You Can try This To Run The Command And Let cmd
Wait For More Commands
Process.Start("cmd", "/k YourCode")
Add a file .jslintrc (or .jshintrc in the case of jshint) at the root of your project with the following content:
{
"node": true
}
If you need to just empty the style
of an element then:
element.style.cssText = null;
This should do good. Hope it helps!
According to the Twitter Bootstrap documentation: http://getbootstrap.com/css/#helper-classes-center
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="singlebutton"></label>
<div class="col-md-4 center-block">
<button id="singlebutton" name="singlebutton" class="btn btn-primary center-block">
Next Step!
</button>
</div>
</div>
All the class center-block
does is to tell the element to have a margin of 0 auto, the auto being the left/right margins. However, unless the class text-center or css text-align:center; is set on the parent, the element does not know the point to work out this auto calculation from so will not center itself as anticipated.
See an example of the code above here: https://jsfiddle.net/Seany84/2j9pxt1z/
If you want to search as string, you can cast to text like this:
SELECT * FROM books WHERE price::TEXT LIKE '123%'
You can change the case of String before using it, like this
String name1 = fname.getText().toString().toLowerCase();
String name2 = sname.getText().toString().toLowerCase();
Then continue with rest operation.
The AngularJS source code also has a version inside of angular-sanitize.js.
var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
// Match everything outside of normal chars and " (quote character)
NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;
/**
* Escapes all potentially dangerous characters, so that the
* resulting string can be safely inserted into attribute or
* element text.
* @param value
* @returns {string} escaped text
*/
function encodeEntities(value) {
return value.
replace(/&/g, '&').
replace(SURROGATE_PAIR_REGEXP, function(value) {
var hi = value.charCodeAt(0);
var low = value.charCodeAt(1);
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
}).
replace(NON_ALPHANUMERIC_REGEXP, function(value) {
return '&#' + value.charCodeAt(0) + ';';
}).
replace(/</g, '<').
replace(/>/g, '>');
}
def TimestampMillisec64():
return int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000)
Slight bias to SQL Server
Summary
DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
SQL Server 2008 has date
type though. So just use
CAST(GETDATE() AS DATE)
Edit: To add one day, compare to the day before "zero"
DATEADD(day, DATEDIFF(day, -1, GETDATE()), 0)
From cyberkiwi:
An alternative that does not involve 2 functions is (the +1 can be in or ourside the brackets).
DATEDIFF(DAY, 0, GETDATE() +1)
DateDiff
returns a number but for all purposes this will work as a date wherever you intend to use this expression, except converting it to VARCHAR directly - in which case you would have used the CONVERT approach directly on GETDATE(), e.g.
convert(varchar, GETDATE() +1, 102)
View.INVISIBLE->The View is invisible but it will occupy some space in layout
View.GONE->The View is not visible and it will not occupy any space in layout
Just upgrade pip worked for me:
pip install --upgrade pip
Building on what is mentioned in the comments, the simplest solution would be:
@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {
//whatever
}
class SomeDto {
private List<WhateverBudgerPerDateDTO> budgetPerDate;
//getters setters
}
The solution assumes that the HTTP request you are creating actually has
Content-Type:application/json
instead of text/plain
Something like this?
div {_x000D_
border: 1px solid #202020;_x000D_
margin-top: 25px;_x000D_
margin-left: 25px;_x000D_
width: 158px;_x000D_
height: 158px;_x000D_
padding-top: 25px;_x000D_
-webkit-box-shadow: 0px -4px 3px rgba(50, 50, 50, 0.75);_x000D_
-moz-box-shadow: 0px -4px 3px rgba(50, 50, 50, 0.75);_x000D_
box-shadow: 0px -4px 3px rgba(50, 50, 50, 0.75);_x000D_
}
_x000D_
<div></div>
_x000D_
.block1 {_x000D_
color: red;_x000D_
width: 100px;_x000D_
border: 1px solid green;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.block2 {_x000D_
color: blue;_x000D_
width: 70px;_x000D_
border: 2px solid black;_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
right: 0px;_x000D_
}
_x000D_
<div class='block1'>_x000D_
<p>text</p>_x000D_
<p>text2</p>_x000D_
<div class='block2'>block2</div>_x000D_
</div>
_x000D_
Should do it. Assuming you don't need it to flow.
This might help someone like me that finds this answer when searching for solutions to how Rails handles the class loading ... I found that I had to define a module
whose name matched my filename appropriately, rather than just defining a class:
In file lib/development_mail_interceptor.rb (Yes, I'm using code from a Railscast :))
module DevelopmentMailInterceptor
class DevelopmentMailInterceptor
def self.delivering_email(message)
message.subject = "intercepted for: #{message.to} #{message.subject}"
message.to = "[email protected]"
end
end
end
works, but it doesn't load if I hadn't put the class inside a module.
If you are using SQL Server 2012 and above, you can use FORMATMESSAGE
. eg.
DECLARE @s NVARCHAR(50) = 'World';
DECLARE @d INT = 123;
SELECT FORMATMESSAGE('Hello %s, %d', @s, @d)
-- RETURNS 'Hello World, 123'
More examples from MSDN: FORMATMESSAGE
SELECT FORMATMESSAGE('Signed int %i, %d %i, %d, %+i, %+d, %+i, %+d', 5, -5, 50, -50, -11, -11, 11, 11);
SELECT FORMATMESSAGE('Signed int with leading zero %020i', 5);
SELECT FORMATMESSAGE('Signed int with leading zero 0 %020i', -55);
SELECT FORMATMESSAGE('Unsigned int %u, %u', 50, -50);
SELECT FORMATMESSAGE('Unsigned octal %o, %o', 50, -50);
SELECT FORMATMESSAGE('Unsigned hexadecimal %x, %X, %X, %X, %x', 11, 11, -11, 50, -50);
SELECT FORMATMESSAGE('Unsigned octal with prefix: %#o, %#o', 50, -50);
SELECT FORMATMESSAGE('Unsigned hexadecimal with prefix: %#x, %#X, %#X, %X, %x', 11, 11, -11, 50, -50);
SELECT FORMATMESSAGE('Hello %s!', 'TEST');
SELECT FORMATMESSAGE('Hello %20s!', 'TEST');
SELECT FORMATMESSAGE('Hello %-20s!', 'TEST');
SELECT FORMATMESSAGE('Hello %20s!', 'TEST');
NOTES:
FORMATMESSAGE
comes up as a (harmless) errorUse the static method Guid.NewGuid()
instead of calling the default constructor.
var responseObject = proxy.CallService(new RequestObject
{
Data = "misc. data",
Guid = Guid.NewGuid()
});
You don't need the assignment, list.append(x)
will always append x
to a
and therefore there's no need te redefine a
.
a = []
for i in range(5):
a.append(i)
print(a)
is all you need. This works because list
s are mutable.
Also see the docs on data structures.
basis with the above code, I reflected the code like below, may be it's more suitable:
public String getPath(Uri uri) {
String selectedImagePath;
//1:MEDIA GALLERY --- query from MediaStore.Images.Media.DATA
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor != null){
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
selectedImagePath = cursor.getString(column_index);
}else{
selectedImagePath = null;
}
if(selectedImagePath == null){
//2:OI FILE Manager --- call method: uri.getPath()
selectedImagePath = uri.getPath();
}
return selectedImagePath;
}
There are many other binaries that need to be linked so I think it's much better to try something like sudo update-alternatives --all
and choosing the right alternatives for everything else besides java
and javac
.
why make is sooooo hard people when it can be soooo easy :)
//here is the pull from the form
$your_form_text = $_POST['your_form_text'];
//line 1 fixes the line breaks - line 2 the slashes
$your_form_text = nl2br($your_form_text);
$your_form_text = stripslashes($your_form_text);
//email away
$message = "Comments: $your_form_text";
mail("[email protected]", "Website Form Submission", $message, $headers);
you will obviously need headers and likely have more fields, but this is your textarea take care of
Here is how I add parameters:
sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime))
sprocCommand.Parameters("@Date_Of_Birth").Value = DOB
I am assuming when you write out DOB there are no quotes.
Are you using a third-party control to get the date? I have had problems with the way the text value is generated from some of them.
Lastly, does it work if you type in the .Value attribute of the parameter without referencing DOB?
Try this CSS:
h1 {
left: 0;
line-height: 200px;
margin-top: -100px;
position: absolute;
text-align: center;
top: 50%;
width: 100%;
}
jsFiddle: http://jsfiddle.net/wprw3/
fgets would work for you. here is very good documentation on this :-
http://www.cplusplus.com/reference/cstdio/fgets/
If you don't want to use fgets, following method will work for you :-
int readline(FILE *f, char *buffer, size_t len)
{
char c;
int i;
memset(buffer, 0, len);
for (i = 0; i < len; i++)
{
int c = fgetc(f);
if (!feof(f))
{
if (c == '\r')
buffer[i] = 0;
else if (c == '\n')
{
buffer[i] = 0;
return i+1;
}
else
buffer[i] = c;
}
else
{
//fprintf(stderr, "read_line(): recv returned %d\n", c);
return -1;
}
}
return -1;
}
Your JFrame default close action can be set to "DISPOSE_ON_CLOSE
" instead of EXIT_ON_CLOSE
(why people keep using EXIT_ON_CLOSE is beyond me).
If you have any undisposed windows or non-daemon threads, your application will not terminate. This should be considered a error (and solving it with System.exit is a very bad idea).
The most common culprits are java.util.Timer and a custom Thread you've created. Both should be set to daemon or must be explicitly killed.
If you want to check for all active frames, you can use Frame.getFrames()
. If all Windows/Frames are disposed of, then use a debugger to check for any non-daemon threads that are still running.
You're close. This should do the trick:
new {items = new [] {
new {name = "command" , index = "X", optional = "0"},
new {name = "command" , index = "X", optional = "0"}
}}
If your source was an enumerable of some sort, you might want to do this:
new {items = source.Select(item => new
{
name = item.Name, index = item.Index, options = item.Optional
})};
Here you are not fitting a normal distribution. Replacing sns.distplot(data)
by sns.distplot(data, fit=norm, kde=False)
should do the trick.
To eliminate the need for the cmd variable, you can do this:
eval 'mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".
The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.
ffmpeg
vs the fake oneFor a while both Libav and FFmpeg separately developed their own version of ffmpeg
.
Libav then renamed their bizarro ffmpeg
to avconv
to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv
instead of their counterfeit version of ffmpeg
. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.
This message was removed upstream when the fake "ffmpeg
" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.
In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1
. Unfortunately the new "deprecated" message has caused additional user confusion.
Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg
is back in the repositories again.
To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.
If you are using avconv
then you are using Libav. If you are using ffmpeg
you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.
Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h
header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg
or avconv
and viewing the console output.
ffmpeg
The real ffmpeg
is in the repository, so you can install it with:
apt-get install ffmpeg
Your options are:
ffmpeg
,ffmpeg
,These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.
Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg
from the repository.
For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.
Try this:
subset(studentdata, Drink=='water')
that should do it.
Roughly you can do it like that :
try
{
//do something
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
if (!Page.IsStartupScriptRegistered("myErrorScript"))
{
Page.ClientScript.RegisterStartupScript("myErrorScript", script);
}
}
But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.
On Windows and Linux, it's AltShiftA, as RichieHindle pointed out. On OSX it's OptionCommandA (??A). It's also worth noting that the two modes can have different font preferences, so if you've changed the default text font, it can be jarring to toggle block selection modes and see the font change.
Finally, the "search commands" (Ctrl3 or Command3) pop-up will find it for you if you type block. This is useful if you use the feature just frequently enough to forget the hotkey.
I know this is a late response but I was facing a similar issue and I managed to solve it by using notifyDataSetChanged()
in the right place.
So my situation was as follows.
I had to update a listview in an action bar tab (fragment) with contents returned from a completely different activity. Initially however, the listview would not reflect any changes. However, when I clicked another tab and then returned to the desired tab,the listview would be updated with the correct content from the other activity. So to solve this I used notifyDataSetChanged()
of the action bar adapter in the code of the activity which had to return the data.
This is the code snippet which I used in the activity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.action_new_forward:
FragmentTab2.mListAdapter.notifyDataSetChanged();//this updates the adapter in my action bar tab
Intent ina = new Intent(getApplicationContext(), MainActivity.class);
ina.putExtra("stra", values1);
startActivity(ina);// This is the code to start the parent activity of my action bar tab(fragment).
}
}
This activity would return some data to FragmentTab2
and it would directly update my listview in FragmentTab2
.
Hope someone finds this useful!
This is the most popular (9500 stars) and light weight (20KB minify, 7.5KB minify+gzip) popup gallery I think: Magnific-Popup
The problem is with your notificationId
. Think it as an array index. Each time you update your notification, the notificationId
is the place it takes to store value. As you are not incrementing your int value (in this case, your notificationId
), this always replaces the previous one. The best solution I guess is to increment it just after you update a notification. And if you want to keep it persistent, then you can store the value of your notificationId
in sharedPreferences
. Whenever you come back, you can just grab the last integer value (notificationId
stored in sharedPreferences
) and use it.
For Mac
Open KeyChain Access and find your pssword account on password category ( you can search it on top right keychain access page)
when you find it , delete all keys related to your git source control. and try it again
private void HighLightGridRows()
{
Debugger.Launch();
for (int i = 0; i < dtgvAppSettings.Rows.Count; i++)
{
String key = dtgvAppSettings.Rows[i].Cells["Key"].Value.ToString();
if (key.ToLower().Contains("applicationpath") == true)
{
dtgvAppSettings.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
}
}
}
I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.
It works (refreshes the graphs) if I put
plt.clf()
plt.cla()
plt.close()
after every plt.show()
Proper Swift 3.0 for iOS 10+ solution: Using ImageRenderer
and closure syntax:
func imageWith(newSize: CGSize) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: newSize)
let image = renderer.image { _ in
self.draw(in: CGRect.init(origin: CGPoint.zero, size: newSize))
}
return image.withRenderingMode(self.renderingMode)
}
And here's the Objective-C version:
@implementation UIImage (ResizeCategory)
- (UIImage *)imageWithSize:(CGSize)newSize
{
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:newSize];
UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext*_Nonnull myContext) {
[self drawInRect:(CGRect) {.origin = CGPointZero, .size = newSize}];
}];
return [image imageWithRenderingMode:self.renderingMode];
}
@end
SQL Server 2000 Programs | MS SQL Server | Client Network Utility | Select TCP_IP then Properties
SQL Server 2005 Programs | SQL Server | SQL Server Configuration Manager | Select Protocols for MSSQLSERVER or select Client Protocols and right click on TCP/IP
For me only way to delete project was switch language to English (UK) - from Polish and then button "DELETE" worked. If anyone have problem with not working or missing options in Google Cloud Platform I suggest switching to english after that everything works like charm...
I run this
var data = '{"rut" : "' + $('#cb_rut').val() + '" , "email" : "' + $('#email').val() + '" }';
var data = JSON.parse(data);
$.ajax({
type: 'GET',
url: 'linkserverApi',
success: function(success) {
console.log('Success!');
console.log(success);
},
error: function() {
console.log('Uh Oh!');
},
jsonp: 'jsonp'
});
And edit header in the response
'Access-Control-Allow-Methods' , 'GET, POST, PUT, DELETE'
'Access-Control-Max-Age' , '3628800'
'Access-Control-Allow-Origin', 'websiteresponseUrl'
'Content-Type', 'text/javascript; charset=utf8'
Like the others said:
inputString.split('\n') # --> ['Line 1', 'Line 2', 'Line 3']
This is identical to the above, but the string module's functions are deprecated and should be avoided:
import string
string.split(inputString, '\n') # --> ['Line 1', 'Line 2', 'Line 3']
Alternatively, if you want each line to include the break sequence (CR,LF,CRLF), use the splitlines
method with a True
argument:
inputString.splitlines(True) # --> ['Line 1\n', 'Line 2\n', 'Line 3']
The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldName
from outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)
class Foo:
def __init__(self):
self.__privateField = 4;
print self.__privateField # yields 4 no problem
foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'
It will be accessible through _Foo__privateField
instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.
What fixed it for me was
A recursive algorithm that parses through an XmlDocument
Here is an example - Recursively reading an xml document and using regex to get contents
Here is another recursive example - http://www.java2s.com/Tutorial/CSharp/0540__XML/LoopThroughXmlDocumentRecursively.html
When I worked on Mac OS X in the lab I was able to get the terminal colors from using Terminal (rather than X11) and then editing the profile (from the Mac menu bar). The interface is a bit odd on the colors, but you have to set the modified theme as default.
Further settings worked by editing .bashrc
.
I'm sorry, but upgrading development station to SSD and tons of ram has probably a bigger influence than points below combined.
Increasing build performance has major priority for the development teams, so make sure you are using latest Gradle and Android Gradle Plugin.
Create a file named gradle.properties
in whatever directory applies:
/home/<username>/.gradle/
(Linux)/Users/<username>/.gradle/
(Mac)C:\Users\<username>\.gradle
(Windows)Append:
# IDE (e.g. Android Studio) users:
# Settings specified in this file will override any Gradle settings
# configured through the IDE.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# The Gradle daemon aims to improve the startup and execution time of Gradle.
# When set to true the Gradle daemon is to run the build.
# TODO: disable daemon on CI, since builds should be clean and reliable on servers
org.gradle.daemon=true
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# https://medium.com/google-developers/faster-android-studio-builds-with-dex-in-process-5988ed8aa37e#.krd1mm27v
org.gradle.jvmargs=-Xmx5120m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
org.gradle.parallel=true
# Enables new incubating mode that makes Gradle selective when configuring projects.
# Only relevant projects are configured which results in faster builds for large multi-projects.
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:configuration_on_demand
org.gradle.configureondemand=true
# Set to true or false to enable or disable the build cache.
# If this parameter is not set, the build cache is disabled by default.
# http://tools.android.com/tech-docs/build-cache
android.enableBuildCache=true
Gradle properties works local if you place them at projectRoot\gradle.properties
and globally if you place them at user_home\.gradle\gradle.properties
. Properties applied if you run gradle tasks from console or directly from idea:
It is possible to tweak Gradle-IntelliJ integration from the IDE settings GUI. Enabling "offline work" (check answer from yava below) will disable real network requests on every "sync gradle file".
One of the slowest steps of the apk build is converting java bytecode into single dex file. Enabling native multidex (minSdk 21 for debug builds only) will help the tooling to reduce an amount of work (check answer from Aksel Willgert below).
Prefer @aar
dependencies over library sub-projects.
Search aar package on mavenCentral, jCenter or use jitpack.io to build any library from github. If you are not editing sources of the dependency library you should not build it every time with your project sources.
Consider to exclude project and cache files from antivirus scanning. This is obviously a trade off with security (don't try this at home!). But if you switch between branches a lot, then antivirus will rescan files before allowing gradle process to use it, which slows build time (in particular AndroidStudio sync project with gradle files and indexing tasks). Measure build time and process CPU with and without antivirus enabled to see if it is related.
Gradle has built-in support for profiling projects. Different projects are using a different combination of plugins and custom scripts. Using --profile
will help to find bottlenecks.
The solution you are looking for is in Angular's official tutorial. In this tutorial Phones are loaded from a JSON file using Angulars $http service . In the code below we use $http.get to load a phones.json file saved in the phones directory:
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
});
We then iterate over the phones:
<table>
<tbody ng-repeat="i in phones">
<tr><td>{{i.name}}</td><td>{{$index}}</td></tr>
<tr ng-repeat="e in i.details">
<td>{{$index}}</td>
<td>{{e.foo}}</td>
<td>{{e.bar}}</td></tr>
</tbody>
</table>
java.util.Date class has before and after method to compare dates.
Date date1 = new Date();
Date date2 = new Date();
if(date1.before(date2)){
//Do Something
}
if(date1.after(date2)){
//Do Something else
}
You can use os.scandir()
. New function in stdlib starts from Python 3.5.
import os
for entry in os.scandir('.'):
if entry.is_file():
print(entry.name)
Faster than os.listdir()
. os.walk()
implements os.scandir()
.
Notice: Trying to get property of non-object in C:\wamp\www\phone\pages\init.php on line 22
@22 is
<?php echo $sidemenu->mname."<br />";?>
$sidemenu
is not an object, and you are trying to access one of its properties.
That is the reason for your error.
var EmployeeController = ["$scope", "EmployeeService",
function ($scope, EmployeeService) {
$scope.Employee = {};
$scope.Save = function (Employee) {
if ($scope.EmployeeForm.$valid) {
EmployeeService
.Save(Employee)
.then(function (response) {
if (response.HasError) {
$scope.HasError = response.HasError;
$scope.ErrorMessage = response.ResponseMessage;
} else {
}
})
.catch(function (response) {
});
}
}
}]
var EmployeeService = ["$http", "$q",
function ($http, $q) {
var self = this;
self.Save = function (employee) {
var deferred = $q.defer();
$http
.post("/api/EmployeeApi/Create", angular.toJson(employee))
.success(function (response, status, headers, config) {
deferred.resolve(response, status, headers, config);
})
.error(function (response, status, headers, config) {
deferred.reject(response, status, headers, config);
});
return deferred.promise;
};
I think it would be a lot more productive to use a TextWriter
, in this case a StreamWriter to write to the MemoryStream. After that, as other have said, you need to "rewind" the MemoryStream using something like stringAsStream.Position = 0L;
.
stringAsStream = new MemoryStream();
// create stream writer with UTF-16 (Unicode) encoding to write to the memory stream
using(StreamWriter sWriter = new StreamWriter(stringAsStream, UnicodeEncoding.Unicode))
{
sWriter.Write("Lorem ipsum.");
}
stringAsStream.Position = 0L; // rewind
Note that:
StreamWriter defaults to using an instance of UTF8Encoding unless specified otherwise. This instance of UTF8Encoding is constructed without a byte order mark (BOM)
Also, you don't have to create a new UnicodeEncoding()
usually, since there's already one as a static member of the class for you to use in convenient utf-8, utf-16, and utf-32 flavors.
And then, finally (as others have said) you're trying to convert the byte
s directly to char
s, which they are not. If I had a memory stream and knew it was a string, I'd use a TextReader
to get the string back from the bytes. It seems "dangerous" to me to mess around with the raw bytes.
This is how you can set the timeout after you click.
$(".selectorOnWhichEventCapture").on('click', function() {
setTimeout(function(){
$(".selector").doWhateverYouWantToDo();
}, 5000);
});
//5000 = 5sec = 5000 milisec
It also posible string replacement with stringByReplacingCharactersInRange:withString:
for (int i = 0; i < card.length - 4; i++) {
if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) {
NSRange range = NSMakeRange(i, 1);
card = [card stringByReplacingCharactersInRange:range withString:@"*"];
}
} //out: **** **** **** 1234
@ECHO OFF
:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/
:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"
:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m
:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m
PAUSE
You need to go to the /.idea/compiler.xml
and change target
to required jdk
level.
I would like to re-emphasize the following:
Took me ages to realise, somehow even after reading the answers here it didn't click.
Non-Americans take note! If you use Excel with "." as 1000 separator, you need to replace the "," with a "." in the formula, such as:
[>=1000]€ #.##0." K";[<=-1000]-€ #.##0." K";0
The code above will display € 62.123 as "€ 62 K".
you have to set cellpadding and cellspacing that's it.
<table cellpadding="5" cellspacing="5">
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
</tr>
</table>
Go to Setting>Debug>Un-check close on end.
As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.
It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.
Another option with yapf
:
from pprint import pformat
from yapf.yapflib.yapf_api import FormatCode
dict_example = {'1': '1', '2': '2', '3': [1, 2, 3, 4, 5], '4': {'1': '1', '2': '2', '3': [1, 2, 3, 4, 5]}}
dict_string = pformat(dict_example)
formatted_code, _ = FormatCode(dict_string)
print(formatted_code)
Output:
{
'1': '1',
'2': '2',
'3': [1, 2, 3, 4, 5],
'4': {
'1': '1',
'2': '2',
'3': [1, 2, 3, 4, 5]
}
}
If you want to map an object you can use Lodash. Just make sure it's installed via NPM or Yarn and import it.
With Lodash:
Lodash provides a function _.mapValues
to map the values and preserve the keys.
_.mapValues({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });
// => { one: 3, two: 6, three: 9 }
Here is my proposition based on json_encode() solution with :
If word not found, it still returns 0 equal to false.
function in_array_count($needle, $haystack, $caseSensitive = true) {
if(!$caseSensitive) {
return substr_count(strtoupper(json_encode($haystack)), strtoupper($needle));
}
return substr_count(json_encode($haystack), $needle);
}
Hope it helps.
Use C++ streams and restore state afterwards
This is a variation of How do I print bytes as hexadecimal? but:
main.cpp
#include <iomanip>
#include <iostream>
int main() {
int array[] = {0, 0x8, 0x10, 0x18};
constexpr size_t size = sizeof(array) / sizeof(array[0]);
// Sanity check decimal print.
for (size_t i = 0; i < size; ++i)
std::cout << array[i] << " ";
std::cout << std::endl;
// Hex print and restore default afterwards.
std::ios cout_state(nullptr);
cout_state.copyfmt(std::cout);
std::cout << std::hex << std::setfill('0') << std::setw(2);
for (size_t i = 0; i < size; ++i)
std::cout << array[i] << " ";
std::cout << std::endl;
std::cout.copyfmt(cout_state);
// Check that cout state was restored.
for (size_t i = 0; i < size; ++i)
std::cout << array[i] << " ";
std::cout << std::endl;
}
Compile and run:
g++ -o main.out -std=c++11 main.cpp
./main.out
Output:
0 8 16 24
00 8 10 18
0 8 16 24
Tested on Ubuntu 16.04, GCC 6.4.0.
you should add all the entity files in the .addAnnotatedClass(Class) method, if the class needs to be auto discovered.
use this link, it might help..
http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/cfg/AnnotationConfiguration.html
I received this error in my code because I'd not run JSON.parse(result).
So my result was a string instead of an array of objects.
i.e. I got:
"[{},{}]"
instead of:
[{},{}]
import { Storage } from '@ionic/storage';
...
private static readonly SERVER = 'server';
...
getStorage(): Promise {
return this.storage.get(LoginService.SERVER);
}
...
this.getStorage()
.then((value) => {
let servers: Server[] = JSON.parse(value) as Server[];
}
);
How to search all columns of all tables in a database for a keyword?
http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm
EDIT: Here's the actual T-SQL, in case of link rot:
CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
END
I came across HikariCP
and I was amazed by the benchmarks and I wanted to try it instead of my default choice C3P0
and to my surprise I struggled to get the configurations
right probably because the configurations differ based on what combination of tech stack you are using.
I have setup Spring Boot
project with JPA, Web, Security
starters (Using Spring Initializer) to use PostgreSQL
as a database with HikariCP
as connection pooling.
I have used Gradle
as build tool and I would like to share what worked for me for the following assumptions:
You need the following build.gradle
if you are using Gradle
or equivalent pom.xml
if you are using maven
buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
group = 'com'
version = '1.0'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-aop')
// Exclude the tomcat-jdbc since it's used as default for connection pooling
// This can also be achieved by setting the spring.datasource.type to HikariCP
// datasource see application.properties below
compile('org.springframework.boot:spring-boot-starter-data-jpa') {
exclude group: 'org.apache.tomcat', module: 'tomcat-jdbc'
}
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-web')
runtime('org.postgresql:postgresql')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('org.springframework.security:spring-security-test')
// Download HikariCP but, exclude hibernate-core to avoid version conflicts
compile('com.zaxxer:HikariCP:2.5.1') {
exclude group: 'org.hibernate', module: 'hibernate-core'
}
// Need this in order to get the HikariCPConnectionProvider
compile('org.hibernate:hibernate-hikaricp:5.2.11.Final') {
exclude group: 'com.zaxxer', module: 'HikariCP'
exclude group: 'org.hibernate', module: 'hibernate-core'
}
}
There are a bunch of excludes in the above build.gradle
and that's because
jdbc-tomcat
connection pool when downloading the spring-boot-starter-data-jpa
dependencies. This can be achieved by setting up the spring.datasource.type=com.zaxxer.hikari.HikariDataSource
also but, I don't want an extra dependency if I don't need it hibernate-core
when downloading com.zaxxer
dependency and that's because hibernate-core
is already downloaded by Spring Boot
and we don't want to end up with different versions. hibernate-core
when downloading hibernate-hikaricp
module which is needed in order to make HikariCP use org.hibernate.hikaricp.internal.HikariCPConnectionProvider
as connection provider instead of deprecated com.zaxxer.hikari.hibernate.HikariConnectionProvider
Once I figured out the build.gradle
and what to keep and what to not, I was ready to copy/paste a datasource
configuration into my application.properties
and expected everything to work with flying colors but, not really and I stumbled upon the following issues
com.zaxxer.hikari.hibernate.HikariConnectionProvider
key/value
in the application.properties
and was complaining about dataSource, dataSourceClassName, jdbcUrl
. I had to debug into HikariConfig, HikariConfigurationUtil, HikariCPConnectionProvider
and found out that HikariCP
could not find the properties from application.properties
because it was named differently. Anyway, this is where I had to rely on trial and error and make sure that HikariCP
is able to pick the properties (i.e. data source that's db details, as well as pooling properties) as well as Sping Boot behave as expected and I ended up with the following application.properties
file.
server.contextPath=/
debug=true
# Spring data source needed for Spring boot to behave
# Pre Spring Boot v2.0.0.M6 without below Spring Boot defaults to tomcat-jdbc connection pool included
# in spring-boot-starter-jdbc and as compiled dependency under spring-boot-starter-data-jpa
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:postgresql://localhost:5432/somedb
spring.datasource.username=dbuser
spring.datasource.password=dbpassword
# Hikari will use the above plus the following to setup connection pooling
spring.datasource.hikari.minimumIdle=5
spring.datasource.hikari.maximumPoolSize=20
spring.datasource.hikari.idleTimeout=30000
spring.datasource.hikari.poolName=SpringBootJPAHikariCP
spring.datasource.hikari.maxLifetime=2000000
spring.datasource.hikari.connectionTimeout=30000
# Without below HikariCP uses deprecated com.zaxxer.hikari.hibernate.HikariConnectionProvider
# Surprisingly enough below ConnectionProvider is in hibernate-hikaricp dependency and not hibernate-core
# So you need to pull that dependency but, make sure to exclude it's transitive dependencies or you will end up
# with different versions of hibernate-core
spring.jpa.hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider
# JPA specific configs
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.use_sql=true
spring.jpa.properties.hibernate.id.new_generator_mappings=false
spring.jpa.properties.hibernate.default_schema=dbschema
spring.jpa.properties.hibernate.search.autoregister_listeners=false
spring.jpa.properties.hibernate.bytecode.use_reflection_optimizer=false
# Enable logging to verify that HikariCP is used, the second entry is specific to HikariCP
logging.level.org.hibernate.SQL=DEBUG
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
As shown above the configurations are divided into categories based on following naming patterns
It's hard to come across a tutorial or post or some resource that shows how the above properties file is used and how the properties should be named. Well, there you have it.
Throwing the above application.properties
with build.gradle
(or at least similar) into a Spring Boot JPA project version (1.5.8) should work like a charm and connect to your pre-configured database (i.e. in my case it's PostgreSQL that both HikariCP & Spring
figure out from the spring.datasource.url
on which database driver to use).
I did not see the need to create a DataSource
bean and that's because Spring Boot is capable of doing everything for me just by looking into application.properties
and that's neat.
The article in HikariCP's github wiki shows how to setup Spring Boot with JPA but, lacks explanation and details.
The above two file is also availble as a public gist https://gist.github.com/rhamedy/b3cb936061cc03acdfe21358b86a5bc6
I am not quite sure what you need, but I would use something like this:
#!/usr/bin/env ruby
until ARGV.empty? do
puts "From arguments: #{ARGV.shift}"
end
while a = gets
puts "From stdin: #{a}"
end
Note that because ARGV array is empty before first gets
, Ruby won't try to interpret argument as text file from which to read (behaviour inherited from Perl).
If stdin is empty or there is no arguments, nothing is printed.
Few test cases:
$ cat input.txt | ./myprog.rb
From stdin: line 1
From stdin: line 2
$ ./myprog.rb arg1 arg2 arg3
From arguments: arg1
From arguments: arg2
From arguments: arg3
hi!
From stdin: hi!
The problem with the script is that the environment used for the script is not the same as the one used for your tests, so setting the environment variables there does nothing for your tests.
To properly set the variable you need to set it in Jenkins. Go to Manage Jenkins>Manage Nodes>Master>Configure. Check the Environment variables check box, then enter DISPLAY in the name box, and set the value to :1.0.
Additionally you'll need to set permissions, try disabling your xhost access controls using xhost +
in the terminal.
null is unknown in sql so we cant expect two unknowns to be same.
However you can get that behavior by setting ANSI_NULLS to Off(its On by Default) You will be able to use = operator for nulls
SET ANSI_NULLS off
if null=null
print 1
else
print 2
set ansi_nulls on
if null=null
print 1
else
print 2
The browser is still submitting the form after your code runs.
Add return false;
to the handler to prevent that.
Request.QueryString["pID"];
Here Request is a object that retrieves the values that the client browser passed to the server during an HTTP request and QueryString is a collection is used to retrieve the variable values in the HTTP query string.
READ MORE@ http://msdn.microsoft.com/en-us/library/ms524784(v=vs.90).aspx
You can't. That member is private, it's not visible outside the class. That's the whole point of the public/protected/private modifiers.
(You could probably use dirty pointer tricks though, but my guess is that you'd enter undefined behavior territory pretty fast.)
Just to be clear, all the answers so far are correct, but the reasoning behind them is not explained very well.
The sumall
variable is not yet a string. Parentheticals will not convert to a string (e.g. summ = (int(birthday[0])+int(birthday[1]))
still returns an integer. It looks like you most likely intended to type str((int(sumall[0])+int(sumall[1])))
, but forgot to. The reason the str()
function fixes everything is because it converts anything in it compatible to a string.
/*$mpdf = new mPDF('', // mode - default ''
'', // format - A4, for example, default ''
0, // font size - default 0
'', // default font family
15, // margin_left
15, // margin right
16, // margin top
16, // margin bottom
9, // margin header
9, // margin footer
'L'); // L - landscape, P - portrait*/
kw=(EditText)findViewById(R.id.kw);
btn=(Button)findViewById(R.id.btn);
cost=(TextView )findViewById(R.id.cost);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { cst = Double.valueOf(kw.getText().toString());
cst = cst*0.551;
cost.setText(cst.toString());
}
});
Or even just:
<div id="full-size">
Your contents go here
</div>
html,body{ margin:0; padding:0; height:100%; width:100%; }
#full-size{
height:100%;
width:100%;
overflow:hidden; /* or overflow:auto; if you want scrollbars */
}
(html, body can be set to like.. 95%-99% or some such to account for slight inconsistencies in margins, etc.)
volatile:
volatile
is a keyword. volatile
forces all threads to get latest value of the variable from main memory instead of cache. No locking is required to access volatile variables. All threads can access volatile variable value at same time.
Using volatile
variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.
This means that changes to a volatile
variable are always visible to other threads. What's more, it also means that when a thread reads a volatile
variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.
When to use: One thread modifies the data and other threads have to read latest value of data. Other threads will take some action but they won't update data.
AtomicXXX:
AtomicXXX
classes support lock-free thread-safe programming on single variables. These AtomicXXX
classes (like AtomicInteger
) resolves memory inconsistency errors / side effects of modification of volatile variables, which have been accessed in multiple threads.
When to use: Multiple threads can read and modify data.
synchronized:
synchronized
is keyword used to guard a method or code block. By making method as synchronized has two effects:
First, it is not possible for two invocations of synchronized
methods on the same object to interleave. When one thread is executing a synchronized
method for an object, all other threads that invoke synchronized
methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized
method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized
method for the same object. This guarantees that changes to the state of the object are visible to all threads.
When to use: Multiple threads can read and modify data. Your business logic not only update the data but also executes atomic operations
AtomicXXX
is equivalent of volatile + synchronized
even though the implementation is different. AmtomicXXX
extends volatile
variables + compareAndSet
methods but does not use synchronization.
Related SE questions:
Difference between volatile and synchronized in Java
Volatile boolean vs AtomicBoolean
Good articles to read: ( Above content is taken from these documentation pages)
https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html
If your skype is open, Quit skype and try,
or
Go to your xampp/wamp installed, search for httpd.conf. Open that file using textpad/notepad, search for Listen or 80 , update listen port to 8081 and save the file. Restart xampp/wamp, start the servers.
or
follow below steps in skype
Just for the sake of completion: when parsing a date using strptime()
and the date contains the name of a day, month, etc, be aware that you have to account for the locale.
It's mentioned as a footnote in the docs as well.
As an example:
import locale
print(locale.getlocale())
>> ('nl_BE', 'ISO8859-1')
from datetime import datetime
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')
>> ValueError: time data '6-Mar-2016' does not match format '%d-%b-%Y'
locale.setlocale(locale.LC_ALL, 'en_US')
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')
>> '2016-03-06'
As Kristian has pointed out, good control over z-values will often solve your problems.
If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.
I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:
box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;
This will give you some control over the "amount" of shadow in each direction.
Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.
Hope this was what you were looking for!
As of ES6 (and so versions of Node greater than v4), a new "template literal" intrinsic type was added to Javascript (denoted by back-ticks "`") which can also be used to construct multi-line strings, as in:
`this is a
single string`
which evaluates to: 'this is a\nsingle string'
.
Note that the newline at the end of the first line is included in the resulting string.
Template literals were added to allow programmers to construct strings where values or code could be directly injected into a string literal without having to use util.format
or other templaters, as in:
let num=10;
console.log(`the result of ${num} plus ${num} is ${num + num}.`);
which will print "the result of 10 plus 10 is 20." to the console.
Older version of node can use a "line continuation" character allowing you to write multi-line strings such as:
'this is a \
single string'
which evaluates to: 'this is a single string'
.
Note that the newline at the end of the first line is not included in the resulting string.
I do it like this:
(Shortened the code a bit)
public struct Age
{
public readonly int Years;
public readonly int Months;
public readonly int Days;
}
public Age( int y, int m, int d ) : this()
{
Years = y;
Months = m;
Days = d;
}
public static Age CalculateAge ( DateTime birthDate, DateTime anotherDate )
{
if( startDate.Date > endDate.Date )
{
throw new ArgumentException ("startDate cannot be higher then endDate", "startDate");
}
int years = endDate.Year - startDate.Year;
int months = 0;
int days = 0;
// Check if the last year, was a full year.
if( endDate < startDate.AddYears (years) && years != 0 )
{
years--;
}
// Calculate the number of months.
startDate = startDate.AddYears (years);
if( startDate.Year == endDate.Year )
{
months = endDate.Month - startDate.Month;
}
else
{
months = ( 12 - startDate.Month ) + endDate.Month;
}
// Check if last month was a complete month.
if( endDate < startDate.AddMonths (months) && months != 0 )
{
months--;
}
// Calculate the number of days.
startDate = startDate.AddMonths (months);
days = ( endDate - startDate ).Days;
return new Age (years, months, days);
}
// Implement Equals, GetHashCode, etc... as well
// Overload equality and other operators, etc...
}
I found the answer, thanks to your information Michelle.
You can indeed get the right view using View#getChildAt(int index)
. The catch is that it starts counting from the first visible item. In fact, you can only get the visible items. You solve this with ListView#getFirstVisiblePosition()
.
Example:
private void updateView(int index){
View v = yourListView.getChildAt(index -
yourListView.getFirstVisiblePosition());
if(v == null)
return;
TextView someText = (TextView) v.findViewById(R.id.sometextview);
someText.setText("Hi! I updated you manually!");
}
You could use is()
instead of hasClass()
:
if ($('html').is('.m320, .m768')) { ... }
What does it mean for the ranges to overlap? It means there exists some number C which is in both ranges, i.e.
x1 <= C <= x2
and
y1 <= C <= y2
Now, if we are allowed to assume that the ranges are well-formed (so that x1 <= x2 and y1 <= y2) then it is sufficient to test
x1 <= y2 && y1 <= x2
Either attribute can be applied to View's (visual control) horizontal or vertical size. It's used to set a View or Layouts size based on either it's contents or the size of it's parent layout rather than explicitly specifying a dimension.
fill_parent
(deprecated and renamed MATCH_PARENT
in API Level 8 and higher)
Setting the layout of a widget to fill_parent will force it to expand to take up as much space as is available within the layout element it's been placed in. It's roughly equivalent of setting the dockstyle of a Windows Form Control to Fill
.
Setting a top level layout or control to fill_parent will force it to take up the whole screen.
wrap_content
Setting a View's size to wrap_content will force it to expand only far enough to contain the values (or child controls) it contains. For controls -- like text boxes (TextView) or images (ImageView) -- this will wrap the text or image being shown. For layout elements it will resize the layout to fit the controls / layouts added as its children.
It's roughly the equivalent of setting a Windows Form Control's Autosize
property to True.
Online Documentation
There's some details in the Android code documentation here.
Is the size of C “int” 2 bytes or 4 bytes?
Does an Integer variable in C occupy 2 bytes or 4 bytes?
C allows "bytes" to be something other than 8 bits per "byte".
CHAR_BIT
number of bits for smallest object that is not a bit-field (byte) C11dr §5.2.4.2.1 1
A value of something than 8 is increasingly uncommon. For maximum portability, use CHAR_BIT
rather than 8. The size of an int
in bits in C is sizeof(int) * CHAR_BIT
.
#include <limits.h>
printf("(int) Bit size %zu\n", sizeof(int) * CHAR_BIT);
What are the factors that it depends on?
The int
bit size is commonly 32 or 16 bits. C specified minimum ranges:
minimum value for an object of type
int
INT_MIN
-32767
maximum value for an object of typeint
INT_MAX
+32767
C11dr §5.2.4.2.1 1
The minimum range for int
forces the bit size to be at least 16 - even if the processor was "8-bit". A size like 64 bits is seen in specialized processors. Other values like 18, 24, 36, etc. have occurred on historic platforms or are at least theoretically possible. Modern coding rarely worries about non-power-of-2 int
bit sizes.
The computer's processor and architecture drive the int
bit size selection.
Yet even with 64-bit processors, the compiler's int
size may be 32-bit for compatibility reasons as large code bases depend on int
being 32-bit (or 32/16).
Edit: see the end examples for ES6 updated examples.
This answer simply handle the case of direct parent-child relationship. When parent and child have potentially a lot of intermediaries, check this answer.
While they still work fine, other answers are missing something very important.
Is there not a simple way to pass a child's props to its parent using events, in React.js?
The parent already has that child prop!: if the child has a prop, then it is because its parent provided that prop to the child! Why do you want the child to pass back the prop to the parent, while the parent obviously already has that prop?
Child: it really does not have to be more complicated than that.
var Child = React.createClass({
render: function () {
return <button onClick={this.props.onClick}>{this.props.text}</button>;
},
});
Parent with single child: using the value it passes to the child
var Parent = React.createClass({
getInitialState: function() {
return {childText: "Click me! (parent prop)"};
},
render: function () {
return (
<Child onClick={this.handleChildClick} text={this.state.childText}/>
);
},
handleChildClick: function(event) {
// You can access the prop you pass to the children
// because you already have it!
// Here you have it in state but it could also be
// in props, coming from another parent.
alert("The Child button text is: " + this.state.childText);
// You can also access the target of the click here
// if you want to do some magic stuff
alert("The Child HTML is: " + event.target.outerHTML);
}
});
Parent with list of children: you still have everything you need on the parent and don't need to make the child more complicated.
var Parent = React.createClass({
getInitialState: function() {
return {childrenData: [
{childText: "Click me 1!", childNumber: 1},
{childText: "Click me 2!", childNumber: 2}
]};
},
render: function () {
var children = this.state.childrenData.map(function(childData,childIndex) {
return <Child onClick={this.handleChildClick.bind(null,childData)} text={childData.childText}/>;
}.bind(this));
return <div>{children}</div>;
},
handleChildClick: function(childData,event) {
alert("The Child button data is: " + childData.childText + " - " + childData.childNumber);
alert("The Child HTML is: " + event.target.outerHTML);
}
});
It is also possible to use this.handleChildClick.bind(null,childIndex)
and then use this.state.childrenData[childIndex]
Note we are binding with a null
context because otherwise React issues a warning related to its autobinding system. Using null means you don't want to change the function context. See also.
This is for me a bad idea in term of coupling and encapsulation:
var Parent = React.createClass({
handleClick: function(childComponent) {
// using childComponent.props
// using childComponent.refs.button
// or anything else using childComponent
},
render: function() {
<Child onClick={this.handleClick} />
}
});
Using props: As I explained above, you already have the props in the parent so it's useless to pass the whole child component to access props.
Using refs: You already have the click target in the event, and in most case this is enough. Additionnally, you could have used a ref directly on the child:
<Child ref="theChild" .../>
And access the DOM node in the parent with
React.findDOMNode(this.refs.theChild)
For more advanced cases where you want to access multiple refs of the child in the parent, the child could pass all the dom nodes directly in the callback.
The component has an interface (props) and the parent should not assume anything about the inner working of the child, including its inner DOM structure or which DOM nodes it declares refs for. A parent using a ref of a child means that you tightly couple the 2 components.
To illustrate the issue, I'll take this quote about the Shadow DOM, that is used inside browsers to render things like sliders, scrollbars, video players...:
They created a boundary between what you, the Web developer can reach and what’s considered implementation details, thus inaccessible to you. The browser however, can traipse across this boundary at will. With this boundary in place, they were able to build all HTML elements using the same good-old Web technologies, out of the divs and spans just like you would.
The problem is that if you let the child implementation details leak into the parent, you make it very hard to refactor the child without affecting the parent. This means as a library author (or as a browser editor with Shadow DOM) this is very dangerous because you let the client access too much, making it very hard to upgrade code without breaking retrocompatibility.
If Chrome had implemented its scrollbar letting the client access the inner dom nodes of that scrollbar, this means that the client may have the possibility to simply break that scrollbar, and that apps would break more easily when Chrome perform its auto-update after refactoring the scrollbar... Instead, they only give access to some safe things like customizing some parts of the scrollbar with CSS.
About using anything else
Passing the whole component in the callback is dangerous and may lead novice developers to do very weird things like calling childComponent.setState(...)
or childComponent.forceUpdate()
, or assigning it new variables, inside the parent, making the whole app much harder to reason about.
Edit: ES6 examples
As many people now use ES6, here are the same examples for ES6 syntax
The child can be very simple:
const Child = ({
onClick,
text
}) => (
<button onClick={onClick}>
{text}
</button>
)
The parent can be either a class (and it can eventually manage the state itself, but I'm passing it as props here:
class Parent1 extends React.Component {
handleChildClick(childData,event) {
alert("The Child button data is: " + childData.childText + " - " + childData.childNumber);
alert("The Child HTML is: " + event.target.outerHTML);
}
render() {
return (
<div>
{this.props.childrenData.map(child => (
<Child
key={child.childNumber}
text={child.childText}
onClick={e => this.handleChildClick(child,e)}
/>
))}
</div>
);
}
}
But it can also be simplified if it does not need to manage state:
const Parent2 = ({childrenData}) => (
<div>
{childrenData.map(child => (
<Child
key={child.childNumber}
text={child.childText}
onClick={e => {
alert("The Child button data is: " + child.childText + " - " + child.childNumber);
alert("The Child HTML is: " + e.target.outerHTML);
}}
/>
))}
</div>
)
PERF WARNING (apply to ES5/ES6): if you are using PureComponent
or shouldComponentUpdate
, the above implementations will not be optimized by default because using onClick={e => doSomething()}
, or binding directly during the render phase, because it will create a new function everytime the parent renders. If this is a perf bottleneck in your app, you can pass the data to the children, and reinject it inside "stable" callback (set on the parent class, and binded to this
in class constructor) so that PureComponent
optimization can kick in, or you can implement your own shouldComponentUpdate
and ignore the callback in the props comparison check.
You can also use Recompose library, which provide higher order components to achieve fine-tuned optimisations:
// A component that is expensive to render
const ExpensiveComponent = ({ propA, propB }) => {...}
// Optimized version of same component, using shallow comparison of props
// Same effect as React's PureRenderMixin
const OptimizedComponent = pure(ExpensiveComponent)
// Even more optimized: only updates if specific prop keys have changed
const HyperOptimizedComponent = onlyUpdateForKeys(['propA', 'propB'])(ExpensiveComponent)
In this case you could optimize the Child component by using:
const OptimizedChild = onlyUpdateForKeys(['text'])(Child)
For the nodejs
Selenium library, I used the following snippet. In my case, I was looking for two objects that are added to the window, which in this example are <SOME PROPERTY>
, 10000
is the timeout milliseconds, <NEXT STEP HERE>
is what happens after the properties are found on the window.
driver.wait( driver => {
return driver.executeScript( 'if(window.hasOwnProperty(<SOME PROPERTY>) && window.hasOwnProperty(<SOME PROPERTY>)) return true;' ); }, 10000).then( ()=>{
<NEXT STEP HERE>
}).catch(err => {
console.log("looking for window properties", err);
});
Maybe you could use String#split
To answer your comment:
I'm not sure if there can be more than one . in a filename, but whatever, even if there are more dots you can use the split. Consider e.g. that:
String input = "boo.and.foo";
String[] result = input.split(".");
This will return an array containing:
{ "boo", "and", "foo" }
So you will know that the last index in the array is the extension and all others are the base.
Did you check the string concatenation function? Something like:
update table_c set column_a = column_b || column_c
should work. More here
You can do same thing using single query
SELECT sum(if(DATE(dDate)=DATE(CURRENT_TIMESTAMP),earning,null)) astodays,
sum(if(YEARWEEK(dDate)=YEARWEEK(CURRENT_DATE),earning,null)) as weeks,
IF((MONTH(dDate) = MONTH(CURRENT_TIMESTAMP()) AND YEAR(dDate) = YEAR(CURRENT_TIMESTAMP())),sum(earning),0) AS months,
IF(YEAR(dDate) = YEAR(CURRENT_TIMESTAMP()),sum(earning),0) AS years,
sum(fAdminFinalEarning) as total_earning FROM `earning`
Hope this works.
getElementById
Return Value: An Element Object, representing an element with the specified ID. Returns null if no elements with the specified ID exists see: https://www.w3schools.com/jsref/met_document_getelementbyid.asp
Truthy vs Falsy
In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN). see: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
When the dom element is not found in the document
it will return null
. null is a Falsy and can be used as boolean expression
in the if statement.
var myElement = document.getElementById("myElement");
if(myElement){
// Element exists
}
When Python2.x sees a == b
, it tries the following.
type(b)
is a new-style class, and type(b)
is a subclass of type(a)
, and type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.type(a)
has overridden __eq__
(that is, type(a).__eq__
isn't object.__eq__
), then the result is a.__eq__(b)
.type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.__cmp__
. If it exists, the objects are equal iff it returns zero
.object.__eq__(a, b)
, which is True
iff a
and b
are the same object.If any of the special methods return NotImplemented
, Python acts as though the method didn't exist.
Note that last step carefully: if neither a
nor b
overloads ==
, then a == b
is the same as a is b
.
This error also occurs if you use four-space instead of two-space indentation.
e.g., the following would throw the error:
fields:
- metadata: {}
name: colName
nullable: true
whereas changing indentation to two-spaces would fix it:
fields:
- metadata: {}
name: colName
nullable: true
Based on @user's answer, you can just add this extension anywhere in your app code and have your selection color directly in storyboard editor for every cells of your app :
@IBDesignable extension UITableViewCell {
@IBInspectable var selectedColor: UIColor? {
set {
if let color = newValue {
selectedBackgroundView = UIView()
selectedBackgroundView!.backgroundColor = color
} else {
selectedBackgroundView = nil
}
}
get {
return selectedBackgroundView?.backgroundColor
}
}
}
EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:
import java.util.*;
import java.text.*;
public class Test {
public static void main(String[] args) throws InterruptedException {
Date date = new Date(1318386508000L);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
System.out.println(formatted);
format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
formatted = format.format(date);
System.out.println(formatted);
}
}
Output:
12/10/2011 02:28:28
12/10/2011 13:28:28
I would also suggest you start using Joda Time which is simply a much nicer date/time API...
EDIT: Note that if your system doesn't know about the Australia/Sydney
time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah")
it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName()
and see what it says... and check your code for typos too :)
You will have to build a CLR procedure that provides regex functionality, as this article illustrates.
Their example function uses VB.NET:
Imports System
Imports System.Data.Sql
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Collections 'the IEnumerable interface is here
Namespace SimpleTalk.Phil.Factor
Public Class RegularExpressionFunctions
'RegExIsMatch function
<SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
Public Shared Function RegExIsMatch( _
ByVal pattern As SqlString, _
ByVal input As SqlString, _
ByVal Options As SqlInt32) As SqlBoolean
If (input.IsNull OrElse pattern.IsNull) Then
Return SqlBoolean.False
End If
Dim RegExOption As New System.Text.RegularExpressions.RegExOptions
RegExOption = Options
Return RegEx.IsMatch(input.Value, pattern.Value, RegExOption)
End Function
End Class '
End Namespace
...and is installed in SQL Server using the following SQL (replacing '%'-delimted variables by their actual equivalents:
sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE
IF EXISTS ( SELECT 1
FROM sys.objects
WHERE object_id = OBJECT_ID(N'dbo.RegExIsMatch') )
DROP FUNCTION dbo.RegExIsMatch
go
IF EXISTS ( SELECT 1
FROM sys.assemblies asms
WHERE asms.name = N'RegExFunction ' )
DROP ASSEMBLY [RegExFunction]
CREATE ASSEMBLY RegExFunction
FROM '%FILE%'
GO
CREATE FUNCTION RegExIsMatch
(
@Pattern NVARCHAR(4000),
@Input NVARCHAR(MAX),
@Options int
)
RETURNS BIT
AS EXTERNAL NAME
RegExFunction.[SimpleTalk.Phil.Factor.RegularExpressionFunctions].RegExIsMatch
GO
--a few tests
---Is this card a valid credit card?
SELECT dbo.RegExIsMatch ('^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$','4241825283987487',1)
--is there a number in this string
SELECT dbo.RegExIsMatch( '\d','there is 1 thing I hate',1)
--Verifies number Returns 1
DECLARE @pattern VARCHAR(255)
SELECT @pattern ='[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]'
SELECT dbo.RegExIsMatch (@pattern, '1298-673-4192',1),
dbo.RegExIsMatch (@pattern,'A08Z-931-468A',1),
dbo.RegExIsMatch (@pattern,'[A90-123-129X',1),
dbo.RegExIsMatch (@pattern,'12345-KKA-1230',1),
dbo.RegExIsMatch (@pattern,'0919-2893-1256',1)
Running your code shows an image for me, after adjusting the path. Can you verify that your image path is correct, try absolute path for instance?
Use the CellMouseDown
event on the DataGridView
. From the event handler arguments you can determine which cell was clicked. Using the PointToClient()
method on the DataGridView you can determine the relative position of the pointer to the DataGridView, so you can pop up the menu in the correct location.
(The DataGridViewCellMouseEvent
parameter just gives you the X
and Y
relative to the cell you clicked, which isn't as easy to use to pop up the context menu.)
This is the code I used to get the mouse position, then adjust for the position of the DataGridView:
var relativeMousePosition = DataGridView1.PointToClient(Cursor.Position);
this.ContextMenuStrip1.Show(DataGridView1, relativeMousePosition);
The entire event handler looks like this:
private void DataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
// Ignore if a column or row header is clicked
if (e.RowIndex != -1 && e.ColumnIndex != -1)
{
if (e.Button == MouseButtons.Right)
{
DataGridViewCell clickedCell = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];
// Here you can do whatever you want with the cell
this.DataGridView1.CurrentCell = clickedCell; // Select the clicked cell, for instance
// Get mouse position relative to the vehicles grid
var relativeMousePosition = DataGridView1.PointToClient(Cursor.Position);
// Show the context menu
this.ContextMenuStrip1.Show(DataGridView1, relativeMousePosition);
}
}
}
If you just want the bitmap, This too works
InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();
sample uri : content://media/external/images/media/12345
There is merge!
.
h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}
Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.
Something like this maybe:
jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);
Then create new JSONObject, put the other values into it and add it to the JSONArray:
jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);
The Bootstrap Collapse has some Events that you can react to:
$(document).ready(function(){
$('#accordProfile').on('shown', function () {
$(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-up");
});
$('#accordProfile').on('hidden', function () {
$(".icon-chevron-up").removeClass("icon-chevron-up").addClass("icon-chevron-down");
});
});
if it crashes on the delete
line then you have almost certainly somehow corrupted the heap. We would need to see more code to diagnose the problem since the example you presented has no errors.
Perhaps you have a buffer overflow on the heap which corrupted the heap structures or even something as simple as a "double free" (or in the c++ case "double delete").
Also, as The Fuzz noted, you may have an error in your destructor as well.
And yes, it is completely normal and expected for delete
to invoke the destructor, that is in fact one of its two purposes (call destructor then free memory).
RESTful API (Route):
rtr.route('/testing')
.get((req, res)=>{
res.render('test')
})
.post((req, res, next)=>{
res.render('test')
})
AJAX Code:
$(function(){
$('#anyid').on('click', function(e){
e.preventDefault()
$.ajax({
url: '/testing',
method: 'GET',
contentType: 'application/json',
success: function(res){
console.log('GET Request')
}
})
})
$('#anyid').on('submit', function(e){
e.preventDefault()
$.ajax({
url: '/testing',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
info: "put data here to pass in JSON format."
}),
success: function(res){
console.log('POST Request')
}
})
})
})
I don't know about web.config or IIS. But I believe that from C# code you can do it like
Session.Timeout = 60; // 60 is number of minutes
For Java:
X, exactly n times: X{n}
X, at least n times: X{n,}
X, at least n but not more than m times: X{n,m}
The steps you listed will work, but there's a longer way that gives you more options:
git checkout dmgr2 # gets you "on branch dmgr2"
git fetch origin # gets you up to date with origin
git merge origin/master
The fetch
command can be done at any point before the merge
, i.e., you can swap the order of the fetch and the checkout, because fetch
just goes over to the named remote (origin
) and says to it: "gimme everything you have that I don't", i.e., all commits on all branches. They get copied to your repository, but named origin/branch
for any branch named branch
on the remote.
At this point you can use any viewer (git log
, gitk
, etc) to see "what they have" that you don't, and vice versa. Sometimes this is only useful for Warm Fuzzy Feelings ("ah, yes, that is in fact what I want") and sometimes it is useful for changing strategies entirely ("whoa, I don't want THAT stuff yet").
Finally, the merge
command takes the given commit, which you can name as origin/master
, and does whatever it takes to bring in that commit and its ancestors, to whatever branch you are on when you run the merge
. You can insert --no-ff
or --ff-only
to prevent a fast-forward, or merge only if the result is a fast-forward, if you like.
When you use the sequence:
git checkout dmgr2
git pull origin master
the pull
command instructs git to run git fetch
, and then the moral equivalent of git merge origin/master
. So this is almost the same as doing the two steps by hand, but there are some subtle differences that probably are not too concerning to you. (In particular the fetch
step run by pull
brings over only origin/master
, and it does not update the ref in your repo:1 any new commits winds up referred-to only by the special FETCH_HEAD
reference.)
If you use the more-explicit git fetch origin
(then optionally look around) and then git merge origin/master
sequence, you can also bring your own local master
up to date with the remote, with only one fetch
run across the network:
git fetch origin
git checkout master
git merge --ff-only origin/master
git checkout dmgr2
git merge --no-ff origin/master
for instance.
1This second part has been changed—I say "fixed"—in git 1.8.4, which now updates "remote branch" references opportunistically. (It was, as the release notes say, a deliberate design decision to skip the update, but it turns out that more people prefer that git update it. If you want the old remote-branch SHA-1, it defaults to being saved in, and thus recoverable from, the reflog. This also enables a new git 1.9/2.0 feature for finding upstream rebases.)
To add previous iOS simulator to Xcode 4.2, you need old xcode_3.2.6_and_ios_sdk_4.3.dmg (or similar version) installer file and do as following:
Now there are a list of your installed simulator.
Try this:
fname = "feed.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
Back to your code:
fname = "feed.txt"
fname = open('feed.txt', 'r')
what's the point of this? fname
is a string first and then a file object. You don't really use the string defined in the first line and you should use one variable for one thing only: either a string or a file object.
for line in feed:
lines = line.split('\n')
line
is one line from the file. It does not make sense to split('\n')
it.
For swift 2.0:
let cacheSizeMemory = 4*1024*1024; // 4MB
let cacheSizeDisk = 32*1024*1024; // 32MB
let sharedCache = NSURLCache(memoryCapacity: cacheSizeMemory, diskCapacity: cacheSizeDisk, diskPath: "nsurlcache")
NSURLCache.setSharedURLCache(sharedCache)
You shouldn't be calling .ToString()
.
As the error message clearly states, you're writing a conditional in which one half is an IHtmlString
and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.
There is never a reason to call Html.Raw(...).ToString()
.
Html.Raw
returns an HtmlString
instance that wraps the original string.
The Razor page output knows not to escape HtmlString
instances.
However, calling HtmlString.ToString()
just returns the original string
value again; it doesn't accomplish anything.
Addressing cases that some of the other answers don't handle well:
Many of the solutions on this page involve polling Console.KeyAvailable
or blocking on Console.ReadKey
. While it's true that the .NET Console
is not very cooperative here, you can use Task.Run
to move towards a more modern Async
mode of listening.
The main issue to be aware of is that, by default, your console thread isn't set up for Async
operation--meaning that, when you fall out of the bottom of your main
function, instead of awaiting Async
completions, your AppDoman and process will end. A proper way to address this would be to use Stephen Cleary's AsyncContext to establish full Async
support in your single-threaded console program. But for simpler cases, like waiting for a keypress, installing a full trampoline may be overkill.
The example below would be for a console program used in some kind of iterative batch file. In this case, when the program is done with its work, normally it should exit without requiring a keypress, and then we allow an optional key press to prevent the app from exiting. We can pause the cycle to examine things, possibly resuming, or use the pause as a known 'control point' at which to cleanly break out of the batch file.
static void Main(String[] args)
{
Console.WriteLine("Press any key to prevent exit...");
var tHold = Task.Run(() => Console.ReadKey(true));
// ... do your console app activity ...
if (tHold.IsCompleted)
{
#if false // For the 'hold' state, you can simply halt forever...
Console.WriteLine("Holding.");
Thread.Sleep(Timeout.Infinite);
#else // ...or allow continuing to exit
while (Console.KeyAvailable)
Console.ReadKey(true); // flush/consume any extras
Console.WriteLine("Holding. Press 'Esc' to exit.");
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
;
#endif
}
}
The answer by Nick Mitchinson is for Bootstrap version 2.
If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-6">
<textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>
</div>
</div>
</div>
Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.
If you offer cbind
a set of arguments all of whom are vectors, you will get not a dataframe, but rather a matrix, in this case an all character matrix. They have different features. You can get a dataframe if some of your arguments remain dataframes, Try:
merger <- cbind(Date =as.character(Date),
weather1[ , c("High", "Low", "Avg..High", "Avg.Low")] ,
ScnMov =sale$Scanned.Movement[a] )
Change modalPresentationStyle
before presenting
vc.modalPresentationStyle = UIModalPresentationFullScreen;
Sometime ago I implemented an easy to use "download manager" library: PTDownloadManager. You could give it a shot!
This should work:
window.onload = function() {
document.getElementById('about').className = 'expand';
};
Or if you're using jQuery:
$(function() {
$('#about').addClass('expand');
});
sys.argv[0]
is not the first argument but the filename of the python program you are currently executing. I think you want sys.argv[1]
You may specify a comparer(IComparer implementation) as a parameter in Array.Sort, the order of sorting actually depends on comparer. The default comparer is used in ascending sorting
in your terminal
npm run build
and you host the dist folder. for more see this video
public class FormattedTablePrint {
public static void printRow(int[] row) {
for (int i : row) {
System.out.print(i);
System.out.print("\t");
}
System.out.println();
}
public static void main(String[] args) {
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++) {
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;
}
}
for(int[] row : twoDm) {
printRow(row);
}
}
}
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30
31 32 33 34 35
Of course, you might swap the 7 & 5 as mentioned in other answers, to get 7 per row.
This may be what you are looking for:
body>div {_x000D_
background: #aaa;_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
body>div>div {_x000D_
flex-grow: 1;_x000D_
width: 33%;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(even) {_x000D_
background: #23a;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(odd) {_x000D_
background: #49b;_x000D_
}
_x000D_
<div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
</div>
_x000D_
Ive a really hacky solution with this...
<style type="text/css">
input[type="file"]
{
width: 80px;
}
</style>
<input id="File1" type="file" />
The problem is the width attribute that is hiding the text field will obvously vary between browsers, vary between Windows XP themes and so on. Maybe its something you can work with though?...
I used Sorin Comanescu's solution, but hit a problem when trying to get the selected value. My combobox was a toolstrip combobox. I used the "combobox" property, which exposes a normal combobox.
I had a
Dictionary<Control, string> controls = new Dictionary<Control, string>();
Binding code (Sorin Comanescu's solution - worked like a charm):
controls.Add(pictureBox1, "Image");
controls.Add(dgvText, "Text");
cbFocusedControl.ComboBox.DataSource = new BindingSource(controls, null);
cbFocusedControl.ComboBox.ValueMember = "Key";
cbFocusedControl.ComboBox.DisplayMember = "Value";
The problem was that when I tried to get the selected value, I didn't realize how to retrieve it. After several attempts I got this:
var control = ((KeyValuePair<Control, string>) cbFocusedControl.ComboBox.SelectedItem).Key
Hope it helps someone else!
You can write like this in JavaScript or jQuery Ajax and call the file
$('#btn').click(function(){_x000D_
$.ajax({_x000D_
url:'test.php?call=true',_x000D_
type:'GET',_x000D_
success:function(data){_x000D_
body.append(data);_x000D_
}_x000D_
});_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>_x000D_
<form method='get' >_x000D_
_x000D_
<input type="button" id="btn" value="click">_x000D_
</form>_x000D_
_x000D_
<?php_x000D_
if(isset($_GET['call'])){_x000D_
_x000D_
function anyfunction(){_x000D_
echo "added";_x000D_
_x000D_
// Your funtion code_x000D_
}_x000D_
}_x000D_
?>
_x000D_
Just put quotes around the Environment variable (as you have done) :
if "%DevEnvDir%" == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"
but it's the way you put opening bracket without a space that is confusing it.
Works for me...
C:\if "%gtk_basepath%" == "C:\Program Files\GtkSharp\2.12\" (echo yes)
yes
In the latest browsers (IE9+) you can also use document.head:
Example:
var favicon = document.createElement('link');
favicon.id = 'myFavicon';
favicon.rel = 'shortcut icon';
favicon.href = 'http://www.test.com/my-favicon.ico';
document.head.appendChild(favicon);
Depending on what you want to accomplish within the loop, iterate over one of these instead:
countries.keySet()
countries.entrySet()
countries.values()
This can happen if you don't have mod_proxy_http
enabled
sudo a2enmod proxy_http
For me to get my https based load balancer working, i had to enable the following:
sudo a2enmod ssl
sudo a2enmod proxy
sudo a2enmod proxy_balancer
sudo a2enmod proxy_http
In case you want to get fancy by outputting an *
for each character they type, you can do something like this (using andreas' read -s
solution):
unset password;
while IFS= read -r -s -n1 pass; do
if [[ -z $pass ]]; then
echo
break
else
echo -n '*'
password+=$pass
fi
done
Without being fancy
echo "Please enter your username";
read username;
echo "Please enter your password";
stty -echo
read password;
stty echo
It appears that it is possible to track a smart phone without using GPS.
Sources:
Primary: "PinMe: Tracking a Smartphone User around the World"
Secondary: "How to Track a Cellphone Without GPS—or Consent"
I have not yet found a link to the team's final code. When I do I will post, if another has not done so.
I would use a composite (multi-column) key.
CREATE TABLE INFO (
t1ID INT,
t2ID INT,
PRIMARY KEY (t1ID, t2ID)
)
This way you can have t1ID and t2ID as foreign keys pointing to their respective tables as well.
You can subclass HandleErrorAttribute
and override its OnException
member (no need to copy) so that it logs the exception with ELMAH and only if the base implementation handles it. The minimal amount of code you need is as follows:
using System.Web.Mvc;
using Elmah;
public class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
public override void OnException(ExceptionContext context)
{
base.OnException(context);
if (!context.ExceptionHandled)
return;
var httpContext = context.HttpContext.ApplicationInstance.Context;
var signal = ErrorSignal.FromContext(httpContext);
signal.Raise(context.Exception, httpContext);
}
}
The base implementation is invoked first, giving it a chance to mark the exception as being handled. Only then is the exception signaled. The above code is simple and may cause issues if used in an environment where the HttpContext
may not be available, such as testing. As a result, you will want code that is that is more defensive (at the cost of being slightly longer):
using System.Web;
using System.Web.Mvc;
using Elmah;
public class HandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
public override void OnException(ExceptionContext context)
{
base.OnException(context);
if (!context.ExceptionHandled // if unhandled, will be logged anyhow
|| TryRaiseErrorSignal(context) // prefer signaling, if possible
|| IsFiltered(context)) // filtered?
return;
LogException(context);
}
private static bool TryRaiseErrorSignal(ExceptionContext context)
{
var httpContext = GetHttpContextImpl(context.HttpContext);
if (httpContext == null)
return false;
var signal = ErrorSignal.FromContext(httpContext);
if (signal == null)
return false;
signal.Raise(context.Exception, httpContext);
return true;
}
private static bool IsFiltered(ExceptionContext context)
{
var config = context.HttpContext.GetSection("elmah/errorFilter")
as ErrorFilterConfiguration;
if (config == null)
return false;
var testContext = new ErrorFilterModule.AssertionHelperContext(
context.Exception,
GetHttpContextImpl(context.HttpContext));
return config.Assertion.Test(testContext);
}
private static void LogException(ExceptionContext context)
{
var httpContext = GetHttpContextImpl(context.HttpContext);
var error = new Error(context.Exception, httpContext);
ErrorLog.GetDefault(httpContext).Log(error);
}
private static HttpContext GetHttpContextImpl(HttpContextBase context)
{
return context.ApplicationInstance.Context;
}
}
This second version will try to use error signaling from ELMAH first, which involves the fully configured pipeline like logging, mailing, filtering and what have you. Failing that, it attempts to see whether the error should be filtered. If not, the error is simply logged. This implementation does not handle mail notifications. If the exception can be signaled then a mail will be sent if configured to do so.
You may also have to take care that if multiple HandleErrorAttribute
instances are in effect then duplicate logging does not occur, but the above two examples should get your started.
I just had this issue building react-native app when I try to install Pod. I had to export 2 variables:
export CC=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
CPP='/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -E'
If you are searching literally the way to return a JSON list in flask and you are completly sure that your variable is a list then the easy way is (where bin is a list of 1's and 0's):
return jsonify({'ans':bin}), 201
Finally, in your client you will obtain something like
{ "ans": [ 0.0, 0.0, 1.0, 1.0, 0.0 ] }
You have to do it like this:
If strMyString.Contains("Something") OrElse strMyString.Contains("Something2") Then
'[Put Code Here]
End if
Try it like this:
Sub testIt()
Dim r As Long, endRow as Long, pasteRowIndex As Long
endRow = 10 ' of course it's best to retrieve the last used row number via a function
pasteRowIndex = 1
For r = 1 To endRow 'Loop through sheet1 and search for your criteria
If Cells(r, Columns("B").Column).Value = "YourCriteria" Then 'Found
'Copy the current row
Rows(r).Select
Selection.Copy
'Switch to the sheet where you want to paste it & paste
Sheets("Sheet2").Select
Rows(pasteRowIndex).Select
ActiveSheet.Paste
'Next time you find a match, it will be pasted in a new row
pasteRowIndex = pasteRowIndex + 1
'Switch back to your table & continue to search for your criteria
Sheets("Sheet1").Select
End If
Next r
End Sub
I had the same problem. I uninstalled the 6.8.14 and installed back older version 5.6.8, and it worked.
Try this example
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
http://php.net/manual/en/function.json-decode.php
NB - two negatives makes a positive . :)
Dan Abramov's answer is right about redux-thunk
but I will talk a bit more about redux-saga that is quite similar but more powerful.
redux-thunk
is imperative / redux-saga
is declarativeWhen you have a thunk in your hands, like an IO monad or a promise, you can't easily know what it will do once you execute. The only way to test a thunk is to execute it, and mock the dispatcher (or the whole outside world if it interacts with more stuff...).
If you are using mocks, then you are not doing functional programming.
Seen through the lens of side-effects, mocks are a flag that your code is impure, and in the functional programmer's eye, proof that something is wrong. Instead of downloading a library to help us check the iceberg is intact, we should be sailing around it. A hardcore TDD/Java guy once asked me how you do mocking in Clojure. The answer is, we usually don't. We usually see it as a sign we need to refactor our code.
The sagas (as they got implemented in redux-saga
) are declarative and like the Free monad or React components, they are much easier to test without any mock.
See also this article:
in modern FP, we shouldn’t write programs — we should write descriptions of programs, which we can then introspect, transform, and interpret at will.
(Actually, Redux-saga is like a hybrid: the flow is imperative but the effects are declarative)
There is a lot of confusion in the frontend world on how some backend concepts like CQRS / EventSourcing and Flux / Redux may be related, mostly because in Flux we use the term "action" which can sometimes represent both imperative code (LOAD_USER
) and events (USER_LOADED
). I believe that like event-sourcing, you should only dispatch events.
Imagine an app with a link to a user profile. The idiomatic way to handle this with each middleware would be:
redux-thunk
<div onClick={e => dispatch(actions.loadUserProfile(123)}>Robert</div>
function loadUserProfile(userId) {
return dispatch => fetch(`http://data.com/${userId}`)
.then(res => res.json())
.then(
data => dispatch({ type: 'USER_PROFILE_LOADED', data }),
err => dispatch({ type: 'USER_PROFILE_LOAD_FAILED', err })
);
}
redux-saga
<div onClick={e => dispatch({ type: 'USER_NAME_CLICKED', payload: 123 })}>Robert</div>
function* loadUserProfileOnNameClick() {
yield* takeLatest("USER_NAME_CLICKED", fetchUser);
}
function* fetchUser(action) {
try {
const userProfile = yield fetch(`http://data.com/${action.payload.userId }`)
yield put({ type: 'USER_PROFILE_LOADED', userProfile })
}
catch(err) {
yield put({ type: 'USER_PROFILE_LOAD_FAILED', err })
}
}
This saga translates to:
every time a username gets clicked, fetch the user profile and then dispatch an event with the loaded profile.
As you can see, there are some advantages of redux-saga
.
The usage of takeLatest
permits to express that you are only interested to get the data of the last username clicked (handle concurrency problems in case the user click very fast on a lot of usernames). This kind of stuff is hard with thunks. You could have used takeEvery
if you don't want this behavior.
You keep action creators pure. Note it's still useful to keep actionCreators (in sagas put
and components dispatch
), as it might help you to add action validation (assertions/flow/typescript) in the future.
Your code becomes much more testable as the effects are declarative
You don't need anymore to trigger rpc-like calls like actions.loadUser()
. Your UI just needs to dispatch what HAS HAPPENED. We only fire events (always in the past tense!) and not actions anymore. This means that you can create decoupled "ducks" or Bounded Contexts and that the saga can act as the coupling point between these modular components.
This means that your views are more easy to manage because they don't need anymore to contain that translation layer between what has happened and what should happen as an effect
For example imagine an infinite scroll view. CONTAINER_SCROLLED
can lead to NEXT_PAGE_LOADED
, but is it really the responsibility of the scrollable container to decide whether or not we should load another page? Then he has to be aware of more complicated stuff like whether or not the last page was loaded successfully or if there is already a page that tries to load, or if there is no more items left to load? I don't think so: for maximum reusability the scrollable container should just describe that it has been scrolled. The loading of a page is a "business effect" of that scroll
Some might argue that generators can inherently hide state outside of redux store with local variables, but if you start to orchestrate complex things inside thunks by starting timers etc you would have the same problem anyway. And there's a select
effect that now permits to get some state from your Redux store.
Sagas can be time-traveled and also enables complex flow logging and dev-tools that are currently being worked on. Here is some simple async flow logging that is already implemented:
Sagas are not only replacing redux thunks. They come from backend / distributed systems / event-sourcing.
It is a very common misconception that sagas are just here to replace your redux thunks with better testability. Actually this is just an implementation detail of redux-saga. Using declarative effects is better than thunks for testability, but the saga pattern can be implemented on top of imperative or declarative code.
In the first place, the saga is a piece of software that permits to coordinate long running transactions (eventual consistency), and transactions across different bounded contexts (domain driven design jargon).
To simplify this for frontend world, imagine there is widget1 and widget2. When some button on widget1 is clicked, then it should have an effect on widget2. Instead of coupling the 2 widgets together (ie widget1 dispatch an action that targets widget2), widget1 only dispatch that its button was clicked. Then the saga listen for this button click and then update widget2 by dispaching a new event that widget2 is aware of.
This adds a level of indirection that is unnecessary for simple apps, but make it more easy to scale complex applications. You can now publish widget1 and widget2 to different npm repositories so that they never have to know about each others, without having them to share a global registry of actions. The 2 widgets are now bounded contexts that can live separately. They do not need each others to be consistent and can be reused in other apps as well. The saga is the coupling point between the two widgets that coordinate them in a meaningful way for your business.
Some nice articles on how to structure your Redux app, on which you can use Redux-saga for decoupling reasons:
I want my components to be able to trigger the display of in-app notifications. But I don't want my components to be highly coupled to the notification system that has its own business rules (max 3 notifications displayed at the same time, notification queueing, 4 seconds display-time etc...).
I don't want my JSX components to decide when a notification will show/hide. I just give it the ability to request a notification, and leave the complex rules inside the saga. This kind of stuff is quite hard to implement with thunks or promises.
I've described here how this can be done with saga
The term saga comes from the backend world. I initially introduced Yassine (the author of Redux-saga) to that term in a long discussion.
Initially, that term was introduced with a paper, the saga pattern was supposed to be used to handle eventual consistency in distributed transactions, but its usage has been extended to a broader definition by backend developers so that it now also covers the "process manager" pattern (somehow the original saga pattern is a specialized form of process manager).
Today, the term "saga" is confusing as it can describe 2 different things. As it is used in redux-saga, it does not describe a way to handle distributed transactions but rather a way to coordinate actions in your app. redux-saga
could also have been called redux-process-manager
.
See also:
If you don't like the idea of using generators but you are interested by the saga pattern and its decoupling properties, you can also achieve the same with redux-observable which uses the name epic
to describe the exact same pattern, but with RxJS. If you're already familiar with Rx, you'll feel right at home.
const loadUserProfileOnNameClickEpic = action$ =>
action$.ofType('USER_NAME_CLICKED')
.switchMap(action =>
Observable.ajax(`http://data.com/${action.payload.userId}`)
.map(userProfile => ({
type: 'USER_PROFILE_LOADED',
userProfile
}))
.catch(err => Observable.of({
type: 'USER_PROFILE_LOAD_FAILED',
err
}))
);
yield put(someActionThunk)
if it makes sense.If you are frightened of using Redux-saga (or Redux-observable) but just need the decoupling pattern, check redux-dispatch-subscribe: it permits to listen to dispatches and trigger new dispatches in listener.
const unsubscribe = store.addDispatchListener(action => {
if (action.type === 'ping') {
store.dispatch({ type: 'pong' });
}
});
I had a similar problem and found the following command to work:
sudo systemctl stop tomcat
After running this command you can type the following to verify that it is "disabled":
systemctl list-units
I know this is a very old question, but this worked for me:
UPDATE TABLE SET FIELD1 =
CASE
WHEN FIELD1 = Condition1 THEN 'Result1'
WHEN FIELD1 = Condition2 THEN 'Result2'
WHEN FIELD1 = Condition3 THEN 'Result3'
END;
Regards
If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.
<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>
install this package
https://github.com/nilpahar/custom-migration/
and run this command.
php artisan migrate:custom -f migration_name
Since you're using knockout, you should consider using the knockout utility function arrayMap()
and it's other array utility functions.
Here's a listing of array utility functions and their equivalent LINQ methods:
arrayFilter() -> Where()
arrayFirst() -> First()
arrayForEach() -> (no direct equivalent)
arrayGetDistictValues() -> Distinct()
arrayIndexOf() -> IndexOf()
arrayMap() -> Select()
arrayPushAll() -> (no direct equivalent)
arrayRemoveItem() -> (no direct equivalent)
compareArrays() -> (no direct equivalent)
So what you could do in your example is this:
var mapped = ko.utils.arrayMap(selectedFruits, function (fruit) {
return fruit.id;
});
If you want a LINQ like interface in javascript, you could use a library such as linq.js which offers a nice interface to many of the LINQ methods.
var mapped = Enumerable.From(selectedFruits)
.Select("$.id") // 1 of 3 different ways to specify a selector function
.ToArray();
Async is suitable if your script doesn’t contains DOM manipulation and other scripts doesn’t depend upon on this. Eg: bootstrap cdn,jquery
Defer is suitable if your script contains DOM manipulation and other scripts depend upon on this.
Eg: <script src=”createfirst.js”> //let this will create element <script src=”showfirst.js”> //after createfirst create element it will show that.
Thus make it:
Eg: <script defer src=”createfirst.js”> //let this will create element <script defer src=”showfirst.js”>
//after createfirst create element it will
This will execute scripts in order.
But if i made:
Eg: <script async src=”createfirst.js”> //let this will create element <script defer src=”showfirst.js”>
//after createfirst create element it will
Then, this code might result unexpected results. Coz: if html parser access createfirst script.It won’t stop DOM creation and starts downloading code from src .Once src got resolved/code got downloaded, it will execute immediately parallel with DOM.
What if showfirst.js execute first than createfirst.js.This might be possible if createfirst takes long time (Assume after DOM parsing finished).Then, showfirst will execute immediately.
In Charles, go to Proxy>>Proxy Settings and select the SSL tab. Add your host to the list of Locations.
For example, if your secure call is going to https://secure.example.com, you can enter secure.example.com, or *.example.com.
Once the above is in place, you may need to right-click on the call in the main Charles window and select the SSL Proxying option.
Hope this helps.
Several answers show dangerous examples. OP's example [ $a == $b ]
specifically used unquoted variable substitution (as of Oct '17 edit). For [...]
that is safe for string equality.
But if you're going to enumerate alternatives like [[...]]
, you must inform also that the right-hand-side must be quoted. If not quoted, it is a pattern match! (From bash man page: "Any part of the pattern may be quoted to force it to be matched as a string.").
Here in bash, the two statements yielding "yes" are pattern matching, other three are string equality:
$ rht="A*"
$ lft="AB"
$ [ $lft = $rht ] && echo yes
$ [ $lft == $rht ] && echo yes
$ [[ $lft = $rht ]] && echo yes
yes
$ [[ $lft == $rht ]] && echo yes
yes
$ [[ $lft == "$rht" ]] && echo yes
$
You might be looking for a List
? Either LinkedList
or ArrayList
are good classes to take a look at. You can then call toArray()
to get the list as an array.
For Jar
Add pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Try this:
SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL
To test it using a new date instance:
SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL
Output is: 06-10-2015 22:00, which is the previous day.
I followed many links including the official documentation, however it all ended up in this error:
Requires: container-selinux >= 2.9
You could try using --skip-broken to work around the problem
You could try running: rpm -Va --nofiles --nodigest
The only way it worked for me is as follows (yum upgrade
worked I guess):
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
yum upgrade docker-ce
Here is how you can use Contains
to achieve what you want:
buildingStatus.Select(item => item.GetCharValue()).Contains(v.Status)
this will return a Boolean value.
Based on Why does FtpWebRequest download files from the root directory? Can this cause a 553 error?, I wrote a PowerShell script that enabled to download a file from a FTP-Server via explicit FTP over TLS:
# Config
$Username = "USERNAME"
$Password = "PASSWORD"
$LocalFile = "C:\PATH_TO_DIR\FILNAME.EXT"
#e.g. "C:\temp\somefile.txt"
$RemoteFile = "ftp://PATH_TO_REMOTE_FILE"
#e.g. "ftp://ftp.server.com/home/some/path/somefile.txt"
try{
# Create a FTPWebRequest
$FTPRequest = [System.Net.FtpWebRequest]::Create($RemoteFile)
$FTPRequest.Credentials = New-Object System.Net.NetworkCredential($Username,$Password)
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$FTPRequest.UseBinary = $true
$FTPRequest.KeepAlive = $false
$FTPRequest.EnableSsl = $true
# Send the ftp request
$FTPResponse = $FTPRequest.GetResponse()
# Get a download stream from the server response
$ResponseStream = $FTPResponse.GetResponseStream()
# Create the target file on the local system and the download buffer
$LocalFileFile = New-Object IO.FileStream ($LocalFile,[IO.FileMode]::Create)
[byte[]]$ReadBuffer = New-Object byte[] 1024
# Loop through the download
do {
$ReadLength = $ResponseStream.Read($ReadBuffer,0,1024)
$LocalFileFile.Write($ReadBuffer,0,$ReadLength)
}
while ($ReadLength -ne 0)
}catch [Exception]
{
$Request = $_.Exception
Write-host "Exception caught: $Request"
}
Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.
Anyway, I'd just do this:
public Integer tryParse(Object obj) {
Integer retVal;
try {
retVal = Integer.parseInt((String) obj);
} catch (NumberFormatException nfe) {
retVal = 0; // or null if that is your preference
}
return retVal;
}
I am from .net background. However, java/c# are more/less same.
If you instantiate a non-primitive type (array in your case), it won't be null.
e.g. int[] numbers = new int[3];
In this case, the space is allocated & each of the element has a default value of 0.
It will be null
, when you don't new
it up.
e.g.
int[] numbers = null; // changed as per @Joachim's suggestion.
if (numbers == null)
{
System.out.println("yes, it is null. Please new it up");
}
You can used following code that can solve your problem.
Matrix matrix = new Matrix();
matrix.postScale(0.5f, 0.5f);
Bitmap croppedBitmap = Bitmap.createBitmap(bitmapOriginal, 100, 100,100, 100, matrix, true);
Above method do postScalling of image before cropping, so you can get best result with cropped image without getting OOM error.
For more detail you can refer this blog
Use Math.round(value)
then after type cast it to integer.
float a = 8.61f;
int b = (int)Math.round(a);
[i for i, v in enumerate(L) if v[0] == 53]
There are a couple of ways that you can accomplish this. You can do the following:
<li>
@Html.ActionLink("Clients", "Index", "User", new { @class = "elements" }, null)
</li>
or this:
<li>
<a href="@Url.Action("Index", "Users")" class="elements">
<span>Clients</span>
</a>
</li>
Lately I do the following:
<a href="@Url.Action("Index", null, new { area = string.Empty, controller = "User" }, Request.Url.Scheme)">
<span>Clients</span>
</a>
The result would have http://localhost/10000
(or with whatever port you are using) to be appended to the URL structure like:
http://localhost:10000/Users
I hope this helps.
There's always the "brute force":
Search->File
Type the following in "Containing text" -> ^.*$
. Then check the "Regular Expression" checkbox
Type the following in "File name patterns" -> *.java
Click "Search"
Check the number of matches in the "Search" Tab.
I launched ubuntu Xampp server on AWS amazon. And met the same problem with FTP, even though add user to group ftp SFTP and set permissions, owner group of htdocs folder. Finally find the reason in inbound rules in security group, added All TCP, 0 - 65535 rule(0.0.0.0/0,::/0) , then working right!
You could use cut
df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf),
labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))
set.seed(24)
df <- data.frame(value= sample(0:2500, 100, replace=TRUE))
Can be usefull.
public boolean deleteAllFood() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
int affectedRows = db.delete(DBHelper.TABLE_NAME_FOOD, null, null);
return affectedRows > 0;
}
public class DBProgram {
private static DBProgram INSTANCE;
private Context context;
private DBHelper dbHelper;
private DBProgram(Context context) {
// burda bu methodu kullanan activity ile eilestiriyoruz
this.dbHelper = new DBHelper(context);
}
public static synchronized DBProgram getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = new DBProgram(context);
}
return INSTANCE;
}
//**********************************************
public boolean updateById(ProgramModel program) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.COLUM_NAME_P, program.getProgName());
contentValues.put(DBHelper.COLUM_DAY_P, program.getDay());
contentValues.put(DBHelper.COLUMN_WEIGHT_P, program.getWeight());
contentValues.put(DBHelper.COLUMN_SET_P, program.getSet());
contentValues.put(DBHelper.COLUMN_REPETITION_P, program.getRepetition());
int affectedRows = database.update(DBHelper.TABLE_NAME_PROGRAM, contentValues, "PROG_ID_P = ?", new String[]{String.valueOf(program.getId())});
return affectedRows > 0;
}
//**********************************************
//**********************************************
// TODO
public boolean deleteProgramById(int id) {
SQLiteDatabase database = dbHelper.getReadableDatabase();
int affectedRows = database.delete(DBHelper.TABLE_NAME_PROGRAM, DBHelper.COLUMN_ID_P + "= ?", new String[]{String.valueOf(id)});
// return bize etkilenen sira sayisiniini temsil eder
return affectedRows > 0;
}
//**********************************************
//***************************************************
public boolean deleteProgramByName(String progName) {
SQLiteDatabase database = dbHelper.getReadableDatabase();
final String whereClause = DBHelper.COLUM_NAME_P + "=?";
final String whereArgs[] = {progName};
int affectedRows = database.delete(DBHelper.TABLE_NAME_PROGRAM, whereClause, whereArgs);
return affectedRows > 0;
}
//***************************************************
//************************************** get Meal
// TODO WEB Get All Meals
public List<ProgramModel> getAllProgram(String name) {
List<ProgramModel> foodList = new ArrayList<>();
ProgramModel food;
SQLiteDatabase database = dbHelper.getReadableDatabase();
final String kolonlar[] = {DBHelper.COLUMN_ID_P,
DBHelper.COLUM_NAME_P,
DBHelper.COLUM_DAY_P,
DBHelper.COLUMN_WEIGHT_P,
DBHelper.COLUMN_SET_P,
DBHelper.COLUMN_REPETITION_P};
final String whereClause = DBHelper.COLUM_DAY_P + "=?";
final String whereArgs[] = {name};
Cursor cursor = database.query(DBHelper.TABLE_NAME_PROGRAM, kolonlar, whereClause, whereArgs, null, null, null);
while (cursor.moveToNext()) {
food = new ProgramModel();
food.setId(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_ID_P)));
food.setProgName(cursor.getString(cursor.getColumnIndex(DBHelper.COLUM_NAME_P)));
food.setDay(cursor.getString(cursor.getColumnIndex(DBHelper.COLUM_DAY_P)));
food.setWeight(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_WEIGHT_P)));
food.setSet(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_SET_P)));
food.setRepetition(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_REPETITION_P)));
foodList.add(food);
}
database.close();
cursor.close();
return foodList;
}
//**************************************
//**************************************insert FOOD
//TODO LOCAL insert Foods
public boolean insertProgram(ProgramModel favorite) {
boolean result = false;
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.COLUM_NAME_P, favorite.getProgName());
contentValues.put(DBHelper.COLUM_DAY_P, favorite.getDay());
contentValues.put(DBHelper.COLUMN_WEIGHT_P, favorite.getWeight());
contentValues.put(DBHelper.COLUMN_SET_P, favorite.getSet());
contentValues.put(DBHelper.COLUMN_REPETITION_P, favorite.getRepetition());
SQLiteDatabase database = dbHelper.getWritableDatabase();
long id = database.insert(DBHelper.TABLE_NAME_PROGRAM, null, contentValues);
if (id != 1) {
result = true;
}
database.close();
return result;
}
//***************************************************
// ******************************* SQLITE HELPER CLASS ******************
private class DBHelper extends SQLiteOpenHelper {
private final Context context;
private static final String DATABASE_NAME = "PROGRAM_INFO";
private static final String TABLE_NAME_PROGRAM = "PROGRAM";
private static final int DATABASE_VERSION = 2;
// FOOD
private static final String COLUMN_ID_P = "PROG_ID_P";
private static final String COLUM_NAME_P = "PROG_NAME_P";
private static final String COLUM_DAY_P = "PROG_DAY_P";
private static final String COLUMN_WEIGHT_P = "PROG_WEIGHT_P";
private static final String COLUMN_SET_P = "PROG_SET_P";
private static final String COLUMN_REPETITION_P = "PROG_REPETITION_P";
private final String CREATE_TABLE_PROGRAM = "CREATE TABLE " + TABLE_NAME_PROGRAM +
" (" + COLUMN_ID_P + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUM_NAME_P + " TEXT, "
+ COLUM_DAY_P + " TEXT, "
+ COLUMN_WEIGHT_P + " INTEGER, "
+ COLUMN_SET_P + " INTEGER, "
+ COLUMN_REPETITION_P + " INTEGER)";
private static final String DROP_TABLE_PROGRAM = "DROP TABLE IF EXIST " + TABLE_NAME_PROGRAM;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PROGRAM);
Util.showMessage(context, "Database Created");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE_PROGRAM);
Util.showMessage(context, "Database Upgrated");
onCreate(db);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
super.onDowngrade(db, oldVersion, newVersion);
}
}
}
I was facing same issue in my Spring Integration project. I added below JSON dependencies in pom.xml file. It works for me.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
A list of versions can be found here: https://mvnrepository.com/artifact/org.json/json
In a comment to one of the answers you mention that to_date with a format doesn't help. In another comment you explain that the table is accessed via DBLINK.
So obviously the other system contains an invalid date that Oracle cannot accept. Fix this in the other dbms (or whatever you dblink to) and your query will work.
Having said this, I agree with the others: always use to_date with a format to convert a string literal to a date. Also never use only two digits for a year. For example '23/04/49' means 2049 in your system (format RR), but it confuses the reader (as you see from the answers suggesting a format with YY).
The photos
property is an optional array and must be unwrapped before accessing its elements (the same as you do to get the count
property of the array):
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos![i].url
}
I use the bcp utility. (Bulk Copy Program) I load about 1.5 million text records each month. Each text record is 800 characters wide. On my server, it takes about 30 seconds to add the 1.5 million text records into a SQL Server table.
The instructions for bcp are at http://msdn.microsoft.com/en-us/library/ms162802.aspx
My way is @Html.CheckBoxFor(model => model.As, new { @value= "true" })
(meaning is checked)
Check if pip has been cached on another path, to do so, call $ which pip and check that the path is different from the one prompted in the error, if that's the case run:
$ hash -r
When the cache is clear, pip will be working again. reference: http://cheng.logdown.com/posts/2015/06/14/-usr-bin-pip-no-such-file-or-directory
brew install maven
Please ensure that you've installed the latest Xcode and Command Line tools.
xcode-select --install